hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
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
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
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
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
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
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
1c3be38f9a2e2b8f10e434b26589fe509b0b9df5
1,130
py
Python
src/hexlet/fs/__init__.py
hexlet-components/python-immutable-fs-trees
992df582993469da4437434fad09fe8fefbaae68
[ "0BSD" ]
3
2020-09-24T17:13:01.000Z
2022-01-27T18:58:41.000Z
src/hexlet/fs/__init__.py
hexlet-components/python-immutable-fs-trees
992df582993469da4437434fad09fe8fefbaae68
[ "0BSD" ]
3
2020-11-11T15:07:40.000Z
2022-01-25T20:54:59.000Z
src/hexlet/fs/__init__.py
hexlet-components/python-immutable-fs-trees
992df582993469da4437434fad09fe8fefbaae68
[ "0BSD" ]
7
2020-09-13T15:33:16.000Z
2022-01-19T03:08:36.000Z
# coding: utf-8 __all__ = ( 'mkfile', 'mkdir', 'is_file', 'is_directory', ) def mkfile(name, meta={}): """Return file node.""" return { 'name': name, 'meta': meta, 'type': 'file' } def mkdir(name, children=[], meta={}): """Return directory node.""" return { 'name': name, 'children': children, 'meta': meta, 'type': 'directory' } def is_directory(node): """Check is node a directory.""" return node.get('type') == 'directory' def is_file(node): """Check is node a file.""" return node.get('type') == 'file' def get_children(directory): """Return children of node.""" return directory.get('children') def get_meta(node): """Return meta of node.""" return node.get('meta') def get_name(node): """Return name of node.""" return node.get('name') def flatten(tree): result = [] def walk(subtree): for item in subtree: if isinstance(item, list): walk(item) else: result.append(item) walk(tree) return result
17.121212
42
0.533628
__all__ = ( 'mkfile', 'mkdir', 'is_file', 'is_directory', ) def mkfile(name, meta={}): return { 'name': name, 'meta': meta, 'type': 'file' } def mkdir(name, children=[], meta={}): return { 'name': name, 'children': children, 'meta': meta, 'type': 'directory' } def is_directory(node): return node.get('type') == 'directory' def is_file(node): return node.get('type') == 'file' def get_children(directory): return directory.get('children') def get_meta(node): return node.get('meta') def get_name(node): return node.get('name') def flatten(tree): result = [] def walk(subtree): for item in subtree: if isinstance(item, list): walk(item) else: result.append(item) walk(tree) return result
true
true
1c3be4ac14d210a3695a7a37e502d4ea9d56c2d8
2,373
py
Python
docs/conf.py
Linuxiston/linuxiston_uz
5687df6922a53b58f13ba5554f4a70dd9871ef2a
[ "MIT" ]
null
null
null
docs/conf.py
Linuxiston/linuxiston_uz
5687df6922a53b58f13ba5554f4a70dd9871ef2a
[ "MIT" ]
4
2021-03-10T08:56:07.000Z
2021-05-12T06:04:52.000Z
docs/conf.py
Linuxiston/linuxiston_uz
5687df6922a53b58f13ba5554f4a70dd9871ef2a
[ "MIT" ]
null
null
null
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. import os import sys import django if os.getenv("READTHEDOCS", default=False) == "True": sys.path.insert(0, os.path.abspath("..")) os.environ["DJANGO_READ_DOT_ENV_FILE"] = "True" os.environ["USE_DOCKER"] = "no" else: sys.path.insert(0, os.path.abspath("/app")) os.environ["DATABASE_URL"] = "sqlite:///readthedocs.db" os.environ["CELERY_BROKER_URL"] = os.getenv("REDIS_URL", "redis://redis:6379") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") django.setup() # -- Project information ----------------------------------------------------- project = "Linuxiston Community" copyright = """2021, Shukrullo Turgunov""" author = "Shukrullo Turgunov" # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", ] # Add any paths that contain templates here, relative to this directory. # templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "alabaster" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ["_static"]
37.078125
79
0.671302
import os import sys import django if os.getenv("READTHEDOCS", default=False) == "True": sys.path.insert(0, os.path.abspath("..")) os.environ["DJANGO_READ_DOT_ENV_FILE"] = "True" os.environ["USE_DOCKER"] = "no" else: sys.path.insert(0, os.path.abspath("/app")) os.environ["DATABASE_URL"] = "sqlite:///readthedocs.db" os.environ["CELERY_BROKER_URL"] = os.getenv("REDIS_URL", "redis://redis:6379") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") django.setup() project = "Linuxiston Community" copyright = """2021, Shukrullo Turgunov""" author = "Shukrullo Turgunov" extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", ] exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] html_theme = "alabaster"
true
true
1c3be675a8450793c01dc0047a6380d459dcb4b4
5,367
py
Python
tests/test_cmd_forget.py
samuelsinayoko/doit
e7aa4f5f399c65bf9567ced9fb2673d52d9d6c92
[ "MIT" ]
1,390
2015-01-01T21:11:47.000Z
2022-03-31T11:35:44.000Z
tests/test_cmd_forget.py
samuelsinayoko/doit
e7aa4f5f399c65bf9567ced9fb2673d52d9d6c92
[ "MIT" ]
393
2015-01-05T11:18:29.000Z
2022-03-20T11:46:46.000Z
tests/test_cmd_forget.py
samuelsinayoko/doit
e7aa4f5f399c65bf9567ced9fb2673d52d9d6c92
[ "MIT" ]
176
2015-01-07T16:58:56.000Z
2022-03-28T12:12:11.000Z
from io import StringIO import pytest from doit.exceptions import InvalidCommand from doit.dependency import DbmDB, Dependency from doit.cmd_forget import Forget from .conftest import tasks_sample, CmdFactory class TestCmdForget(object): @pytest.fixture def tasks(self, request): return tasks_sample() @staticmethod def _add_task_deps(tasks, testdb): """put some data on testdb""" dep = Dependency(DbmDB, testdb) for task in tasks: dep._set(task.name,"dep","1") dep.close() dep2 = Dependency(DbmDB, testdb) assert "1" == dep2._get("g1.a", "dep") dep2.close() def testForgetDefault(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory(Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=['t1', 't2'], ) cmd_forget._execute(False, False, False) got = output.getvalue().split("\n")[:-1] assert ["forgetting t1", "forgetting t2"] == got, repr(output.getvalue()) dep = Dependency(DbmDB, depfile_name) assert None == dep._get('t1', "dep") assert None == dep._get('t2', "dep") assert '1' == dep._get('t3', "dep") def testForgetAll(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory(Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=[]) cmd_forget._execute(False, False, True) got = output.getvalue().split("\n")[:-1] assert ["forgetting all tasks"] == got, repr(output.getvalue()) dep = Dependency(DbmDB, depfile_name) for task in tasks: assert None == dep._get(task.name, "dep") def testDisableDefault(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory(Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=['t1', 't2'], sel_default_tasks=True) cmd_forget._execute(False, True, False) got = output.getvalue().split("\n")[:-1] assert ["no tasks specified, pass task name, --enable-default or --all"] == got, ( repr(output.getvalue())) dep = Dependency(DbmDB, depfile_name) for task in tasks: assert "1" == dep._get(task.name, "dep") def testForgetOne(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory(Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=["t2", "t1"]) cmd_forget._execute(False, True, False) got = output.getvalue().split("\n")[:-1] assert ["forgetting t2", "forgetting t1"] == got dep = Dependency(DbmDB, depfile_name) assert None == dep._get("t1", "dep") assert None == dep._get("t2", "dep") assert "1" == dep._get("g1.a", "dep") def testForgetGroup(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory( Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=["g1"]) cmd_forget._execute(False, False, False) got = output.getvalue().split("\n")[:-1] assert "forgetting g1" == got[0] dep = Dependency(DbmDB, depfile_name) assert "1" == dep._get("t1", "dep") assert "1" == dep._get("t2", "dep") assert None == dep._get("g1", "dep") assert None == dep._get("g1.a", "dep") assert None == dep._get("g1.b", "dep") def testForgetTaskDependency(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory( Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=["t3"]) cmd_forget._execute(True, False, False) dep = Dependency(DbmDB, depfile_name) assert None == dep._get("t3", "dep") assert None == dep._get("t1", "dep") # if task dependency not from a group dont forget it def testDontForgetTaskDependency(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory( Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=["t3"]) cmd_forget._execute(False, False, False) dep = Dependency(DbmDB, depfile_name) assert None == dep._get("t3", "dep") assert "1" == dep._get("t1", "dep") def testForgetInvalid(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory( Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=["XXX"]) pytest.raises(InvalidCommand, cmd_forget._execute, False, False, False)
40.969466
90
0.602758
from io import StringIO import pytest from doit.exceptions import InvalidCommand from doit.dependency import DbmDB, Dependency from doit.cmd_forget import Forget from .conftest import tasks_sample, CmdFactory class TestCmdForget(object): @pytest.fixture def tasks(self, request): return tasks_sample() @staticmethod def _add_task_deps(tasks, testdb): dep = Dependency(DbmDB, testdb) for task in tasks: dep._set(task.name,"dep","1") dep.close() dep2 = Dependency(DbmDB, testdb) assert "1" == dep2._get("g1.a", "dep") dep2.close() def testForgetDefault(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory(Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=['t1', 't2'], ) cmd_forget._execute(False, False, False) got = output.getvalue().split("\n")[:-1] assert ["forgetting t1", "forgetting t2"] == got, repr(output.getvalue()) dep = Dependency(DbmDB, depfile_name) assert None == dep._get('t1', "dep") assert None == dep._get('t2', "dep") assert '1' == dep._get('t3', "dep") def testForgetAll(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory(Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=[]) cmd_forget._execute(False, False, True) got = output.getvalue().split("\n")[:-1] assert ["forgetting all tasks"] == got, repr(output.getvalue()) dep = Dependency(DbmDB, depfile_name) for task in tasks: assert None == dep._get(task.name, "dep") def testDisableDefault(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory(Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=['t1', 't2'], sel_default_tasks=True) cmd_forget._execute(False, True, False) got = output.getvalue().split("\n")[:-1] assert ["no tasks specified, pass task name, --enable-default or --all"] == got, ( repr(output.getvalue())) dep = Dependency(DbmDB, depfile_name) for task in tasks: assert "1" == dep._get(task.name, "dep") def testForgetOne(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory(Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=["t2", "t1"]) cmd_forget._execute(False, True, False) got = output.getvalue().split("\n")[:-1] assert ["forgetting t2", "forgetting t1"] == got dep = Dependency(DbmDB, depfile_name) assert None == dep._get("t1", "dep") assert None == dep._get("t2", "dep") assert "1" == dep._get("g1.a", "dep") def testForgetGroup(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory( Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=["g1"]) cmd_forget._execute(False, False, False) got = output.getvalue().split("\n")[:-1] assert "forgetting g1" == got[0] dep = Dependency(DbmDB, depfile_name) assert "1" == dep._get("t1", "dep") assert "1" == dep._get("t2", "dep") assert None == dep._get("g1", "dep") assert None == dep._get("g1.a", "dep") assert None == dep._get("g1.b", "dep") def testForgetTaskDependency(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory( Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=["t3"]) cmd_forget._execute(True, False, False) dep = Dependency(DbmDB, depfile_name) assert None == dep._get("t3", "dep") assert None == dep._get("t1", "dep") def testDontForgetTaskDependency(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory( Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=["t3"]) cmd_forget._execute(False, False, False) dep = Dependency(DbmDB, depfile_name) assert None == dep._get("t3", "dep") assert "1" == dep._get("t1", "dep") def testForgetInvalid(self, tasks, depfile_name): self._add_task_deps(tasks, depfile_name) output = StringIO() cmd_forget = CmdFactory( Forget, outstream=output, dep_file=depfile_name, backend='dbm', task_list=tasks, sel_tasks=["XXX"]) pytest.raises(InvalidCommand, cmd_forget._execute, False, False, False)
true
true
1c3be6c578a2858b8a6ed8f3d43e5684f6edad78
1,199
py
Python
backend/library/coro.py
the-lans/FastAPITemplate
51c25622944b26fde545fec1824b2e334b020662
[ "MIT" ]
2
2021-08-15T09:07:21.000Z
2021-08-15T21:03:37.000Z
backend/library/coro.py
the-lans/YaML
cded6010b800f9a0bf00e50f0a144d9b1fc85959
[ "MIT" ]
null
null
null
backend/library/coro.py
the-lans/YaML
cded6010b800f9a0bf00e50f0a144d9b1fc85959
[ "MIT" ]
1
2021-08-15T21:03:40.000Z
2021-08-15T21:03:40.000Z
import asyncio from datetime import timedelta from typing import Union from backend.library.func import call_func def get_loop(): """ :return: current loop """ try: return asyncio.get_event_loop() except RuntimeError: return loop loop = get_loop() async def run_coro_after(coro, time: Union[float, timedelta]): """ Sleeps before awaiting coro :param coro: coro to ba awaited after time :param time: :return: """ if isinstance(time, timedelta): time = time.total_seconds() await asyncio.sleep(time) return await coro def start_coro(coro, after: Union[timedelta, float] = None): """ Starts coro :param coro: coro to be started :param after: if specified, then coro will be started after some time :return: started coro """ if after: coro = run_coro_after(coro, after) return get_loop().create_task(coro) async def coro_func(func, *args, **kwargs): """ Makes coro from sync function :param func: :param args: :param kwargs: :return: running coro in executor """ return await get_loop().run_in_executor(None, call_func, func, args, kwargs)
21.8
80
0.655546
import asyncio from datetime import timedelta from typing import Union from backend.library.func import call_func def get_loop(): try: return asyncio.get_event_loop() except RuntimeError: return loop loop = get_loop() async def run_coro_after(coro, time: Union[float, timedelta]): if isinstance(time, timedelta): time = time.total_seconds() await asyncio.sleep(time) return await coro def start_coro(coro, after: Union[timedelta, float] = None): if after: coro = run_coro_after(coro, after) return get_loop().create_task(coro) async def coro_func(func, *args, **kwargs): return await get_loop().run_in_executor(None, call_func, func, args, kwargs)
true
true
1c3be71ee094276ee43ab6d1f528d53421b89e41
422
py
Python
Python_Exercicios/Mundo2/Repetições em Python (for)/python_047.py
jbauermanncode/Curso_Em_Video_Python
330c207d7bed4e663fe1b9ab433ab57a9828b7f1
[ "MIT" ]
null
null
null
Python_Exercicios/Mundo2/Repetições em Python (for)/python_047.py
jbauermanncode/Curso_Em_Video_Python
330c207d7bed4e663fe1b9ab433ab57a9828b7f1
[ "MIT" ]
null
null
null
Python_Exercicios/Mundo2/Repetições em Python (for)/python_047.py
jbauermanncode/Curso_Em_Video_Python
330c207d7bed4e663fe1b9ab433ab57a9828b7f1
[ "MIT" ]
null
null
null
''' Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros termos dessa progressão. ''' # Ler o primeiro ter a razão pt = int(input('Digite o primeiro termo: ')) r = int(input('Digite a razão: ')) contador = 0 for i in range(pt, 100, r): contador = contador + 1 if contador <= 10: print('-> ', end='') print(i, end=' ') print('Acabou!')
28.133333
131
0.609005
pt = int(input('Digite o primeiro termo: ')) r = int(input('Digite a razão: ')) contador = 0 for i in range(pt, 100, r): contador = contador + 1 if contador <= 10: print('-> ', end='') print(i, end=' ') print('Acabou!')
true
true
1c3be83003f778c4fba3d9bd23fc303426032508
7,633
py
Python
dvc/command/plots.py
vladkol/dvc
f4349aa09b839687fbb24913ee222b815f875567
[ "Apache-2.0" ]
null
null
null
dvc/command/plots.py
vladkol/dvc
f4349aa09b839687fbb24913ee222b815f875567
[ "Apache-2.0" ]
null
null
null
dvc/command/plots.py
vladkol/dvc
f4349aa09b839687fbb24913ee222b815f875567
[ "Apache-2.0" ]
null
null
null
import argparse import logging import os from dvc.command import completion from dvc.command.base import CmdBase, append_doc_link, fix_subparsers from dvc.exceptions import DvcException from dvc.schema import PLOT_PROPS from dvc.utils import format_link logger = logging.getLogger(__name__) PAGE_HTML = """<!DOCTYPE html> <html> <head> <title>DVC Plot</title> <script src="https://cdn.jsdelivr.net/npm/vega@5.10.0"></script> <script src="https://cdn.jsdelivr.net/npm/vega-lite@4.8.1"></script> <script src="https://cdn.jsdelivr.net/npm/vega-embed@6.5.1"></script> </head> <body> {divs} </body> </html>""" DIV_HTML = """<div id = "{id}"></div> <script type = "text/javascript"> var spec = {vega_json}; vegaEmbed('#{id}', spec); </script>""" class CmdPlots(CmdBase): def _func(self, *args, **kwargs): raise NotImplementedError def _props(self): # Pass only props specified by user, to not shadow ones from plot def props = {p: getattr(self.args, p) for p in PLOT_PROPS} return {k: v for k, v in props.items() if v is not None} def run(self): if self.args.show_vega: if not self.args.targets: logger.error("please specify a target for `--show-vega`") return 1 if len(self.args.targets) > 1: logger.error( "you can only specify one target for `--show-vega`" ) return 1 try: plots = self._func(targets=self.args.targets, props=self._props()) if self.args.show_vega: target = self.args.targets[0] logger.info(plots[target]) return 0 divs = [ DIV_HTML.format(id=f"plot{i}", vega_json=plot) for i, plot in enumerate(plots.values()) ] html = PAGE_HTML.format(divs="\n".join(divs)) path = self.args.out or "plots.html" path = os.path.join(os.getcwd(), path) with open(path, "w") as fobj: fobj.write(html) logger.info(f"file://{path}") except DvcException: logger.exception("failed to show plots") return 1 return 0 class CmdPlotsShow(CmdPlots): UNINITIALIZED = True def _func(self, *args, **kwargs): return self.repo.plots.show(*args, **kwargs) class CmdPlotsDiff(CmdPlots): UNINITIALIZED = True def _func(self, *args, **kwargs): return self.repo.plots.diff( *args, revs=self.args.revisions, experiment=self.args.experiment, **kwargs, ) class CmdPlotsModify(CmdPlots): def run(self): self.repo.plots.modify( self.args.target, props=self._props(), unset=self.args.unset, ) return 0 def add_parser(subparsers, parent_parser): PLOTS_HELP = ( "Commands to visualize and compare plot metrics in structured files " "(JSON, YAML, CSV, TSV)" ) plots_parser = subparsers.add_parser( "plots", parents=[parent_parser], description=append_doc_link(PLOTS_HELP, "plots"), help=PLOTS_HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) plots_subparsers = plots_parser.add_subparsers( dest="cmd", help="Use `dvc plots CMD --help` to display command-specific help.", ) fix_subparsers(plots_subparsers) SHOW_HELP = "Generate plots from metrics files." plots_show_parser = plots_subparsers.add_parser( "show", parents=[parent_parser], description=append_doc_link(SHOW_HELP, "plots/show"), help=SHOW_HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) plots_show_parser.add_argument( "targets", nargs="*", help="Files to visualize (supports any file, " "even when not found as `plots` in `dvc.yaml`). " "Shows all plots by default.", ).complete = completion.FILE _add_props_arguments(plots_show_parser) _add_output_arguments(plots_show_parser) plots_show_parser.set_defaults(func=CmdPlotsShow) PLOTS_DIFF_HELP = ( "Show multiple versions of plot metrics " "by plotting them in a single image." ) plots_diff_parser = plots_subparsers.add_parser( "diff", parents=[parent_parser], description=append_doc_link(PLOTS_DIFF_HELP, "plots/diff"), help=PLOTS_DIFF_HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) plots_diff_parser.add_argument( "--targets", nargs="*", help="Files to visualize (supports any file, " "even when not found as `plots` in `dvc.yaml`). " "Shows all plots by default.", metavar="<path>", ).complete = completion.FILE plots_diff_parser.add_argument( "-e", "--experiment", action="store_true", default=False, help=argparse.SUPPRESS, ) plots_diff_parser.add_argument( "revisions", nargs="*", default=None, help="Git commits to plot from", ) _add_props_arguments(plots_diff_parser) _add_output_arguments(plots_diff_parser) plots_diff_parser.set_defaults(func=CmdPlotsDiff) PLOTS_MODIFY_HELP = "Modify display properties of plot metrics files." plots_modify_parser = plots_subparsers.add_parser( "modify", parents=[parent_parser], description=append_doc_link(PLOTS_MODIFY_HELP, "plots/modify"), help=PLOTS_MODIFY_HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) plots_modify_parser.add_argument( "target", help="Metric file to set properties to", ).complete = completion.FILE _add_props_arguments(plots_modify_parser) plots_modify_parser.add_argument( "--unset", nargs="*", metavar="<property>", help="Unset one or more display properties.", ) plots_modify_parser.set_defaults(func=CmdPlotsModify) def _add_props_arguments(parser): parser.add_argument( "-t", "--template", nargs="?", default=None, help=( "Special JSON or HTML schema file to inject with the data. " "See {}".format( format_link("https://man.dvc.org/plots#plot-templates") ) ), metavar="<path>", ).complete = completion.FILE parser.add_argument( "-x", default=None, help="Field name for X axis.", metavar="<field>" ) parser.add_argument( "-y", default=None, help="Field name for Y axis.", metavar="<field>" ) parser.add_argument( "--no-header", action="store_false", dest="header", default=None, # Use default None to distinguish when it's not used help="Provided CSV or TSV datafile does not have a header.", ) parser.add_argument( "--title", default=None, metavar="<text>", help="Plot title." ) parser.add_argument( "--x-label", default=None, help="X axis label", metavar="<text>" ) parser.add_argument( "--y-label", default=None, help="Y axis label", metavar="<text>" ) def _add_output_arguments(parser): parser.add_argument( "-o", "--out", default=None, help="Destination path to save plots to", metavar="<path>", ).complete = completion.DIR parser.add_argument( "--show-vega", action="store_true", default=False, help="Show output in Vega format.", )
30.16996
78
0.609852
import argparse import logging import os from dvc.command import completion from dvc.command.base import CmdBase, append_doc_link, fix_subparsers from dvc.exceptions import DvcException from dvc.schema import PLOT_PROPS from dvc.utils import format_link logger = logging.getLogger(__name__) PAGE_HTML = """<!DOCTYPE html> <html> <head> <title>DVC Plot</title> <script src="https://cdn.jsdelivr.net/npm/vega@5.10.0"></script> <script src="https://cdn.jsdelivr.net/npm/vega-lite@4.8.1"></script> <script src="https://cdn.jsdelivr.net/npm/vega-embed@6.5.1"></script> </head> <body> {divs} </body> </html>""" DIV_HTML = """<div id = "{id}"></div> <script type = "text/javascript"> var spec = {vega_json}; vegaEmbed('#{id}', spec); </script>""" class CmdPlots(CmdBase): def _func(self, *args, **kwargs): raise NotImplementedError def _props(self): props = {p: getattr(self.args, p) for p in PLOT_PROPS} return {k: v for k, v in props.items() if v is not None} def run(self): if self.args.show_vega: if not self.args.targets: logger.error("please specify a target for `--show-vega`") return 1 if len(self.args.targets) > 1: logger.error( "you can only specify one target for `--show-vega`" ) return 1 try: plots = self._func(targets=self.args.targets, props=self._props()) if self.args.show_vega: target = self.args.targets[0] logger.info(plots[target]) return 0 divs = [ DIV_HTML.format(id=f"plot{i}", vega_json=plot) for i, plot in enumerate(plots.values()) ] html = PAGE_HTML.format(divs="\n".join(divs)) path = self.args.out or "plots.html" path = os.path.join(os.getcwd(), path) with open(path, "w") as fobj: fobj.write(html) logger.info(f"file://{path}") except DvcException: logger.exception("failed to show plots") return 1 return 0 class CmdPlotsShow(CmdPlots): UNINITIALIZED = True def _func(self, *args, **kwargs): return self.repo.plots.show(*args, **kwargs) class CmdPlotsDiff(CmdPlots): UNINITIALIZED = True def _func(self, *args, **kwargs): return self.repo.plots.diff( *args, revs=self.args.revisions, experiment=self.args.experiment, **kwargs, ) class CmdPlotsModify(CmdPlots): def run(self): self.repo.plots.modify( self.args.target, props=self._props(), unset=self.args.unset, ) return 0 def add_parser(subparsers, parent_parser): PLOTS_HELP = ( "Commands to visualize and compare plot metrics in structured files " "(JSON, YAML, CSV, TSV)" ) plots_parser = subparsers.add_parser( "plots", parents=[parent_parser], description=append_doc_link(PLOTS_HELP, "plots"), help=PLOTS_HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) plots_subparsers = plots_parser.add_subparsers( dest="cmd", help="Use `dvc plots CMD --help` to display command-specific help.", ) fix_subparsers(plots_subparsers) SHOW_HELP = "Generate plots from metrics files." plots_show_parser = plots_subparsers.add_parser( "show", parents=[parent_parser], description=append_doc_link(SHOW_HELP, "plots/show"), help=SHOW_HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) plots_show_parser.add_argument( "targets", nargs="*", help="Files to visualize (supports any file, " "even when not found as `plots` in `dvc.yaml`). " "Shows all plots by default.", ).complete = completion.FILE _add_props_arguments(plots_show_parser) _add_output_arguments(plots_show_parser) plots_show_parser.set_defaults(func=CmdPlotsShow) PLOTS_DIFF_HELP = ( "Show multiple versions of plot metrics " "by plotting them in a single image." ) plots_diff_parser = plots_subparsers.add_parser( "diff", parents=[parent_parser], description=append_doc_link(PLOTS_DIFF_HELP, "plots/diff"), help=PLOTS_DIFF_HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) plots_diff_parser.add_argument( "--targets", nargs="*", help="Files to visualize (supports any file, " "even when not found as `plots` in `dvc.yaml`). " "Shows all plots by default.", metavar="<path>", ).complete = completion.FILE plots_diff_parser.add_argument( "-e", "--experiment", action="store_true", default=False, help=argparse.SUPPRESS, ) plots_diff_parser.add_argument( "revisions", nargs="*", default=None, help="Git commits to plot from", ) _add_props_arguments(plots_diff_parser) _add_output_arguments(plots_diff_parser) plots_diff_parser.set_defaults(func=CmdPlotsDiff) PLOTS_MODIFY_HELP = "Modify display properties of plot metrics files." plots_modify_parser = plots_subparsers.add_parser( "modify", parents=[parent_parser], description=append_doc_link(PLOTS_MODIFY_HELP, "plots/modify"), help=PLOTS_MODIFY_HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) plots_modify_parser.add_argument( "target", help="Metric file to set properties to", ).complete = completion.FILE _add_props_arguments(plots_modify_parser) plots_modify_parser.add_argument( "--unset", nargs="*", metavar="<property>", help="Unset one or more display properties.", ) plots_modify_parser.set_defaults(func=CmdPlotsModify) def _add_props_arguments(parser): parser.add_argument( "-t", "--template", nargs="?", default=None, help=( "Special JSON or HTML schema file to inject with the data. " "See {}".format( format_link("https://man.dvc.org/plots#plot-templates") ) ), metavar="<path>", ).complete = completion.FILE parser.add_argument( "-x", default=None, help="Field name for X axis.", metavar="<field>" ) parser.add_argument( "-y", default=None, help="Field name for Y axis.", metavar="<field>" ) parser.add_argument( "--no-header", action="store_false", dest="header", default=None, help="Provided CSV or TSV datafile does not have a header.", ) parser.add_argument( "--title", default=None, metavar="<text>", help="Plot title." ) parser.add_argument( "--x-label", default=None, help="X axis label", metavar="<text>" ) parser.add_argument( "--y-label", default=None, help="Y axis label", metavar="<text>" ) def _add_output_arguments(parser): parser.add_argument( "-o", "--out", default=None, help="Destination path to save plots to", metavar="<path>", ).complete = completion.DIR parser.add_argument( "--show-vega", action="store_true", default=False, help="Show output in Vega format.", )
true
true
1c3be867a5388ae3bb6f6bf6154f4631ad868c77
28
py
Python
engine/cameras/__init__.py
LloydTao/ecm3423-fur-effect
fefa73665b459dfd1648dca97a95e8313cf53dd5
[ "MIT" ]
null
null
null
engine/cameras/__init__.py
LloydTao/ecm3423-fur-effect
fefa73665b459dfd1648dca97a95e8313cf53dd5
[ "MIT" ]
null
null
null
engine/cameras/__init__.py
LloydTao/ecm3423-fur-effect
fefa73665b459dfd1648dca97a95e8313cf53dd5
[ "MIT" ]
null
null
null
from .cameras import Camera
14
27
0.821429
from .cameras import Camera
true
true
1c3be89d56f6833f2636d1812cadda82dcdc0286
6,931
py
Python
main.py
dasiusp/DasiToolsBot
85d5e6c8a19f118b7926420abc236825d890068f
[ "MIT" ]
null
null
null
main.py
dasiusp/DasiToolsBot
85d5e6c8a19f118b7926420abc236825d890068f
[ "MIT" ]
null
null
null
main.py
dasiusp/DasiToolsBot
85d5e6c8a19f118b7926420abc236825d890068f
[ "MIT" ]
1
2020-08-29T02:32:13.000Z
2020-08-29T02:32:13.000Z
import os import database from telegram import Update, Bot from telegram.ext import Dispatcher, CommandHandler, MessageHandler, Filters from datetime import date allowed = False group_id_name = { "-1001375094289": "Diretoria", "-1001288984466": "Administrativo", "-1001479427906": "Financeiro", "-1001360969735": "Acadêmico", "-1001417414524": "Comercial", "-1001142338317": "Esportivo", "-1001323151506": "TI", "-1001193181957": "Eventos", "-1001159037615": "Criação" } def check_group(bot, update): global allowed chat_id = str(update.message.chat.id) allowed_groups_ref = database.get_allowed_groups() allowed_groups = (allowed_groups_ref.to_dict()).values() if chat_id in allowed_groups: allowed = True else: allowed = False def start(bot, update): check_group(bot, update) if allowed is False: update.message.reply_text("Este grupo não tem permissão para utilizar o bot!", quote=False) return update.message.reply_text("Olá, eu fui criado pelo Vino para facilitar a marcação de " + "todos os membros de um setor ou de todos os membros do DASI!\n\n" + "Digite /ajuda para ver os comandos disponiveis.", quote=False) def help(bot, update): check_group(bot, update) if allowed is False: update.message.reply_text("Este grupo não tem permissão para utilizar o bot!", quote=False) return update.message.reply_text("Lista de comandos \n\n"+ "/join - Entrar na lista do seu setor e do geral\n" + "/diretoria - Todos os membros da diretoria\n" + "/administrativo - Todos os membros do setor Administrativo\n" + "/financeiro - Todos os membros do setor Financeiro\n" + "/academico - Todos os membros do setor Acadêmico\n" + "/comercial - Todos os membros do setor Comercial\n" + "/esportivo - Todos os membros do setor Esportivo\n" + "/ti - Todos os membros do setor de TI\n" + "/eventos - Todos os membros do setor de Eventos\n" + "/criacao - Todos os membros do setor de Criação\n" + "/todos - Todos os membros do DASI", quote=False) def join(bot, update): check_group(bot, update) if allowed is False: update.message.reply_text("Este grupo não tem permissão para utilizar o bot!", quote=False) return user = update.message.from_user chat_id = str(update.message.chat.id) group_name = str(group_id_name.get(str(chat_id))) username = "@" + str(user.username) group_list_ref = database.get_group_list(group_name) group_list = group_list_ref.to_dict() if group_id_name.get(str(chat_id)) is None: update.message.reply_text("Função indisponível para esse chat!", quote=False) return if str(user.id) in group_list.keys(): update.message.reply_text("Você já está na lista do seu setor!", quote=False) else: database.join_group_list(group_name, user.id, username) update.message.reply_text("Você entrou na lista do seu setor!", quote=False) def show_group_members(bot, update, group_name): check_group(bot, update) if allowed is False: update.message.reply_text("Este grupo não tem permissão para utilizar o bot!", quote=False) return group_ref = database.get_group_list(str(group_name)) group = (group_ref.to_dict()).values() if bool(group) is False: update.message.reply_text("Essa lista está vazia!", quote=False) return for i in range(len(group)): lista = " ".join(group) update.message.reply_text(str(group_name) + ": \n\n" + str(lista), quote=False) def diretoria(bot, update): show_group_members(bot, update, "Diretoria") def adm(bot, update): show_group_members(bot, update, "Administrativo") def financeiro(bot, update): show_group_members(bot, update, "Financeiro") def acad(bot, update): show_group_members(bot, update, "Acadêmico") def comercial(bot, update): show_group_members(bot, update, "Comercial") def esportivo(bot, update): show_group_members(bot, update, "Esportivo") def ti(bot, update): show_group_members(bot, update, "TI") def eventos(bot, update): show_group_members(bot, update, "Eventos") def criacao(bot, update): show_group_members(bot, update, "Criação") def todos(bot, update): show_group_members(bot, update, "Todos") def reminder(bot, update): data_ref = database.get_reminder_date() data = data_ref.to_dict() year = int(data.get('year')) month = int(data.get('month')) day = int(data.get('day')) current_reminder = date(year, month, day) today = date.today() day_diff = (today - current_reminder) if (day_diff.days) >= 45: database.update_reminder_date(today) update.message.reply_text("[LEMBRETE]\n\nRealizar transação nas maquininhas de cartão para que elas não sejam desativadas", quote=False) def invalid_message(bot, update): chat_type = update.message.chat.type chat_id = str(update.message.chat.id) if chat_id == "-1001375094289": reminder(bot, update) if chat_type == "private": check_group(bot, update) if allowed is False: update.message.reply_text("Você não tem permissão para utilizar o bot!", quote=False) return update.message.reply_text("Comando inválido! Digite /ajuda para visualizar a lista de comandos.", quote=False) def webhook(request): bot = Bot(token=os.environ["TELEGRAM_TOKEN"]) dispatcher = Dispatcher(bot, None, 0) dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("ajuda", help)) dispatcher.add_handler(CommandHandler("join", join)) dispatcher.add_handler(CommandHandler("diretoria", diretoria)) dispatcher.add_handler(CommandHandler("administrativo", adm)) dispatcher.add_handler(CommandHandler("financeiro", financeiro)) dispatcher.add_handler(CommandHandler("academico", acad)) dispatcher.add_handler(CommandHandler("comercial", comercial)) dispatcher.add_handler(CommandHandler("esportivo", esportivo)) dispatcher.add_handler(CommandHandler("ti", ti)) dispatcher.add_handler(CommandHandler("eventos", eventos)) dispatcher.add_handler(CommandHandler("criacao", criacao)) dispatcher.add_handler(CommandHandler("todos", todos)) dispatcher.add_handler(MessageHandler(Filters.text, invalid_message)) if request.method == "POST": update = Update.de_json(request.get_json(force=True), bot) dispatcher.process_update(update) return "ok"
33.645631
144
0.660799
import os import database from telegram import Update, Bot from telegram.ext import Dispatcher, CommandHandler, MessageHandler, Filters from datetime import date allowed = False group_id_name = { "-1001375094289": "Diretoria", "-1001288984466": "Administrativo", "-1001479427906": "Financeiro", "-1001360969735": "Acadêmico", "-1001417414524": "Comercial", "-1001142338317": "Esportivo", "-1001323151506": "TI", "-1001193181957": "Eventos", "-1001159037615": "Criação" } def check_group(bot, update): global allowed chat_id = str(update.message.chat.id) allowed_groups_ref = database.get_allowed_groups() allowed_groups = (allowed_groups_ref.to_dict()).values() if chat_id in allowed_groups: allowed = True else: allowed = False def start(bot, update): check_group(bot, update) if allowed is False: update.message.reply_text("Este grupo não tem permissão para utilizar o bot!", quote=False) return update.message.reply_text("Olá, eu fui criado pelo Vino para facilitar a marcação de " + "todos os membros de um setor ou de todos os membros do DASI!\n\n" + "Digite /ajuda para ver os comandos disponiveis.", quote=False) def help(bot, update): check_group(bot, update) if allowed is False: update.message.reply_text("Este grupo não tem permissão para utilizar o bot!", quote=False) return update.message.reply_text("Lista de comandos \n\n"+ "/join - Entrar na lista do seu setor e do geral\n" + "/diretoria - Todos os membros da diretoria\n" + "/administrativo - Todos os membros do setor Administrativo\n" + "/financeiro - Todos os membros do setor Financeiro\n" + "/academico - Todos os membros do setor Acadêmico\n" + "/comercial - Todos os membros do setor Comercial\n" + "/esportivo - Todos os membros do setor Esportivo\n" + "/ti - Todos os membros do setor de TI\n" + "/eventos - Todos os membros do setor de Eventos\n" + "/criacao - Todos os membros do setor de Criação\n" + "/todos - Todos os membros do DASI", quote=False) def join(bot, update): check_group(bot, update) if allowed is False: update.message.reply_text("Este grupo não tem permissão para utilizar o bot!", quote=False) return user = update.message.from_user chat_id = str(update.message.chat.id) group_name = str(group_id_name.get(str(chat_id))) username = "@" + str(user.username) group_list_ref = database.get_group_list(group_name) group_list = group_list_ref.to_dict() if group_id_name.get(str(chat_id)) is None: update.message.reply_text("Função indisponível para esse chat!", quote=False) return if str(user.id) in group_list.keys(): update.message.reply_text("Você já está na lista do seu setor!", quote=False) else: database.join_group_list(group_name, user.id, username) update.message.reply_text("Você entrou na lista do seu setor!", quote=False) def show_group_members(bot, update, group_name): check_group(bot, update) if allowed is False: update.message.reply_text("Este grupo não tem permissão para utilizar o bot!", quote=False) return group_ref = database.get_group_list(str(group_name)) group = (group_ref.to_dict()).values() if bool(group) is False: update.message.reply_text("Essa lista está vazia!", quote=False) return for i in range(len(group)): lista = " ".join(group) update.message.reply_text(str(group_name) + ": \n\n" + str(lista), quote=False) def diretoria(bot, update): show_group_members(bot, update, "Diretoria") def adm(bot, update): show_group_members(bot, update, "Administrativo") def financeiro(bot, update): show_group_members(bot, update, "Financeiro") def acad(bot, update): show_group_members(bot, update, "Acadêmico") def comercial(bot, update): show_group_members(bot, update, "Comercial") def esportivo(bot, update): show_group_members(bot, update, "Esportivo") def ti(bot, update): show_group_members(bot, update, "TI") def eventos(bot, update): show_group_members(bot, update, "Eventos") def criacao(bot, update): show_group_members(bot, update, "Criação") def todos(bot, update): show_group_members(bot, update, "Todos") def reminder(bot, update): data_ref = database.get_reminder_date() data = data_ref.to_dict() year = int(data.get('year')) month = int(data.get('month')) day = int(data.get('day')) current_reminder = date(year, month, day) today = date.today() day_diff = (today - current_reminder) if (day_diff.days) >= 45: database.update_reminder_date(today) update.message.reply_text("[LEMBRETE]\n\nRealizar transação nas maquininhas de cartão para que elas não sejam desativadas", quote=False) def invalid_message(bot, update): chat_type = update.message.chat.type chat_id = str(update.message.chat.id) if chat_id == "-1001375094289": reminder(bot, update) if chat_type == "private": check_group(bot, update) if allowed is False: update.message.reply_text("Você não tem permissão para utilizar o bot!", quote=False) return update.message.reply_text("Comando inválido! Digite /ajuda para visualizar a lista de comandos.", quote=False) def webhook(request): bot = Bot(token=os.environ["TELEGRAM_TOKEN"]) dispatcher = Dispatcher(bot, None, 0) dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("ajuda", help)) dispatcher.add_handler(CommandHandler("join", join)) dispatcher.add_handler(CommandHandler("diretoria", diretoria)) dispatcher.add_handler(CommandHandler("administrativo", adm)) dispatcher.add_handler(CommandHandler("financeiro", financeiro)) dispatcher.add_handler(CommandHandler("academico", acad)) dispatcher.add_handler(CommandHandler("comercial", comercial)) dispatcher.add_handler(CommandHandler("esportivo", esportivo)) dispatcher.add_handler(CommandHandler("ti", ti)) dispatcher.add_handler(CommandHandler("eventos", eventos)) dispatcher.add_handler(CommandHandler("criacao", criacao)) dispatcher.add_handler(CommandHandler("todos", todos)) dispatcher.add_handler(MessageHandler(Filters.text, invalid_message)) if request.method == "POST": update = Update.de_json(request.get_json(force=True), bot) dispatcher.process_update(update) return "ok"
true
true
1c3be8b41689875374e3f616c589eefd510a8e3f
2,893
py
Python
venv/lib/python2.7/site-packages/Halberd/reportlib.py
sravani-m/Web-Application-Security-Framework
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
[ "MIT" ]
3
2019-04-09T22:59:33.000Z
2019-06-14T09:23:24.000Z
venv/lib/python2.7/site-packages/Halberd/reportlib.py
sravani-m/Web-Application-Security-Framework
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
[ "MIT" ]
null
null
null
venv/lib/python2.7/site-packages/Halberd/reportlib.py
sravani-m/Web-Application-Security-Framework
d9f71538f5cba6fe1d8eabcb26c557565472f6a6
[ "MIT" ]
null
null
null
# -*- coding: iso-8859-1 -*- """Output module. """ # Copyright (C) 2004, 2005, 2006, 2010 Juan M. Bello Rivas <jmbr@superadditive.com> # # This program 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 2 of the License, or # (at your option) any later version. # # This program 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 this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import sys import Halberd.logger import Halberd.clues.analysis as analysis def report(scantask): """Displays detailed report information to the user. """ if scantask.out: out = open(scantask.out, 'a') else: out = sys.stdout clues = scantask.analyzed hits = analysis.hits(clues) logger = Halberd.logger.getLogger() # xxx This could be passed by the caller in order to avoid recomputation in # case the clues needed a re-analysis. diff_fields = analysis.diff_fields(clues) out.write('=' * 70 + '\n') out.write('%s' % scantask.url) if scantask.addr: out.write(' (%s)' % scantask.addr) out.write(': %d real server(s)\n' % len(clues)) out.write('=' * 70 + '\n') for num, clue in enumerate(clues): assert hits > 0 info = clue.info out.write('\n') # out.write('-' * 70 + '\n') out.write('server %d: %s\n' % (num + 1, info['server'].lstrip())) out.write('-' * 70 + '\n\n') out.write('difference: %d seconds\n' % clue.diff) out.write('successful requests: %d hits (%.2f%%)\n' \ % (clue.getCount(), clue.getCount() * 100 / float(hits))) if info['contloc']: out.write('content-location: %s\n' % info['contloc'].lstrip()) if len(info['cookies']) > 0: out.write('cookie(s):\n') for cookie in info['cookies']: out.write(' %s\n' % cookie.lstrip()) out.write('header fingerprint: %s\n' % info['digest']) different = [(field, value) for field, value in clue.headers \ if field in diff_fields] if different: out.write('different headers:\n') idx = 1 for field, value in different: out.write(' %d. %s:%s\n' % (idx, field, value)) idx += 1 if scantask.debug: import pprint out.write('headers:\n') pprint.pprint(clue.headers, out) # vim: ts=4 sw=4 et
31.445652
84
0.596613
import sys import Halberd.logger import Halberd.clues.analysis as analysis def report(scantask): if scantask.out: out = open(scantask.out, 'a') else: out = sys.stdout clues = scantask.analyzed hits = analysis.hits(clues) logger = Halberd.logger.getLogger() diff_fields = analysis.diff_fields(clues) out.write('=' * 70 + '\n') out.write('%s' % scantask.url) if scantask.addr: out.write(' (%s)' % scantask.addr) out.write(': %d real server(s)\n' % len(clues)) out.write('=' * 70 + '\n') for num, clue in enumerate(clues): assert hits > 0 info = clue.info out.write('\n') out.write('server %d: %s\n' % (num + 1, info['server'].lstrip())) out.write('-' * 70 + '\n\n') out.write('difference: %d seconds\n' % clue.diff) out.write('successful requests: %d hits (%.2f%%)\n' \ % (clue.getCount(), clue.getCount() * 100 / float(hits))) if info['contloc']: out.write('content-location: %s\n' % info['contloc'].lstrip()) if len(info['cookies']) > 0: out.write('cookie(s):\n') for cookie in info['cookies']: out.write(' %s\n' % cookie.lstrip()) out.write('header fingerprint: %s\n' % info['digest']) different = [(field, value) for field, value in clue.headers \ if field in diff_fields] if different: out.write('different headers:\n') idx = 1 for field, value in different: out.write(' %d. %s:%s\n' % (idx, field, value)) idx += 1 if scantask.debug: import pprint out.write('headers:\n') pprint.pprint(clue.headers, out)
true
true
1c3be9a3ab654e77f2f050513e77f951170d63da
7,680
py
Python
docs/conf.py
astaxie/tsuru
e59ef9621742b236903db080379e04d881896f76
[ "BSD-3-Clause" ]
1
2015-04-16T15:06:18.000Z
2015-04-16T15:06:18.000Z
docs/conf.py
astaxie/tsuru
e59ef9621742b236903db080379e04d881896f76
[ "BSD-3-Clause" ]
null
null
null
docs/conf.py
astaxie/tsuru
e59ef9621742b236903db080379e04d881896f76
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # # tsuru documentation build configuration file, created by # sphinx-quickstart on Wed Aug 8 11:09:54 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'tsuru' copyright = u'2012, Globo.com' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'tsurudoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'tsuru.tex', u'tsuru Documentation', u'timeredbull', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'tsuru', u'tsuru Documentation', [u'timeredbull'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'tsuru', u'tsuru Documentation', u'timeredbull', 'tsuru', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
31.86722
80
0.713151
extensions = [] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'tsuru' copyright = u'2012, Globo.com' # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'tsurudoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'tsuru.tex', u'tsuru Documentation', u'timeredbull', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'tsuru', u'tsuru Documentation', [u'timeredbull'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'tsuru', u'tsuru Documentation', u'timeredbull', 'tsuru', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
true
true
1c3bea03b7204ffb3e1292fb83c45288f17d8e2a
651
py
Python
.mm/project.py
avalentino/pyre
7e1f0287eb7eba1c6d1ef385e5160079283ac363
[ "BSD-3-Clause" ]
25
2018-04-23T01:45:39.000Z
2021-12-10T06:01:23.000Z
.mm/project.py
avalentino/pyre
7e1f0287eb7eba1c6d1ef385e5160079283ac363
[ "BSD-3-Clause" ]
53
2018-05-31T04:55:00.000Z
2021-10-07T21:41:32.000Z
.mm/project.py
avalentino/pyre
7e1f0287eb7eba1c6d1ef385e5160079283ac363
[ "BSD-3-Clause" ]
12
2018-04-23T22:50:40.000Z
2022-02-20T17:27:23.000Z
# -*- coding: utf-8 -*- # # michael a.g. aïvázis # california institute of technology # (c) 1998-2021 all rights reserved # def requirements(package): """ Build a dictionary with the external dependencies of the {pyre} project """ # build the package instances packages = [ package(name='cuda', optional=True), package(name='gsl', optional=True), package(name='libpq', optional=True), package(name='mpi', optional=True), package(name='python', optional=False), ] # build a dictionary and return it return { package.name: package for package in packages } # end of file
23.25
75
0.634409
def requirements(package): packages = [ package(name='cuda', optional=True), package(name='gsl', optional=True), package(name='libpq', optional=True), package(name='mpi', optional=True), package(name='python', optional=False), ] return { package.name: package for package in packages }
true
true
1c3bea2ca6cf6637fb72329a95eab934bf988cb6
507
py
Python
env/lib/python3.8/site-packages/plotly/validators/layout/ternary/aaxis/tickfont/_size.py
acrucetta/Chicago_COVI_WebApp
a37c9f492a20dcd625f8647067394617988de913
[ "MIT", "Unlicense" ]
76
2020-07-06T14:44:05.000Z
2022-02-14T15:30:21.000Z
env/lib/python3.8/site-packages/plotly/validators/layout/ternary/aaxis/tickfont/_size.py
acrucetta/Chicago_COVI_WebApp
a37c9f492a20dcd625f8647067394617988de913
[ "MIT", "Unlicense" ]
11
2020-08-09T02:30:14.000Z
2022-03-12T00:50:14.000Z
env/lib/python3.8/site-packages/plotly/validators/layout/ternary/aaxis/tickfont/_size.py
acrucetta/Chicago_COVI_WebApp
a37c9f492a20dcd625f8647067394617988de913
[ "MIT", "Unlicense" ]
11
2020-07-12T16:18:07.000Z
2022-02-05T16:48:35.000Z
import _plotly_utils.basevalidators class SizeValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="size", parent_name="layout.ternary.aaxis.tickfont", **kwargs ): super(SizeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), min=kwargs.pop("min", 1), role=kwargs.pop("role", "style"), **kwargs )
31.6875
87
0.621302
import _plotly_utils.basevalidators class SizeValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="size", parent_name="layout.ternary.aaxis.tickfont", **kwargs ): super(SizeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), min=kwargs.pop("min", 1), role=kwargs.pop("role", "style"), **kwargs )
true
true
1c3bea465ccf1b418cfcb4ed7a32c6a962440a8b
1,920
py
Python
Scripts/Miscellaneous/Automatic Birthday Wisher/main.py
ShivangiPatel102/Python_and_the_Web
6d3b55aef20feeda3cfff941d7bbdc26cbcc70d2
[ "MIT" ]
437
2020-09-24T13:57:39.000Z
2022-03-30T12:45:56.000Z
Scripts/Miscellaneous/Automatic Birthday Wisher/main.py
ShivangiPatel102/Python_and_the_Web
6d3b55aef20feeda3cfff941d7bbdc26cbcc70d2
[ "MIT" ]
355
2020-09-24T13:53:16.000Z
2022-03-27T04:20:40.000Z
Scripts/Miscellaneous/Automatic Birthday Wisher/main.py
ShivangiPatel102/Python_and_the_Web
6d3b55aef20feeda3cfff941d7bbdc26cbcc70d2
[ "MIT" ]
315
2020-09-24T18:41:19.000Z
2022-03-07T05:53:01.000Z
# import required packages import pandas as pd import datetime import smtplib # your gmail credentials here GMAIL_ID = "Your-Gmail-Id" GMAIL_PWD = "Your-Gmail-Password" # function for sending email def sendEmail(to, sub, msg): # conncection to gmail gmail_obj = smtplib.SMTP("smtp.gmail.com", 587) # starting the session gmail_obj.starttls() # login using credentials gmail_obj.login(GMAIL_ID, GMAIL_PWD) # sending email gmail_obj.sendmail(GMAIL_ID, to, f"Subject : {sub}\n\n{msg}") # quit the session gmail_obj.quit() # printing to check whether email is sent or not print( "Email sent to " + str(to) + " with subject " + str(sub) + " and message :" + str(msg) ) # driver code if __name__ == "__main__": # read the excel sheet having all the details dataframe = pd.read_excel("Path-of-your-excel-sheet") # fetching todays date in format : DD-MM today = datetime.datetime.now().strftime("%d-%m") # fetching current year in format : YY yearNow = datetime.datetime.now().strftime("%Y") # writeindex list to avoid spamming of mails writeInd = [] for index, item in dataframe.iterrows(): msg = "Many Many Happy Returns of the day dear " + str(item["Name"]) # stripping the birthday in excel sheet as : DD-MM bday = item["Birthday"].strftime("%d-%m") # condition checking for today birthday if (today == bday) and yearNow not in str(item["Year"]): # calling the sendEmail function sendEmail(item["Email"], "Happy Birthday", msg) writeInd.append(index) for i in writeInd: yr = dataframe.loc[i, "Year"] # this will record the years in which email has been sent dataframe.loc[i, "Year"] = str(yr) + "," + str(yearNow) dataframe.to_excel("Path-of-your-excel-sheet", index=False)
33.103448
76
0.633333
import pandas as pd import datetime import smtplib GMAIL_ID = "Your-Gmail-Id" GMAIL_PWD = "Your-Gmail-Password" def sendEmail(to, sub, msg): gmail_obj = smtplib.SMTP("smtp.gmail.com", 587) gmail_obj.starttls() gmail_obj.login(GMAIL_ID, GMAIL_PWD) gmail_obj.sendmail(GMAIL_ID, to, f"Subject : {sub}\n\n{msg}") gmail_obj.quit() print( "Email sent to " + str(to) + " with subject " + str(sub) + " and message :" + str(msg) ) if __name__ == "__main__": dataframe = pd.read_excel("Path-of-your-excel-sheet") today = datetime.datetime.now().strftime("%d-%m") yearNow = datetime.datetime.now().strftime("%Y") writeInd = [] for index, item in dataframe.iterrows(): msg = "Many Many Happy Returns of the day dear " + str(item["Name"]) bday = item["Birthday"].strftime("%d-%m") if (today == bday) and yearNow not in str(item["Year"]): sendEmail(item["Email"], "Happy Birthday", msg) writeInd.append(index) for i in writeInd: yr = dataframe.loc[i, "Year"] dataframe.loc[i, "Year"] = str(yr) + "," + str(yearNow) dataframe.to_excel("Path-of-your-excel-sheet", index=False)
true
true
1c3beb7ba9f14915689bdfcdc1df88061029b323
3,957
py
Python
src/problem2.py
kreftrl/08-Exam1-201920
e129f87dc43e8432741340a137da58851a94da6c
[ "MIT" ]
null
null
null
src/problem2.py
kreftrl/08-Exam1-201920
e129f87dc43e8432741340a137da58851a94da6c
[ "MIT" ]
null
null
null
src/problem2.py
kreftrl/08-Exam1-201920
e129f87dc43e8432741340a137da58851a94da6c
[ "MIT" ]
null
null
null
""" Exam 1, problem 2. Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Mark Hays, Amanda Stouder, Aaron Wilkin, their colleagues, and Robert Kreft. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. def main(): """ Calls the TEST functions in this module. """ test_factor_sum() def test_factor_sum(): """ Tests the factor_sum function. """ ########################################################################### # DONE: 2. Implement this TEST function, as follows: # # 1. Read the doc-string of the factor_sum function defined below. # # 2. Add to THIS function at least ** 5 ** tests that, taken together, # would form a ** REASONABLY GOOD test set ** # for testing the factor_sum function defined below. # # Use the usual format: # Test XXX: # expected = XXX # actual = XXX # print() # print('Expected:', expected) # print('Actual: ', actual) # # IMPORTANT: # The function that you are TESTING is PURPOSELY implemented INCORRECTLY # (it just returns 0). Do NOT implement the factor_sum function. # Just write these TESTS of that function after reading its doc-string. ########################################################################### print() print('---------------------------------------------------------') print('Testing the factor_sum function:') print('---------------------------------------------------------') ########################################################################### # WRITE YOUR TESTS BELOW HERE: ########################################################################### # 1 prime number test and 2 evens and 2 odds # Test 1: expected = 30 actual = factor_sum(29) print() print('Expected:', expected) print('Actual: ', actual) # Test 2: expected = 39 actual = factor_sum(18) print() print('Expected:', expected) print('Actual: ', actual) # Test 3: expected = 32 actual = factor_sum(21) print() print('Expected:', expected) print('Actual: ', actual) # Test 4: expected = 63 actual = factor_sum(32) print() print('Expected:', expected) print('Actual: ', actual) # Test 5: expected = 78 actual = factor_sum(45) print() print('Expected:', expected) print('Actual: ', actual) def factor_sum(n): """ Given a positive integer n, returns the sum of the digits of the sum of the distinct factors of n, where a FACTOR of n is an integer that divides evenly into n. For example, if n is 28, this function returns 11, because: -- the distinct factors of n are: 1 2 4 7 14 28 -- and the sum of those numbers is 1 + 2 + 4 + 7 + 14 + 28, which is 56 -- and the sum of the digits of 56 is 11, so this function returns 11 when n is 28. As another example, if n is 25, this function returns 4, because: -- the distinct factors of n are: 1 5 25 -- and the sum of those numbers is 1 + 5 + 25, which is 31 -- and the sum of the digits of 31 is 4, so this function returns 4 when n is 28. *** ASK FOR AN EXPLANATION IF YOU DO NOT UNDERSTAND THE ABOVE. *** """ ########################################################################### # This function is PURPOSELY implemented INCORRECTLY (it just returns 0). # DO NOT IMPLEMENT factor_sum. Just leave it as it is (returning 0). ########################################################################### return 0 ########################################################################### # DO NOT modify the above line of code! ########################################################################### main()
35.648649
79
0.481425
def main(): test_factor_sum() def test_factor_sum():
true
true
1c3bec99c0a4743386bda3a0b5ce0d83658fb9f0
12,378
py
Python
ipyvolume/test_all.py
mpu-creare/ipyvolume
ad7eca3a994fad9532a0c3eb52223c10eb4ee586
[ "MIT" ]
1
2019-04-09T11:57:07.000Z
2019-04-09T11:57:07.000Z
ipyvolume/test_all.py
mpu-creare/ipyvolume
ad7eca3a994fad9532a0c3eb52223c10eb4ee586
[ "MIT" ]
null
null
null
ipyvolume/test_all.py
mpu-creare/ipyvolume
ad7eca3a994fad9532a0c3eb52223c10eb4ee586
[ "MIT" ]
null
null
null
from __future__ import absolute_import import ipyvolume import ipyvolume.pylab as p3 import ipyvolume as ipv import ipyvolume.examples import ipyvolume.datasets import ipyvolume.utils import ipyvolume.serialize import numpy as np import os import shutil import json import pytest # helpful to remove previous test results for development if os.path.exists("tmp"): shutil.rmtree("tmp") os.makedirs("tmp") def test_serialize(): assert ipyvolume.serialize.array_sequence_to_binary_or_json(1) == 1 assert ipyvolume.serialize.array_sequence_to_binary_or_json([]) == [] empty_array = np.array([]) assert ipyvolume.serialize.array_sequence_to_binary_or_json(empty_array) == [] assert type(ipyvolume.serialize.array_sequence_to_binary_or_json(empty_array)) == list value = np.asarray(5) assert ipyvolume.serialize.array_sequence_to_binary_or_json(value) == 5 value = np.asarray(5) assert ipyvolume.serialize.array_sequence_to_binary_or_json(value) == 5 def test_serialize_cube(): cube = np.zeros((100, 200, 300)) tiles, tile_shape, rows, columns, slices = ipv.serialize._cube_to_tiles(cube, 0, 1) assert len(tiles.shape) == 3 # should be 2d + 1d for channels f = ipv.serialize.StringIO() ipv.serialize.cube_to_png(cube, 0, 1, f) assert len(f.getvalue()) > 0 def test_tile_size(): rows, columns, image_width, image_height = ipyvolume.serialize._compute_tile_size((256, 256, 256)) # expect 16x16, assert rows == 16 assert columns == 16 assert image_width == 256*16 assert image_height == 256*16 rows, columns, image_width, image_height = ipyvolume.serialize._compute_tile_size((254, 254, 254)) # expect the same, everything upscaled to a power of 2 assert rows == 16 assert columns == 16 assert image_width == 256*16 assert image_height == 256*16 ipyvolume.serialize.max_texture_width = 256*8 rows, columns, image_width, image_height = ipyvolume.serialize._compute_tile_size((254, 254, 254)) assert rows == 32 assert columns == 8 assert image_width == 256*8 assert image_height == 256*32 ipyvolume.serialize.min_texture_width = 16*8 rows, columns, image_width, image_height = ipyvolume.serialize._compute_tile_size((16, 16, 16)) assert rows == 2 assert columns == 8 assert image_width == 128 assert image_height == 128 # this is the min texture size ipyvolume.serialize.min_texture_width = 16*8 rows, columns, image_width, image_height = ipyvolume.serialize._compute_tile_size((15, 15, 15)) assert rows == 2 assert columns == 8 assert image_width == 128 assert image_height == 128 # this is the min texture size def test_figure(): f1 = p3.figure() f2 = p3.figure(2) f3 = p3.figure() f4 = p3.figure(2) f5 = p3.gcf() p3.clear() f6 = p3.gcf() assert f1 != f2 assert f2 != f3 assert f3 != f4 assert f2 == f2 assert f4 == f5 assert f5 != f6 f7 = p3.figure('f7') f8 = p3.figure() f9 = p3.figure('f7') f10 = p3.figure(f8) f11 = p3.gcf() f12 = p3.current.figure f13 = p3.figure('f7') f14 = p3.current.figures['f7'] assert f7 == f9 assert f8 == f10 assert f10 == f11 assert f11 == f12 assert f13 == f14 for controls in [True, False]: for debug in [True, False]: p3.figure(debug=debug, controls=controls) def test_context(): f1 = ipv.figure(1) f2 = ipv.figure(2) f3 = ipv.figure(2) assert ipv.gcf() is f3 with f2: assert ipv.gcf() is f2 assert ipv.gcf() is f3 # test nested with f2: assert ipv.gcf() is f2 with f1: assert ipv.gcf() is f1 assert ipv.gcf() is f2 assert ipv.gcf() is f3 def test_limits(): f = p3.figure() p3.xlim(-10, 11) assert f.xlim[0] == -10 assert f.xlim[1] == 11 p3.ylim(-12, 13) assert f.ylim[0] == -12 assert f.ylim[1] == 13 p3.zlim(-14, 15) assert f.zlim[0] == -14 assert f.zlim[1] == 15 p3.xyzlim(-17, 17) assert f.xlim[0] == -17 assert f.xlim[1] == 17 assert f.ylim[0] == -17 assert f.ylim[1] == 17 assert f.zlim[0] == -17 assert f.zlim[1] == 17 # TODO: actually, default xlim should be None, and the limits should # then now grow, but 'move' around the new point f = ipv.figure() assert f.xlim == [0, 1] ipv.ylim(0, 10) ipv.zlim(-10, 0) ipv.scatter(3, 4, 5) assert f.xlim == [0, 3] assert f.ylim == [0, 10] assert f.zlim == [-10, 5] f = ipv.figure() ipv.volshow(np.random.rand(5, 5, 5), extent=[[0.1, 0.9], [0.5, 2], [-2, 5]]) assert f.xlim == [0, 1] assert f.ylim == [0, 2] assert f.zlim == [-2, 5] def test_style(): f = ipv.figure() ipv.style.use('nobox') assert f.style['box']['visible'] == False ipv.style.use(['nobox', {'box': {'visible': True}}]) assert f.style['box']['visible'] == True ipv.style.use({'box': {'visible': False}}) assert f.style['box']['visible'] == False ipv.style.use({'axes': {'visible': False}}) assert f.style['axes']['visible'] == False ipv.style.axes_off() assert f.style['axes']['visible'] == False ipv.style.axes_on() assert f.style['axes']['visible'] == True ipv.style.box_off() assert f.style['box']['visible'] == False ipv.style.box_on() assert f.style['box']['visible'] == True ipv.style.set_style_light() assert f.style['background-color'] == 'white' ipv.style.box_off() assert f.style['box']['visible'] == False assert f.style['background-color'] == 'white' # keep old style settings def test_labels(): f = p3.figure() p3.xlabel("x1") p3.ylabel("y1") p3.zlabel("z1") assert f.xlabel == "x1" assert f.ylabel == "y1" assert f.zlabel == "z1" p3.xyzlabel("x2", "y2", "z2") assert f.xlabel == "x2" assert f.ylabel == "y2" assert f.zlabel == "z2" def test_scatter(): x, y, z = np.random.random((3, 100)) p3.scatter(x, y, z) p3.save("tmp/ipyolume_scatter.html") def test_plot(): x, y, z = np.random.random((3, 100)) p3.plot(x, y, z) p3.save("tmp/ipyolume_plot.html") def test_quiver(): x, y, z, u, v, w = np.random.random((6, 100)) p3.quiver(x, y, z, u, v, w) p3.save("tmp/ipyolume_quiver.html") def test_quiver_exception(): x, y, z, u, v, w = np.random.random((6, 100)) with pytest.raises(KeyError): p3.quiver(x, y, z, u, v, w, vx=u) def test_volshow(): x, y, z = ipyvolume.examples.xyz() p3.volshow(x*y*z) p3.volshow(x*y*z, level=1) p3.volshow(x*y*z, opacity=1) p3.volshow(x*y*z, level_width=1) p3.save("tmp/ipyolume_volume.html") def test_bokeh(): from bokeh.io import output_notebook, show from bokeh.plotting import figure import ipyvolume.bokeh x, y, z = np.random.random((3, 100)) p3.figure() scatter = p3.scatter(x, y, z) tools = "wheel_zoom,box_zoom,box_select,lasso_select,help,reset," p = figure(title="E Lz space", tools=tools, width=500, height=500) r = p.circle(x, y, color="navy", alpha=0.2) ipyvolume.bokeh.link_data_source_selection_to_widget(r.data_source, scatter, 'selected') from bokeh.resources import CDN from bokeh.embed import components script, div = components(p) template_options = dict(extra_script_head=script + CDN.render_js() + CDN.render_css(), body_pre="<h2>Do selections in 2d (bokeh)<h2>" + div + "<h2>And see the selection in ipyvolume<h2>") ipyvolume.embed.embed_html("tmp/bokeh.html", [p3.gcc(), ipyvolume.bokeh.wmh], all_states=True, template_options=template_options) def test_quick(): x, y, z = ipyvolume.examples.xyz() p3.volshow(x*y*z) ipyvolume.quickvolshow(x*y*z, lighting=True) ipyvolume.quickvolshow(x*y*z, lighting=True, level=1, opacity=1, level_width=1) x, y, z, u, v, w = np.random.random((6, 100)) ipyvolume.quickscatter(x, y, z) ipyvolume.quickquiver(x, y, z, u, v, w) @pytest.mark.parametrize("performance", [0,1]) def test_widgets_state(performance): try: _remove_buffers = None try: from ipywidgets.widgets.widget import _remove_buffers except: pass ipyvolume.serialize.performance = performance x, y, z = np.random.random((3, 100)) p3.figure() scatter = p3.scatter(x, y, z) state = scatter.get_state() if _remove_buffers: _remove_buffers(state) else: scatter._split_state_buffers(state) finally: ipyvolume.serialize.performance = 0 def test_download(): url = "https://github.com/maartenbreddels/ipyvolume/raw/master/datasets/hdz2000.npy.bz2" ipyvolume.utils.download_to_file(url, "tmp/test_download.npy.bz2", chunk_size=None) assert os.path.exists("tmp/test_download.npy.bz2") ipyvolume.utils.download_to_file(url, "tmp/test_download2.npy.bz2", chunk_size=1000) assert os.path.exists("tmp/test_download2.npy.bz2") filesize = os.path.getsize("tmp/test_download.npy.bz2") content, encoding = ipyvolume.utils.download_to_bytes(url, chunk_size=None) assert len(content) == filesize content, encoding = ipyvolume.utils.download_to_bytes(url, chunk_size=1000) assert len(content) == filesize byte_list = list(ipyvolume.utils.download_yield_bytes(url, chunk_size=1000)) # write the first chunk of the url to file then attempt to resume the download with open("tmp/test_download3.npy.bz2", 'wb') as f: f.write(byte_list[0]) ipyvolume.utils.download_to_file(url, "tmp/test_download3.npy.bz2", resume=True) def test_embed(): p3.clear() x, y, z = np.random.random((3, 100)) p3.scatter(x, y, z) p3.save("tmp/ipyolume_scatter_online.html", offline=False) assert os.path.getsize("tmp/ipyolume_scatter_online.html") > 0 p3.save("tmp/ipyolume_scatter_offline.html", offline=True, scripts_path='js/subdir') assert os.path.getsize("tmp/ipyolume_scatter_offline.html") > 0 def test_threejs_version(): # a quick check, as a reminder to change if threejs version is updated configpath = os.path.join(os.path.abspath(ipyvolume.__path__[0]), "..", "js", "package.json") with open(configpath) as f: config = json.load(f) major, minor = ipyvolume._version.__version_threejs__.split(".") major_js, minor_js, patch_js = config['dependencies']['three'][1:].split(".") version_msg = "version in python and js side for three js conflect: %s vs %s" % ( ipyvolume._version.__version_threejs__, config['dependencies']['three']) assert (major == major_js) and (minor == minor_js), version_msg def test_animation_control(): fig = ipv.figure() n_points = 3 n_frames = 4 ar = np.zeros(n_points) ar_frames = np.zeros((n_frames, n_points)) colors = np.zeros((n_points, 3)) colors_frames = np.zeros((n_frames, n_points, 3)) scalar = 2 s = ipv.scatter(x=scalar, y=scalar, z=scalar) with pytest.raises(ValueError): # no animation present slider = ipv.animation_control(s, add=False).children[1] s = ipv.scatter(x=ar, y=scalar, z=scalar) slider = ipv.animation_control(s, add=False).children[1] assert slider.max == n_points - 1 s = ipv.scatter(x=ar_frames, y=scalar, z=scalar) slider = ipv.animation_control(s, add=False).children[1] assert slider.max == n_frames - 1 s = ipv.scatter(x=scalar, y=scalar, z=scalar, color=colors_frames) slider = ipv.animation_control(s, add=False).children[1] assert slider.max == n_frames - 1 Nx, Ny = 10, 7 x = np.arange(Nx) y = np.arange(Ny) x, y = np.meshgrid(x, y) z = x + y m = ipv.plot_surface(x, y, z) with pytest.raises(ValueError): # no animation present slider = ipv.animation_control(m, add=False).children[1] z = [x + y * k for k in range(n_frames)] m = ipv.plot_surface(x, y, z) slider = ipv.animation_control(m, add=False).children[1] assert slider.max == n_frames - 1 # just cover and call ipyvolume.examples.ball() ipyvolume.examples.example_ylm() ipyvolume.datasets.aquariusA2.fetch() ipyvolume.datasets.hdz2000.fetch() ipyvolume.datasets.zeldovich.fetch()
31.738462
128
0.643319
from __future__ import absolute_import import ipyvolume import ipyvolume.pylab as p3 import ipyvolume as ipv import ipyvolume.examples import ipyvolume.datasets import ipyvolume.utils import ipyvolume.serialize import numpy as np import os import shutil import json import pytest if os.path.exists("tmp"): shutil.rmtree("tmp") os.makedirs("tmp") def test_serialize(): assert ipyvolume.serialize.array_sequence_to_binary_or_json(1) == 1 assert ipyvolume.serialize.array_sequence_to_binary_or_json([]) == [] empty_array = np.array([]) assert ipyvolume.serialize.array_sequence_to_binary_or_json(empty_array) == [] assert type(ipyvolume.serialize.array_sequence_to_binary_or_json(empty_array)) == list value = np.asarray(5) assert ipyvolume.serialize.array_sequence_to_binary_or_json(value) == 5 value = np.asarray(5) assert ipyvolume.serialize.array_sequence_to_binary_or_json(value) == 5 def test_serialize_cube(): cube = np.zeros((100, 200, 300)) tiles, tile_shape, rows, columns, slices = ipv.serialize._cube_to_tiles(cube, 0, 1) assert len(tiles.shape) == 3 f = ipv.serialize.StringIO() ipv.serialize.cube_to_png(cube, 0, 1, f) assert len(f.getvalue()) > 0 def test_tile_size(): rows, columns, image_width, image_height = ipyvolume.serialize._compute_tile_size((256, 256, 256)) assert rows == 16 assert columns == 16 assert image_width == 256*16 assert image_height == 256*16 rows, columns, image_width, image_height = ipyvolume.serialize._compute_tile_size((254, 254, 254)) assert rows == 16 assert columns == 16 assert image_width == 256*16 assert image_height == 256*16 ipyvolume.serialize.max_texture_width = 256*8 rows, columns, image_width, image_height = ipyvolume.serialize._compute_tile_size((254, 254, 254)) assert rows == 32 assert columns == 8 assert image_width == 256*8 assert image_height == 256*32 ipyvolume.serialize.min_texture_width = 16*8 rows, columns, image_width, image_height = ipyvolume.serialize._compute_tile_size((16, 16, 16)) assert rows == 2 assert columns == 8 assert image_width == 128 assert image_height == 128 ipyvolume.serialize.min_texture_width = 16*8 rows, columns, image_width, image_height = ipyvolume.serialize._compute_tile_size((15, 15, 15)) assert rows == 2 assert columns == 8 assert image_width == 128 assert image_height == 128 def test_figure(): f1 = p3.figure() f2 = p3.figure(2) f3 = p3.figure() f4 = p3.figure(2) f5 = p3.gcf() p3.clear() f6 = p3.gcf() assert f1 != f2 assert f2 != f3 assert f3 != f4 assert f2 == f2 assert f4 == f5 assert f5 != f6 f7 = p3.figure('f7') f8 = p3.figure() f9 = p3.figure('f7') f10 = p3.figure(f8) f11 = p3.gcf() f12 = p3.current.figure f13 = p3.figure('f7') f14 = p3.current.figures['f7'] assert f7 == f9 assert f8 == f10 assert f10 == f11 assert f11 == f12 assert f13 == f14 for controls in [True, False]: for debug in [True, False]: p3.figure(debug=debug, controls=controls) def test_context(): f1 = ipv.figure(1) f2 = ipv.figure(2) f3 = ipv.figure(2) assert ipv.gcf() is f3 with f2: assert ipv.gcf() is f2 assert ipv.gcf() is f3 with f2: assert ipv.gcf() is f2 with f1: assert ipv.gcf() is f1 assert ipv.gcf() is f2 assert ipv.gcf() is f3 def test_limits(): f = p3.figure() p3.xlim(-10, 11) assert f.xlim[0] == -10 assert f.xlim[1] == 11 p3.ylim(-12, 13) assert f.ylim[0] == -12 assert f.ylim[1] == 13 p3.zlim(-14, 15) assert f.zlim[0] == -14 assert f.zlim[1] == 15 p3.xyzlim(-17, 17) assert f.xlim[0] == -17 assert f.xlim[1] == 17 assert f.ylim[0] == -17 assert f.ylim[1] == 17 assert f.zlim[0] == -17 assert f.zlim[1] == 17 f = ipv.figure() assert f.xlim == [0, 1] ipv.ylim(0, 10) ipv.zlim(-10, 0) ipv.scatter(3, 4, 5) assert f.xlim == [0, 3] assert f.ylim == [0, 10] assert f.zlim == [-10, 5] f = ipv.figure() ipv.volshow(np.random.rand(5, 5, 5), extent=[[0.1, 0.9], [0.5, 2], [-2, 5]]) assert f.xlim == [0, 1] assert f.ylim == [0, 2] assert f.zlim == [-2, 5] def test_style(): f = ipv.figure() ipv.style.use('nobox') assert f.style['box']['visible'] == False ipv.style.use(['nobox', {'box': {'visible': True}}]) assert f.style['box']['visible'] == True ipv.style.use({'box': {'visible': False}}) assert f.style['box']['visible'] == False ipv.style.use({'axes': {'visible': False}}) assert f.style['axes']['visible'] == False ipv.style.axes_off() assert f.style['axes']['visible'] == False ipv.style.axes_on() assert f.style['axes']['visible'] == True ipv.style.box_off() assert f.style['box']['visible'] == False ipv.style.box_on() assert f.style['box']['visible'] == True ipv.style.set_style_light() assert f.style['background-color'] == 'white' ipv.style.box_off() assert f.style['box']['visible'] == False assert f.style['background-color'] == 'white' def test_labels(): f = p3.figure() p3.xlabel("x1") p3.ylabel("y1") p3.zlabel("z1") assert f.xlabel == "x1" assert f.ylabel == "y1" assert f.zlabel == "z1" p3.xyzlabel("x2", "y2", "z2") assert f.xlabel == "x2" assert f.ylabel == "y2" assert f.zlabel == "z2" def test_scatter(): x, y, z = np.random.random((3, 100)) p3.scatter(x, y, z) p3.save("tmp/ipyolume_scatter.html") def test_plot(): x, y, z = np.random.random((3, 100)) p3.plot(x, y, z) p3.save("tmp/ipyolume_plot.html") def test_quiver(): x, y, z, u, v, w = np.random.random((6, 100)) p3.quiver(x, y, z, u, v, w) p3.save("tmp/ipyolume_quiver.html") def test_quiver_exception(): x, y, z, u, v, w = np.random.random((6, 100)) with pytest.raises(KeyError): p3.quiver(x, y, z, u, v, w, vx=u) def test_volshow(): x, y, z = ipyvolume.examples.xyz() p3.volshow(x*y*z) p3.volshow(x*y*z, level=1) p3.volshow(x*y*z, opacity=1) p3.volshow(x*y*z, level_width=1) p3.save("tmp/ipyolume_volume.html") def test_bokeh(): from bokeh.io import output_notebook, show from bokeh.plotting import figure import ipyvolume.bokeh x, y, z = np.random.random((3, 100)) p3.figure() scatter = p3.scatter(x, y, z) tools = "wheel_zoom,box_zoom,box_select,lasso_select,help,reset," p = figure(title="E Lz space", tools=tools, width=500, height=500) r = p.circle(x, y, color="navy", alpha=0.2) ipyvolume.bokeh.link_data_source_selection_to_widget(r.data_source, scatter, 'selected') from bokeh.resources import CDN from bokeh.embed import components script, div = components(p) template_options = dict(extra_script_head=script + CDN.render_js() + CDN.render_css(), body_pre="<h2>Do selections in 2d (bokeh)<h2>" + div + "<h2>And see the selection in ipyvolume<h2>") ipyvolume.embed.embed_html("tmp/bokeh.html", [p3.gcc(), ipyvolume.bokeh.wmh], all_states=True, template_options=template_options) def test_quick(): x, y, z = ipyvolume.examples.xyz() p3.volshow(x*y*z) ipyvolume.quickvolshow(x*y*z, lighting=True) ipyvolume.quickvolshow(x*y*z, lighting=True, level=1, opacity=1, level_width=1) x, y, z, u, v, w = np.random.random((6, 100)) ipyvolume.quickscatter(x, y, z) ipyvolume.quickquiver(x, y, z, u, v, w) @pytest.mark.parametrize("performance", [0,1]) def test_widgets_state(performance): try: _remove_buffers = None try: from ipywidgets.widgets.widget import _remove_buffers except: pass ipyvolume.serialize.performance = performance x, y, z = np.random.random((3, 100)) p3.figure() scatter = p3.scatter(x, y, z) state = scatter.get_state() if _remove_buffers: _remove_buffers(state) else: scatter._split_state_buffers(state) finally: ipyvolume.serialize.performance = 0 def test_download(): url = "https://github.com/maartenbreddels/ipyvolume/raw/master/datasets/hdz2000.npy.bz2" ipyvolume.utils.download_to_file(url, "tmp/test_download.npy.bz2", chunk_size=None) assert os.path.exists("tmp/test_download.npy.bz2") ipyvolume.utils.download_to_file(url, "tmp/test_download2.npy.bz2", chunk_size=1000) assert os.path.exists("tmp/test_download2.npy.bz2") filesize = os.path.getsize("tmp/test_download.npy.bz2") content, encoding = ipyvolume.utils.download_to_bytes(url, chunk_size=None) assert len(content) == filesize content, encoding = ipyvolume.utils.download_to_bytes(url, chunk_size=1000) assert len(content) == filesize byte_list = list(ipyvolume.utils.download_yield_bytes(url, chunk_size=1000)) with open("tmp/test_download3.npy.bz2", 'wb') as f: f.write(byte_list[0]) ipyvolume.utils.download_to_file(url, "tmp/test_download3.npy.bz2", resume=True) def test_embed(): p3.clear() x, y, z = np.random.random((3, 100)) p3.scatter(x, y, z) p3.save("tmp/ipyolume_scatter_online.html", offline=False) assert os.path.getsize("tmp/ipyolume_scatter_online.html") > 0 p3.save("tmp/ipyolume_scatter_offline.html", offline=True, scripts_path='js/subdir') assert os.path.getsize("tmp/ipyolume_scatter_offline.html") > 0 def test_threejs_version(): configpath = os.path.join(os.path.abspath(ipyvolume.__path__[0]), "..", "js", "package.json") with open(configpath) as f: config = json.load(f) major, minor = ipyvolume._version.__version_threejs__.split(".") major_js, minor_js, patch_js = config['dependencies']['three'][1:].split(".") version_msg = "version in python and js side for three js conflect: %s vs %s" % ( ipyvolume._version.__version_threejs__, config['dependencies']['three']) assert (major == major_js) and (minor == minor_js), version_msg def test_animation_control(): fig = ipv.figure() n_points = 3 n_frames = 4 ar = np.zeros(n_points) ar_frames = np.zeros((n_frames, n_points)) colors = np.zeros((n_points, 3)) colors_frames = np.zeros((n_frames, n_points, 3)) scalar = 2 s = ipv.scatter(x=scalar, y=scalar, z=scalar) with pytest.raises(ValueError): slider = ipv.animation_control(s, add=False).children[1] s = ipv.scatter(x=ar, y=scalar, z=scalar) slider = ipv.animation_control(s, add=False).children[1] assert slider.max == n_points - 1 s = ipv.scatter(x=ar_frames, y=scalar, z=scalar) slider = ipv.animation_control(s, add=False).children[1] assert slider.max == n_frames - 1 s = ipv.scatter(x=scalar, y=scalar, z=scalar, color=colors_frames) slider = ipv.animation_control(s, add=False).children[1] assert slider.max == n_frames - 1 Nx, Ny = 10, 7 x = np.arange(Nx) y = np.arange(Ny) x, y = np.meshgrid(x, y) z = x + y m = ipv.plot_surface(x, y, z) with pytest.raises(ValueError): slider = ipv.animation_control(m, add=False).children[1] z = [x + y * k for k in range(n_frames)] m = ipv.plot_surface(x, y, z) slider = ipv.animation_control(m, add=False).children[1] assert slider.max == n_frames - 1 ipyvolume.examples.ball() ipyvolume.examples.example_ylm() ipyvolume.datasets.aquariusA2.fetch() ipyvolume.datasets.hdz2000.fetch() ipyvolume.datasets.zeldovich.fetch()
true
true
1c3bedacada37c95d091c6a8334c1be97cfb7e13
17,268
py
Python
hw3/dqn.py
yongjin-shin/homework
0ec67386066be1b1499565d715b6b99dd39954e9
[ "MIT" ]
null
null
null
hw3/dqn.py
yongjin-shin/homework
0ec67386066be1b1499565d715b6b99dd39954e9
[ "MIT" ]
null
null
null
hw3/dqn.py
yongjin-shin/homework
0ec67386066be1b1499565d715b6b99dd39954e9
[ "MIT" ]
null
null
null
import uuid import time import pickle import sys import gym.spaces import itertools import numpy as np import random import tensorflow as tf import tensorflow.contrib.layers as layers from collections import namedtuple from dqn_utils import * OptimizerSpec = namedtuple("OptimizerSpec", ["constructor", "kwargs", "lr_schedule"]) class QLearner(object): def __init__( self, env, q_func, optimizer_spec, session, exploration=LinearSchedule(1000000, 0.1), stopping_criterion=None, replay_buffer_size=1000000, batch_size=32, gamma=0.99, learning_starts=50000, learning_freq=4, frame_history_len=4, target_update_freq=10000, grad_norm_clipping=10, rew_file=None, double_q=True, lander=False): """Run Deep Q-learning algorithm. You can specify your own convnet using q_func. All schedules are w.r.t. total number of steps taken in the environment. Parameters ---------- env: gym.Env gym environment to train on. q_func: function Model to use for computing the q function. It should accept the following named arguments: img_in: tf.Tensor tensorflow tensor representing the input image num_actions: int number of actions scope: str scope in which all the model related variables should be created reuse: bool whether previously created variables should be reused. optimizer_spec: OptimizerSpec Specifying the constructor and kwargs, as well as learning rate schedule for the optimizer session: tf.Session tensorflow session to use. exploration: rl_algs.deepq.utils.schedules.Schedule schedule for probability of chosing random action. stopping_criterion: (env, t) -> bool should return true when it's ok for the RL algorithm to stop. takes in env and the number of steps executed so far. replay_buffer_size: int How many memories to store in the replay buffer. batch_size: int How many transitions to sample each time experience is replayed. gamma: float Discount Factor learning_starts: int After how many environment steps to start replaying experiences learning_freq: int How many steps of environment to take between every experience replay frame_history_len: int How many past frames to include as input to the model. target_update_freq: int How many experience replay rounds (not steps!) to perform between each update to the target Q network grad_norm_clipping: float or None If not None gradients' norms are clipped to this value. double_q: bool If True, then use double Q-learning to compute target values. Otherwise, use vanilla DQN. https://papers.nips.cc/paper/3964-double-q-learning.pdf """ assert type(env.observation_space) == gym.spaces.Box assert type(env.action_space) == gym.spaces.Discrete self.target_update_freq = target_update_freq self.optimizer_spec = optimizer_spec self.batch_size = batch_size self.learning_freq = learning_freq self.learning_starts = learning_starts self.stopping_criterion = stopping_criterion self.env = env self.session = session self.exploration = exploration self.rew_file = str(uuid.uuid4()) + '.pkl' if rew_file is None else rew_file self.gamma = gamma ############### # BUILD MODEL # ############### if len(self.env.observation_space.shape) == 1: # This means we are running on low-dimensional observations (e.g. RAM) input_shape = self.env.observation_space.shape else: img_h, img_w, img_c = self.env.observation_space.shape input_shape = (img_h, img_w, frame_history_len * img_c) self.num_actions = self.env.action_space.n # set up placeholders # placeholder for current observation (or state) self.obs_t_ph = tf.placeholder(tf.float32 if lander else tf.uint8, [None] + list(input_shape)) # placeholder for current action self.act_t_ph = tf.placeholder(tf.int32, [None]) # placeholder for current reward self.rew_t_ph = tf.placeholder(tf.float32, [None]) # placeholder for next observation (or state) self.obs_tp1_ph = tf.placeholder(tf.float32 if lander else tf.uint8, [None] + list(input_shape)) # placeholder for end of episode mask # this value is 1 if the next state corresponds to the end of an episode, # in which case there is no Q-value at the next state; at the end of an # episode, only the current state reward contributes to the target, not the # next state Q-value (i.e. target is just rew_t_ph, not rew_t_ph + gamma * q_tp1) self.done_mask_ph = tf.placeholder(tf.float32, [None]) # casting to float on GPU ensures lower data transfer times. if lander: obs_t_float = self.obs_t_ph obs_tp1_float = self.obs_tp1_ph else: obs_t_float = tf.cast(self.obs_t_ph, tf.float32) / 255.0 obs_tp1_float = tf.cast(self.obs_tp1_ph, tf.float32) / 255.0 # Here, you should fill in your own code to compute the Bellman error. This requires # evaluating the current and next Q-values and constructing the corresponding error. # TensorFlow will differentiate this error for you, you just need to pass it to the # optimizer. See assignment text for details. # Your code should produce one scalar-valued tensor: total_error # This will be passed to the optimizer in the provided code below. # Your code should also produce two collections of variables: # q_func_vars # target_q_func_vars # These should hold all of the variables of the Q-function network and target network, # respectively. A convenient way to get these is to make use of TF's "scope" feature. # For example, you can create your Q-function network with the scope "q_func" like this: # <something> = q_func(obs_t_float, num_actions, scope="q_func", reuse=False) # And then you can obtain the variables like this: # q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='q_func') # Older versions of TensorFlow may require using "VARIABLES" instead of "GLOBAL_VARIABLES" # Tip: use huber_loss (from dqn_utils) instead of squared error when defining self.total_error ###### # YOUR CODE HERE ###### """ 선택해야할 것이 있다면, mask를 활용하자!! (아우 이거 생각한 사람 똑똑하다 증말...) """ # Target function target_value = q_func(obs_tp1_float, self.num_actions, scope='target_func', reuse=False) self.y = self.rew_t_ph + self.gamma * tf.reduce_max(target_value, axis=1) # Q function self.q_value = q_func(obs_t_float, self.num_actions, scope='q_func', reuse=False) mask = tf.one_hot(indices=self.act_t_ph, depth=self.num_actions) masked_q_value = tf.reduce_sum(self.q_value * mask, axis=1) # TD error self.td_error = self.y - masked_q_value self.total_error = tf.reduce_mean(huber_loss(self.td_error, delta=1.0)) target_q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='target_func') q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='q_func') with tf.variable_scope('Optimizer', reuse=False): # construct optimization op (with gradient clipping) self.learning_rate = tf.placeholder(tf.float32, (), name="learning_rate") optimizer = self.optimizer_spec.constructor(learning_rate=self.learning_rate, **self.optimizer_spec.kwargs) self.train_fn = minimize_and_clip(optimizer, self.total_error, var_list=q_func_vars, clip_val=grad_norm_clipping) # update_target_fn will be called periodically to copy Q network to target Q network update_target_fn = [] for var, var_target in zip(sorted(q_func_vars, key=lambda v: v.name), sorted(target_q_func_vars, key=lambda v: v.name)): update_target_fn.append(var_target.assign(var)) self.update_target_fn = tf.group(*update_target_fn) # construct the replay buffer self.replay_buffer = ReplayBuffer(replay_buffer_size, frame_history_len, lander=lander) self.replay_buffer_idx = None ############### # RUN ENV # ############### self.model_initialized = False self.num_param_updates = 0 self.mean_episode_reward = -float('nan') self.best_mean_episode_reward = -float('inf') self.last_obs = self.env.reset() self.log_every_n_steps = 10000 self.start_time = None self.t = 0 def stopping_criterion_met(self): return self.stopping_criterion is not None and self.stopping_criterion(self.env, self.t) @property def step_env(self): # 2. Step the env and store the transition # At this point, "self.last_obs" contains the latest observation that was # recorded from the simulator. Here, your code needs to store this # observation and its outcome (reward, next observation, etc.) into # the replay buffer while stepping the simulator forward one step. # At the end of this block of code, the simulator should have been # advanced one step, and the replay buffer should contain one more # transition. # Specifically, self.last_obs must point to the new latest observation. # Useful functions you'll need to call: # obs, reward, done, info = env.step(action) # this steps the environment forward one step # obs = env.reset() # this resets the environment if you reached an episode boundary. # Don't forget to call env.reset() to get a new observation if done # is true!! # Note that you cannot use "self.last_obs" directly as input # into your network, since it needs to be processed to include context # from previous frames. You should check out the replay buffer # implementation in dqn_utils.py to see what functionality the replay # buffer exposes. The replay buffer has a function called # encode_recent_observation that will take the latest observation # that you pushed into the buffer and compute the corresponding # input that should be given to a Q network by appending some # previous frames. # Don't forget to include epsilon greedy exploration! # And remember that the first time you enter this loop, the model # may not yet have been initialized (but of course, the first step # might as well be random, since you haven't trained your net...) ##### """ Comment가 정확하게 뭘 의미하는지 모르겠음. 쓸데없는 얘기를 적어놓은걸까?? 아니면 내가 이해를 못하는걸까?? Todo 1. minibatch를 만족 못 시킬 경우는 다시 돌아오나?? 2. 0인 경우는 network가 어떻게 처리하려나?? """ self.replay_buffer_idx = self.replay_buffer.store_frame(self.last_obs) if not self.model_initialized or np.random.randn() < self.exploration.value(): act = self.env.action_space.sample() else: prev_obs_frames = self.replay_buffer.encode_recent_observation() q_val = self.session.run(fetches=self.q_value, feed_dict={self.obs_t_ph: prev_obs_frames[None]}) act = tf.reduce_max(q_val, axis=1) next_obs, reward, done, info = self.env.step(act) self.replay_buffer.store_effect(self.replay_buffer_idx, act, reward, done) if done: self.last_obs = self.env.reset() else: self.last_obs = next_obs # YOUR CODE HERE # if not self.replay_buffer.can_sample(self.batch_size): # while not self.replay_buffer.can_sample(self.batch_size): # act = self.env.action_space.sample() # obs, reward, done, info = self.env.step(act) # self.replay_buffer_idx = self.replay_buffer.store_frame(frame=obs) # prev_obs_frames = self.replay_buffer.encode_recent_observation() # self.replay_buffer.store_effect(self.replay_buffer_idx, act, reward, done) # else: return 0 def update_model(self): # 3. Perform experience replay and train the network. # note that this is only done if the replay buffer contains enough samples # for us to learn something useful -- until then, the model will not be # initialized and random actions should be taken if (self.t > self.learning_starts and self.t % self.learning_freq == 0 and self.replay_buffer.can_sample(self.batch_size)): # Here, you should perform training. Training consists of four steps: # 3.a: use the replay buffer to sample a batch of transitions (see the # replay buffer code for function definition, each batch that you sample # should consist of current observations, current actions, rewards, # next observations, and done indicator). # 3.b: initialize the model if it has not been initialized yet; to do # that, call # initialize_interdependent_variables(self.session, tf.global_variables(), { # self.obs_t_ph: obs_t_batch, # self.obs_tp1_ph: obs_tp1_batch, # }) # where obs_t_batch and obs_tp1_batch are the batches of observations at # the current and next time step. The boolean variable model_initialized # indicates whether or not the model has been initialized. # Remember that you have to update the target network too (see 3.d)! # 3.c: train the model. To do this, you'll need to use the self.train_fn and # self.total_error ops that were created earlier: self.total_error is what you # created to compute the total Bellman error in a batch, and self.train_fn # will actually perform a gradient step and update the network parameters # to reduce total_error. When calling self.session.run on these you'll need to # populate the following placeholders: # self.obs_t_ph # self.act_t_ph # self.rew_t_ph # self.obs_tp1_ph # self.done_mask_ph # (this is needed for computing self.total_error) # self.learning_rate -- you can get this from self.optimizer_spec.lr_schedule.value(t) # (this is needed by the optimizer to choose the learning rate) # 3.d: periodically update the target network by calling # self.session.run(self.update_target_fn) # you should update every target_update_freq steps, and you may find the # variable self.num_param_updates useful for this (it was initialized to 0) ##### # YOUR CODE HERE self.num_param_updates += 1 self.t += 1 def log_progress(self): episode_rewards = get_wrapper_by_name(self.env, "Monitor").get_episode_rewards() if len(episode_rewards) > 0: self.mean_episode_reward = np.mean(episode_rewards[-100:]) if len(episode_rewards) > 100: self.best_mean_episode_reward = max(self.best_mean_episode_reward, self.mean_episode_reward) if self.t % self.log_every_n_steps == 0 and self.model_initialized: print("Timestep %d" % (self.t,)) print("mean reward (100 episodes) %f" % self.mean_episode_reward) print("best mean reward %f" % self.best_mean_episode_reward) print("episodes %d" % len(episode_rewards)) print("exploration %f" % self.exploration.value(self.t)) print("learning_rate %f" % self.optimizer_spec.lr_schedule.value(self.t)) if self.start_time is not None: print("running time %f" % ((time.time() - self.start_time) / 60.)) self.start_time = time.time() sys.stdout.flush() with open(self.rew_file, 'wb') as f: pickle.dump(episode_rewards, f, pickle.HIGHEST_PROTOCOL) def learn(*args, **kwargs): alg = QLearner(*args, **kwargs) while not alg.stopping_criterion_met(): alg.step_env # at this point, the environment should have been advanced one step (and # reset if done was true), and self.last_obs should point to the new latest # observation alg.update_model() alg.log_progress()
46.171123
119
0.638754
import uuid import time import pickle import sys import gym.spaces import itertools import numpy as np import random import tensorflow as tf import tensorflow.contrib.layers as layers from collections import namedtuple from dqn_utils import * OptimizerSpec = namedtuple("OptimizerSpec", ["constructor", "kwargs", "lr_schedule"]) class QLearner(object): def __init__( self, env, q_func, optimizer_spec, session, exploration=LinearSchedule(1000000, 0.1), stopping_criterion=None, replay_buffer_size=1000000, batch_size=32, gamma=0.99, learning_starts=50000, learning_freq=4, frame_history_len=4, target_update_freq=10000, grad_norm_clipping=10, rew_file=None, double_q=True, lander=False): assert type(env.observation_space) == gym.spaces.Box assert type(env.action_space) == gym.spaces.Discrete self.target_update_freq = target_update_freq self.optimizer_spec = optimizer_spec self.batch_size = batch_size self.learning_freq = learning_freq self.learning_starts = learning_starts self.stopping_criterion = stopping_criterion self.env = env self.session = session self.exploration = exploration self.rew_file = str(uuid.uuid4()) + '.pkl' if rew_file is None else rew_file self.gamma = gamma tion_space.shape input_shape = (img_h, img_w, frame_history_len * img_c) self.num_actions = self.env.action_space.n self.obs_t_ph = tf.placeholder(tf.float32 if lander else tf.uint8, [None] + list(input_shape)) self.act_t_ph = tf.placeholder(tf.int32, [None]) self.rew_t_ph = tf.placeholder(tf.float32, [None]) self.obs_tp1_ph = tf.placeholder(tf.float32 if lander else tf.uint8, [None] + list(input_shape)) self.done_mask_ph = tf.placeholder(tf.float32, [None]) if lander: obs_t_float = self.obs_t_ph obs_tp1_float = self.obs_tp1_ph else: obs_t_float = tf.cast(self.obs_t_ph, tf.float32) / 255.0 obs_tp1_float = tf.cast(self.obs_tp1_ph, tf.float32) / 255.0 # For example, you can create your Q-function network with the scope "q_func" like this: # <something> = q_func(obs_t_float, num_actions, scope="q_func", reuse=False) # And then you can obtain the variables like this: # q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='q_func') # Older versions of TensorFlow may require using "VARIABLES" instead of "GLOBAL_VARIABLES" # Tip: use huber_loss (from dqn_utils) instead of squared error when defining self.total_error ###### # YOUR CODE HERE ###### # Target function target_value = q_func(obs_tp1_float, self.num_actions, scope='target_func', reuse=False) self.y = self.rew_t_ph + self.gamma * tf.reduce_max(target_value, axis=1) # Q function self.q_value = q_func(obs_t_float, self.num_actions, scope='q_func', reuse=False) mask = tf.one_hot(indices=self.act_t_ph, depth=self.num_actions) masked_q_value = tf.reduce_sum(self.q_value * mask, axis=1) # TD error self.td_error = self.y - masked_q_value self.total_error = tf.reduce_mean(huber_loss(self.td_error, delta=1.0)) target_q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='target_func') q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='q_func') with tf.variable_scope('Optimizer', reuse=False): # construct optimization op (with gradient clipping) self.learning_rate = tf.placeholder(tf.float32, (), name="learning_rate") optimizer = self.optimizer_spec.constructor(learning_rate=self.learning_rate, **self.optimizer_spec.kwargs) self.train_fn = minimize_and_clip(optimizer, self.total_error, var_list=q_func_vars, clip_val=grad_norm_clipping) # update_target_fn will be called periodically to copy Q network to target Q network update_target_fn = [] for var, var_target in zip(sorted(q_func_vars, key=lambda v: v.name), sorted(target_q_func_vars, key=lambda v: v.name)): update_target_fn.append(var_target.assign(var)) self.update_target_fn = tf.group(*update_target_fn) # construct the replay buffer self.replay_buffer = ReplayBuffer(replay_buffer_size, frame_history_len, lander=lander) self.replay_buffer_idx = None ############### # RUN ENV # ############### self.model_initialized = False self.num_param_updates = 0 self.mean_episode_reward = -float('nan') self.best_mean_episode_reward = -float('inf') self.last_obs = self.env.reset() self.log_every_n_steps = 10000 self.start_time = None self.t = 0 def stopping_criterion_met(self): return self.stopping_criterion is not None and self.stopping_criterion(self.env, self.t) @property def step_env(self): # 2. Step the env and store the transition # At this point, "self.last_obs" contains the latest observation that was # recorded from the simulator. Here, your code needs to store this # observation and its outcome (reward, next observation, etc.) into # the replay buffer while stepping the simulator forward one step. # At the end of this block of code, the simulator should have been # advanced one step, and the replay buffer should contain one more # transition. # Specifically, self.last_obs must point to the new latest observation. # Useful functions you'll need to call: # is true!! # Note that you cannot use "self.last_obs" directly as input # into your network, since it needs to be processed to include context # from previous frames. You should check out the replay buffer # implementation in dqn_utils.py to see what functionality the replay # buffer exposes. The replay buffer has a function called # encode_recent_observation that will take the latest observation # that you pushed into the buffer and compute the corresponding # input that should be given to a Q network by appending some # previous frames. # Don't forget to include epsilon greedy exploration! ##### self.replay_buffer_idx = self.replay_buffer.store_frame(self.last_obs) if not self.model_initialized or np.random.randn() < self.exploration.value(): act = self.env.action_space.sample() else: prev_obs_frames = self.replay_buffer.encode_recent_observation() q_val = self.session.run(fetches=self.q_value, feed_dict={self.obs_t_ph: prev_obs_frames[None]}) act = tf.reduce_max(q_val, axis=1) next_obs, reward, done, info = self.env.step(act) self.replay_buffer.store_effect(self.replay_buffer_idx, act, reward, done) if done: self.last_obs = self.env.reset() else: self.last_obs = next_obs # YOUR CODE HERE # if not self.replay_buffer.can_sample(self.batch_size): # while not self.replay_buffer.can_sample(self.batch_size): # act = self.env.action_space.sample() # obs, reward, done, info = self.env.step(act) # self.replay_buffer_idx = self.replay_buffer.store_frame(frame=obs) # prev_obs_frames = self.replay_buffer.encode_recent_observation() # self.replay_buffer.store_effect(self.replay_buffer_idx, act, reward, done) # else: return 0 def update_model(self): # 3. Perform experience replay and train the network. # note that this is only done if the replay buffer contains enough samples # for us to learn something useful -- until then, the model will not be # initialized and random actions should be taken if (self.t > self.learning_starts and self.t % self.learning_freq == 0 and self.replay_buffer.can_sample(self.batch_size)): # Here, you should perform training. Training consists of four steps: # 3.a: use the replay buffer to sample a batch of transitions (see the # replay buffer code for function definition, each batch that you sample # should consist of current observations, current actions, rewards, # next observations, and done indicator). # 3.b: initialize the model if it has not been initialized yet; to do # that, call # initialize_interdependent_variables(self.session, tf.global_variables(), { # self.obs_t_ph: obs_t_batch, # self.obs_tp1_ph: obs_tp1_batch, # }) # where obs_t_batch and obs_tp1_batch are the batches of observations at # the current and next time step. The boolean variable model_initialized # indicates whether or not the model has been initialized. # Remember that you have to update the target network too (see 3.d)! # 3.c: train the model. To do this, you'll need to use the self.train_fn and # populate the following placeholders: # self.obs_t_ph # self.act_t_ph # self.rew_t_ph # self.obs_tp1_ph # self.done_mask_ph # (this is needed for computing self.total_error) # self.learning_rate -- you can get this from self.optimizer_spec.lr_schedule.value(t) # (this is needed by the optimizer to choose the learning rate) # 3.d: periodically update the target network by calling # self.session.run(self.update_target_fn) # you should update every target_update_freq steps, and you may find the # variable self.num_param_updates useful for this (it was initialized to 0) ##### # YOUR CODE HERE self.num_param_updates += 1 self.t += 1 def log_progress(self): episode_rewards = get_wrapper_by_name(self.env, "Monitor").get_episode_rewards() if len(episode_rewards) > 0: self.mean_episode_reward = np.mean(episode_rewards[-100:]) if len(episode_rewards) > 100: self.best_mean_episode_reward = max(self.best_mean_episode_reward, self.mean_episode_reward) if self.t % self.log_every_n_steps == 0 and self.model_initialized: print("Timestep %d" % (self.t,)) print("mean reward (100 episodes) %f" % self.mean_episode_reward) print("best mean reward %f" % self.best_mean_episode_reward) print("episodes %d" % len(episode_rewards)) print("exploration %f" % self.exploration.value(self.t)) print("learning_rate %f" % self.optimizer_spec.lr_schedule.value(self.t)) if self.start_time is not None: print("running time %f" % ((time.time() - self.start_time) / 60.)) self.start_time = time.time() sys.stdout.flush() with open(self.rew_file, 'wb') as f: pickle.dump(episode_rewards, f, pickle.HIGHEST_PROTOCOL) def learn(*args, **kwargs): alg = QLearner(*args, **kwargs) while not alg.stopping_criterion_met(): alg.step_env # at this point, the environment should have been advanced one step (and # reset if done was true), and self.last_obs should point to the new latest # observation alg.update_model() alg.log_progress()
true
true
1c3bedecfccec658a967c782be6d79ce827e2444
968
py
Python
nr_oai_pmh_harvester/rules/nusl/field04107.py
Narodni-repozitar/oai-pmh-harvester
6703f925c404d72385e070445eb5f8af330384d3
[ "MIT" ]
null
null
null
nr_oai_pmh_harvester/rules/nusl/field04107.py
Narodni-repozitar/oai-pmh-harvester
6703f925c404d72385e070445eb5f8af330384d3
[ "MIT" ]
2
2021-01-04T11:40:37.000Z
2021-02-08T12:31:05.000Z
nr_oai_pmh_harvester/rules/nusl/field04107.py
Narodni-repozitar/nr-oai-pmh-harvester
b8c6d76325485fc506a31a94b5533d80cdd04596
[ "MIT" ]
null
null
null
from oarepo_oai_pmh_harvester.decorators import rule from oarepo_taxonomies.utils import get_taxonomy_json from sqlalchemy.orm.exc import NoResultFound @rule("nusl", "marcxml", "/04107", phase="pre") def call_language(el, **kwargs): return language(el, **kwargs) # pragma: no cover def language(el, **kwargs): data = [] if isinstance(el, (list, tuple)): for _ in el: data.extend(get_language_list(_)) # data = get_language_list(data, _) if isinstance(el, dict): data.extend(get_language_list(el)) return { "language": data } def get_language_list(el): res = [] for v in el.values(): lang_taxonomy = get_language_taxonomy(v) if lang_taxonomy: res.extend(lang_taxonomy) return res def get_language_taxonomy(lang_code): try: return get_taxonomy_json(code="languages", slug=lang_code).paginated_data except NoResultFound: pass
25.473684
81
0.659091
from oarepo_oai_pmh_harvester.decorators import rule from oarepo_taxonomies.utils import get_taxonomy_json from sqlalchemy.orm.exc import NoResultFound @rule("nusl", "marcxml", "/04107", phase="pre") def call_language(el, **kwargs): return language(el, **kwargs) def language(el, **kwargs): data = [] if isinstance(el, (list, tuple)): for _ in el: data.extend(get_language_list(_)) if isinstance(el, dict): data.extend(get_language_list(el)) return { "language": data } def get_language_list(el): res = [] for v in el.values(): lang_taxonomy = get_language_taxonomy(v) if lang_taxonomy: res.extend(lang_taxonomy) return res def get_language_taxonomy(lang_code): try: return get_taxonomy_json(code="languages", slug=lang_code).paginated_data except NoResultFound: pass
true
true
1c3beed2175dc230717fc152b35333489f67cfd6
9,366
py
Python
pydft/geometry.py
rosenbrockc/dft
39193cc4c4ac6b151b7ee98f34adb609e412acb4
[ "MIT" ]
6
2017-10-26T07:56:45.000Z
2019-01-17T06:39:33.000Z
pydft/geometry.py
rosenbrockc/dft
39193cc4c4ac6b151b7ee98f34adb609e412acb4
[ "MIT" ]
null
null
null
pydft/geometry.py
rosenbrockc/dft
39193cc4c4ac6b151b7ee98f34adb609e412acb4
[ "MIT" ]
2
2021-11-30T02:33:54.000Z
2022-02-14T12:46:04.000Z
"""Methods and classes for storing and manipulating the global geometry of the physical problem. """ import numpy as np from pydft.base import testmode cell = None """Cell: default geometry to use globally throughout the code when no other geometry is explicitly specified. """ def get_cell(cell_=None): """Returns the cell to use for calculations. """ if cell_ is not None: return cell_ else: return cell def set_cell(cell_): """Sets the global cell to an already initialized instance. Args: cell_ (Cell): new global cell. """ from pydft.bases.fourier import reset_cache reset_cache() global cell cell = cell_ def set_geometry(R, S, X=None, Z=1, grid="MP", f=2): """Sets the global geometry that is used by default in all calculations. Args: R (numpy.ndarray): column lattice vectors of the unit cell for the problem. S (numpy.ndarray): of `int`; defines how many times to divide each of the lattice vectors when defining the descritizing grid. X (numpy.ndarray): of shape (N, 3), where `N` is the number of nucleii in the unit cell. Z (numpy.ndarray or int): specifying the size of charge on each nucleus in `X`. grid (str): one of ['MP', 'BCC']; defines the type of grid to use for sampling *real* space unit cell. f (int): number of electrons per orbital. """ from pydft.bases.fourier import reset_cache reset_cache() global cell cell = Cell(R, S, X, Z, grid, f=f) return cell class Cell(object): """Represents the unit cell in real space *and* the corresponding cell in reciprocal space. Args: R (numpy.ndarray): column lattice vectors of the unit cell for the problem. S (numpy.ndarray): of `int`; defines how many times to divide each of the lattice vectors when defining the descritizing grid. X (numpy.ndarray): of shape (N, 3), where `N` is the number of nucleii in the unit cell. Z (numpy.ndarray or int): specifying the size of charge on each nucleus in `X`. grid (str): one of ['MP', 'BCC']; defines the type of grid to use for sampling *real* space unit cell. f (int): number of electrons per orbital. Attributes: R (numpy.ndarray): column lattice vectors of the unit cell for the problem. S (numpy.ndarray): of `int`; defines how many times to divide each of the lattice vectors when defining the descritizing grid. X (numpy.ndarray): of shape (N, 3), where `N` is the number of nucleii in the unit cell. Z (numpy.ndarray or int): specifying the size of charge on each nucleus in `X`. vol (float): volume of the cell in real space. f (int): number of electrons per orbital. """ def __init__(self, R, S, X=None, Z=1, grid="MP", f=2): self.R = np.array(R) self.S = np.array(S) self.vol = np.linalg.det(self.R) if X is None: self.X = np.array([[0,0,0]]) else: self.X = np.array(X) self.Z = np.array([Z for i in range(len(self.X))]) self.f = f self._M = None """numpy.ndarray: matrix of fractions used to define the points on which the functions are sampled in the unit cell. """ self._N = None """numpy.ndarray: matrix of integers used in computing the Fourier transform of the unit cell sample points. """ self._r = None """numpy.ndarray: points to sample the functions at in the unit cell. """ self._G = None """numpy.ndarray: sample points in reciprocal space. """ self._G2 = None """numpy.ndarray: magnitudes of the sample point vectors in reciprocal space. """ self._K = None """numpy.ndarray: with shape (3, 3); holds the reciprocal lattice vectors for the problem. """ self._Sf = None """numpy.ndarray: with length `self.X.shape[0]`; structure factors for the nucleii in the cell. """ self._dr = None """numpy.ndarray: distance from the center of the cell to each of the sample points. """ if grid != "MP": raise NotImplementedError("Haven't got BCC sampling in place yet.") @property def dr(self): """Returns a matrix of the distance from the center of the cell to each of the sample points. """ if self._dr is None: center = np.sum(self.R, axis=1)/2. self._dr = self.r - center return self._dr @property def K(self): """Reciprocal lattice vectors for the problem. Has shape (3, 3). """ if self._K is None: b1 = 2*np.pi*np.cross(self.R[:,1], self.R[:,2])/self.vol b2 = 2*np.pi*np.cross(self.R[:,2], self.R[:,0])/self.vol b3 = 2*np.pi*np.cross(self.R[:,0], self.R[:,1])/self.vol self._K = np.vstack((b1, b2, b3)).T return self._K @property def Sf(self): """Structure factor for the nuclei in the cell. """ if self._Sf is None: self._Sf = np.sum(np.exp(-1j*np.dot(self.G, self.X.T)), axis=1) return self._Sf @property def r(self): """Points to sample the functions at in the unit cell. """ if self._r is None: Sinv = np.diag(1./self.S) self._r = np.dot(self.M, np.dot(Sinv, self.R.T)) return self._r @property def G(self): """Sample points in reciprocal space. """ if self._G is None: self._G = 2*np.pi*np.dot(self.N, np.linalg.inv(self.R)) return self._G @property def G2(self): """Magnitudes of the sample point vectors in reciprocal space. Returns: numpy.ndarray: of length `np.prod(S)` with magnitude of each `G` vector. """ if self._G2 is None: self._G2 = np.linalg.norm(self.G, axis=1)**2 return self._G2 @property def M(self): """Returns the :math:`M` matrix of integers that determine points at which the functions are sampled in the unit cell. Examples: For `S = [2, 2, 1]`, the returned matrix is: .. code-block:: python np.ndarray([[0,0,0], [1,0,0], [0,1,0], [1,1,0]], dtype=int) """ if self._M is None: ms = np.arange(np.prod(self.S, dtype=int)) m1 = np.fmod(ms, self.S[0]) m2 = np.fmod(np.floor(ms/self.S[0]), self.S[1]) m3 = np.fmod(np.floor(ms/(self.S[0]*self.S[1])), self.S[2]) #Make sure we explicitly use an integer array; it's faster. self._M = np.asarray(np.vstack((m1, m2, m3)).T, dtype=int) return self._M @property def N(self): """"Returns the :math:`N` matrix of integers used in computing the Fourier transform of the unit cell sample points. """ if self._N is None: result = [] for i in range(3): odd = 1 if i % 2 == 1 else 0 m = np.ma.array(self.M[:,i], mask=(self.M[:,i] <= self.S[i]/2)) result.append(m-self.S[i]) self._N = np.array(result).T return self._N def _latvec_plot(self, R=True, withpts=False, legend=False): """Plots the lattice vectors (for real or reciprocal space). """ import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.gca(projection='3d') vecs = self.R if R else self.K for i in range(3): steps = np.linspace(0, 1, np.floor(10*np.linalg.norm(vecs[:,i]))) Ri = vecs[:,i] Ri.shape = (1, 3) steps.shape = (len(steps), 1) line = np.dot(steps, Ri) ax.plot(line[:,0], line[:,1], line[:,2], label="R{0:d}".format(i+1)) if withpts: pts = self.r if R else self.G ax.scatter(pts[:,0], pts[:,1], pts[:,2], color='k') if legend: ax.legend() return (fig, ax) def plot(self, withpts=False): """Plots the unit cell. Args: withpts (bool): when True, the sampling points :attr:`r` are also plotted. """ import matplotlib.pyplot as plt fig, ax = self._latvec_plot(withpts=withpts) plt.title("Real Lattice with Sampling Points") if not testmode: plt.show() def gplot(self, withpts=False): """Plots the reciprocal lattice vectors. Args: withpts (bool): when True, the sampling points in reciprocal space will also be plotted. """ import matplotlib.pyplot as plt fig, ax = self._latvec_plot(R=False, withpts=withpts) plt.title("Reciprocal Lattice with Sampling Points") if not testmode: plt.show()
33.690647
87
0.550822
import numpy as np from pydft.base import testmode cell = None def get_cell(cell_=None): if cell_ is not None: return cell_ else: return cell def set_cell(cell_): from pydft.bases.fourier import reset_cache reset_cache() global cell cell = cell_ def set_geometry(R, S, X=None, Z=1, grid="MP", f=2): from pydft.bases.fourier import reset_cache reset_cache() global cell cell = Cell(R, S, X, Z, grid, f=f) return cell class Cell(object): def __init__(self, R, S, X=None, Z=1, grid="MP", f=2): self.R = np.array(R) self.S = np.array(S) self.vol = np.linalg.det(self.R) if X is None: self.X = np.array([[0,0,0]]) else: self.X = np.array(X) self.Z = np.array([Z for i in range(len(self.X))]) self.f = f self._M = None self._N = None self._r = None self._G = None self._G2 = None self._K = None self._Sf = None self._dr = None if grid != "MP": raise NotImplementedError("Haven't got BCC sampling in place yet.") @property def dr(self): if self._dr is None: center = np.sum(self.R, axis=1)/2. self._dr = self.r - center return self._dr @property def K(self): if self._K is None: b1 = 2*np.pi*np.cross(self.R[:,1], self.R[:,2])/self.vol b2 = 2*np.pi*np.cross(self.R[:,2], self.R[:,0])/self.vol b3 = 2*np.pi*np.cross(self.R[:,0], self.R[:,1])/self.vol self._K = np.vstack((b1, b2, b3)).T return self._K @property def Sf(self): if self._Sf is None: self._Sf = np.sum(np.exp(-1j*np.dot(self.G, self.X.T)), axis=1) return self._Sf @property def r(self): if self._r is None: Sinv = np.diag(1./self.S) self._r = np.dot(self.M, np.dot(Sinv, self.R.T)) return self._r @property def G(self): if self._G is None: self._G = 2*np.pi*np.dot(self.N, np.linalg.inv(self.R)) return self._G @property def G2(self): if self._G2 is None: self._G2 = np.linalg.norm(self.G, axis=1)**2 return self._G2 @property def M(self): if self._M is None: ms = np.arange(np.prod(self.S, dtype=int)) m1 = np.fmod(ms, self.S[0]) m2 = np.fmod(np.floor(ms/self.S[0]), self.S[1]) m3 = np.fmod(np.floor(ms/(self.S[0]*self.S[1])), self.S[2]) #Make sure we explicitly use an integer array; it's faster. self._M = np.asarray(np.vstack((m1, m2, m3)).T, dtype=int) return self._M @property def N(self): if self._N is None: result = [] for i in range(3): odd = 1 if i % 2 == 1 else 0 m = np.ma.array(self.M[:,i], mask=(self.M[:,i] <= self.S[i]/2)) result.append(m-self.S[i]) self._N = np.array(result).T return self._N def _latvec_plot(self, R=True, withpts=False, legend=False): import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.gca(projection='3d') vecs = self.R if R else self.K for i in range(3): steps = np.linspace(0, 1, np.floor(10*np.linalg.norm(vecs[:,i]))) Ri = vecs[:,i] Ri.shape = (1, 3) steps.shape = (len(steps), 1) line = np.dot(steps, Ri) ax.plot(line[:,0], line[:,1], line[:,2], label="R{0:d}".format(i+1)) if withpts: pts = self.r if R else self.G ax.scatter(pts[:,0], pts[:,1], pts[:,2], color='k') if legend: ax.legend() return (fig, ax) def plot(self, withpts=False): import matplotlib.pyplot as plt fig, ax = self._latvec_plot(withpts=withpts) plt.title("Real Lattice with Sampling Points") if not testmode: plt.show() def gplot(self, withpts=False): import matplotlib.pyplot as plt fig, ax = self._latvec_plot(R=False, withpts=withpts) plt.title("Reciprocal Lattice with Sampling Points") if not testmode: plt.show()
true
true
1c3bef64e7ed23c10aae0d0abccd862a01b032ac
10,053
py
Python
tests/test_compare_tools.py
egor43/PyImageComparsion
5270f5646c40391cc5ac225305d7be9b0b7de140
[ "BSD-2-Clause" ]
null
null
null
tests/test_compare_tools.py
egor43/PyImageComparsion
5270f5646c40391cc5ac225305d7be9b0b7de140
[ "BSD-2-Clause" ]
null
null
null
tests/test_compare_tools.py
egor43/PyImageComparsion
5270f5646c40391cc5ac225305d7be9b0b7de140
[ "BSD-2-Clause" ]
null
null
null
""" Модуль содержит юнит-тесты инструментов модуля compare_tools author: https://github.com/egor43 """ import unittest from image_comparsion import image_opener from image_comparsion import image_metrick from image_comparsion import compare_tools class TestCompareTools(unittest.TestCase): """ Набор тестовых кейсов для тестирования функций модуля дополнительного инструментария сравнения изображений """ def setUp(self): """ Подготовка необходимых данных """ self.img1_path = "./tests/files/1.png" with open(self.img1_path, "rb") as image_bs: self.img1 = image_opener.get_img_from_byte_stream(image_bs) self.img2_path = "./tests/files/2.png" with open(self.img2_path, "rb") as image_bs: self.img2 = image_opener.get_img_from_byte_stream(image_bs) self.img3_path = "./tests/files/3.png" with open(self.img3_path, "rb") as image_bs: self.img3 = image_opener.get_img_from_byte_stream(image_bs) self.img4_path = "./tests/files/4.png" with open(self.img4_path, "rb") as image_bs: self.img4 = image_opener.get_img_from_byte_stream(image_bs) self.img5_path = "./tests/files/5.png" with open(self.img5_path, "rb") as image_bs: self.img5 = image_opener.get_img_from_byte_stream(image_bs) def test_hash_match_rates(self): """ Тестирование получения степеней cовпадения хешей изображений """ metricks=("avg", "wav") img1_hashes = image_metrick.image_metricks(self.img1, metricks) img2_hashes = image_metrick.image_metricks(self.img2, metricks) match_rates = compare_tools.hash_match_rates(img1_hashes, img2_hashes) self.assertTrue(match_rates) def test_hash_match_rates_len(self): """ Тестирование количества хешей изображений, возвращаемое при вычислении степеней совпадения """ metricks=("avg", "wav", "dif") img1_hashes = image_metrick.image_metricks(self.img1, metricks) img2_hashes = image_metrick.image_metricks(self.img2, metricks) match_rates = compare_tools.hash_match_rates(img1_hashes, img2_hashes) self.assertEqual(len(match_rates), len(metricks)) def test_hash_match_rates_custom_metrick(self): """ Тестирование получения сепеней совпадения указанных метрик """ metricks=("wav", "dif") img1_hashes = image_metrick.image_metricks(self.img1, metricks) img2_hashes = image_metrick.image_metricks(self.img2, metricks) match_rates = compare_tools.hash_match_rates(img1_hashes, img2_hashes) self.assertTrue("wav" in match_rates) self.assertTrue("dif" in match_rates) def test_hash_match_rates_empty(self): """ Тестирование получения степеней cовпадения пустых хешей изображений """ match_rates = compare_tools.hash_match_rates({}, {}) self.assertFalse(match_rates) def test_image_match_rates(self): """ Тестирование получения степеней овпадения изображений """ match_rates = compare_tools.image_match_rates(self.img1, self.img2) self.assertTrue(match_rates) def test_image_match_rates_for_equals_img(self): """ Тестирование получения 100% степеней совпадений для одинаковых изображений """ match_rates = compare_tools.image_match_rates(self.img1, self.img1) self.assertTrue(all([rate == 100.0 for rate in match_rates.values()])) def test_image_match_rates_for_not_equals_img(self): """ Тестирование получения не 100% степеней совпадений для различных изображений """ match_rates = compare_tools.image_match_rates(self.img1, self.img2) self.assertTrue(all([rate != 100.0 for rate in match_rates.values()])) def test_image_match_rates_with_custom_metrick(self): """ Тестирование получения степеней совпадения по указанным метрикам """ metricks = ("dif", "avg", "per", "wav") match_rates = compare_tools.image_match_rates(self.img1, self.img2, metricks=metricks) self.assertTrue("dif" in match_rates) self.assertTrue("avg" in match_rates) self.assertTrue("per" in match_rates) self.assertTrue("wav" in match_rates) def test_orb_match_rate(self): """ Тестирование получения процента совпадения изображений по дескрипторам ORB детектора """ match_percent = compare_tools.orb_match_rate(self.img2, self.img3) self.assertTrue(match_percent >= 0 and match_percent <= 100) def test_orb_match_rate_for_equals_img(self): """ Тестирование получения близкого к 100% совпадения одинаковых изображений по дескрипторам ORB детектора """ match_percent = compare_tools.orb_match_rate(self.img2, self.img2) self.assertTrue(match_percent >= 97 and match_percent <= 100) def test_image_hash_compare(self): """ Тестирование определения схожести хешей изображений """ match_threshold_hash_percent = 75 self.assertFalse(compare_tools.image_hash_compare(self.img1, self.img2, match_threshold_hash_percent)) def test_image_hash_compare_low_threshold_percent(self): """ Тестирование определения схожести различных хешей изображений при условии низкого порога точности """ match_threshold_hash_percent = 0 self.assertTrue(compare_tools.image_hash_compare(self.img1, self.img2, match_threshold_hash_percent)) def test_image_hash_compare_max_threshold_percent(self): """ Тестирование определения схожести идентичных хешей изображений при условии 100% порога точности """ match_threshold_hash_percent = 100 self.assertTrue(compare_tools.image_hash_compare(self.img2, self.img2, match_threshold_hash_percent)) def test_image_orb_compare(self): """ Тестирование определения схожести ORB дескирпторов изображений """ match_threshold_orb_percent = 75 self.assertFalse(compare_tools.image_orb_compare(self.img2, self.img3, match_threshold_orb_percent)) def test_image_orb_compare_low_threshold_percent(self): """ Тестирование определения схожести различных ORB дескирпторов изображений при условии низкого порога точности """ match_threshold_orb_percent = 0 self.assertTrue(compare_tools.image_orb_compare(self.img2, self.img3, match_threshold_orb_percent)) def test_image_orb_compare_high_threshold_percent(self): """ Тестирование определения схожести идентичных ORB дескирпторов изображений при условии высокого порога точности """ match_threshold_orb_percent = 98 self.assertTrue(compare_tools.image_orb_compare(self.img2, self.img2, match_threshold_orb_percent)) def test_hash_metrick_compare(self): """ Тестирование определения схожести метрик (описывающих хешей) двух изображений. """ img2_metricks = image_metrick.image_metricks(self.img2) img3_metricks = image_metrick.image_metricks(self.img3) self.assertFalse(compare_tools.hash_metrick_compare(img2_metricks, img3_metricks)) def test_hash_metrick_compare_equals(self): """ Тестирование определения схожести метрик (описывающих хешей) двух одинаковых изображений. """ img2_metricks = image_metrick.image_metricks(self.img2) self.assertTrue(compare_tools.hash_metrick_compare(img2_metricks, img2_metricks)) def test_orb_metrick_compare(self): """ Тестирование определения схожести метрик (orb дескрипторов) двух изображений. """ img2_metricks = image_metrick.image_metricks(self.img2) img3_metricks = image_metrick.image_metricks(self.img3) self.assertFalse(compare_tools.orb_metrick_compare(img2_metricks, img3_metricks)) def test_orb_metrick_compare_equals(self): """ Тестирование определения схожести метрик (orb дескрипторов) двух одинаковых изображений. """ img2_metricks = image_metrick.image_metricks(self.img2) self.assertTrue(compare_tools.orb_metrick_compare(img2_metricks, img2_metricks)) def test_grouping_similar_images(self): """ Тестирование группировки похожих изображений """ images = [self.img2, self.img3, self.img4, self.img5] for group in compare_tools.grouping_similar_images(images): self.assertTrue(len(group) > 0) def test_grouping_similar_images_equal(self): """ Тестирование группировки похожих изображений. В случае одинаковых изображений """ images = [self.img2, self.img2, self.img2, self.img2] for group in compare_tools.grouping_similar_images(images): self.assertTrue(len(group) == len(images)) def test_grouping_similar_images_without_orb(self): """ Тестирование группировки похожих изображений. В случае группировки без использования orb дескрипторов """ images = [self.img2, self.img3, self.img4, self.img5] for group in compare_tools.grouping_similar_images(images, with_orb_comparsion=False): self.assertTrue(len(group) > 0) def test_grouping_similar_images_equal_without_orb(self): """ Тестирование группировки похожих изображений. В случае одинаковых изображений и группировки без использования orb дескрипторов """ images = [self.img2, self.img2, self.img2, self.img2] for group in compare_tools.grouping_similar_images(images, with_orb_comparsion=False): self.assertTrue(len(group) == len(images))
42.961538
122
0.685666
import unittest from image_comparsion import image_opener from image_comparsion import image_metrick from image_comparsion import compare_tools class TestCompareTools(unittest.TestCase): def setUp(self): self.img1_path = "./tests/files/1.png" with open(self.img1_path, "rb") as image_bs: self.img1 = image_opener.get_img_from_byte_stream(image_bs) self.img2_path = "./tests/files/2.png" with open(self.img2_path, "rb") as image_bs: self.img2 = image_opener.get_img_from_byte_stream(image_bs) self.img3_path = "./tests/files/3.png" with open(self.img3_path, "rb") as image_bs: self.img3 = image_opener.get_img_from_byte_stream(image_bs) self.img4_path = "./tests/files/4.png" with open(self.img4_path, "rb") as image_bs: self.img4 = image_opener.get_img_from_byte_stream(image_bs) self.img5_path = "./tests/files/5.png" with open(self.img5_path, "rb") as image_bs: self.img5 = image_opener.get_img_from_byte_stream(image_bs) def test_hash_match_rates(self): metricks=("avg", "wav") img1_hashes = image_metrick.image_metricks(self.img1, metricks) img2_hashes = image_metrick.image_metricks(self.img2, metricks) match_rates = compare_tools.hash_match_rates(img1_hashes, img2_hashes) self.assertTrue(match_rates) def test_hash_match_rates_len(self): metricks=("avg", "wav", "dif") img1_hashes = image_metrick.image_metricks(self.img1, metricks) img2_hashes = image_metrick.image_metricks(self.img2, metricks) match_rates = compare_tools.hash_match_rates(img1_hashes, img2_hashes) self.assertEqual(len(match_rates), len(metricks)) def test_hash_match_rates_custom_metrick(self): metricks=("wav", "dif") img1_hashes = image_metrick.image_metricks(self.img1, metricks) img2_hashes = image_metrick.image_metricks(self.img2, metricks) match_rates = compare_tools.hash_match_rates(img1_hashes, img2_hashes) self.assertTrue("wav" in match_rates) self.assertTrue("dif" in match_rates) def test_hash_match_rates_empty(self): match_rates = compare_tools.hash_match_rates({}, {}) self.assertFalse(match_rates) def test_image_match_rates(self): match_rates = compare_tools.image_match_rates(self.img1, self.img2) self.assertTrue(match_rates) def test_image_match_rates_for_equals_img(self): match_rates = compare_tools.image_match_rates(self.img1, self.img1) self.assertTrue(all([rate == 100.0 for rate in match_rates.values()])) def test_image_match_rates_for_not_equals_img(self): match_rates = compare_tools.image_match_rates(self.img1, self.img2) self.assertTrue(all([rate != 100.0 for rate in match_rates.values()])) def test_image_match_rates_with_custom_metrick(self): metricks = ("dif", "avg", "per", "wav") match_rates = compare_tools.image_match_rates(self.img1, self.img2, metricks=metricks) self.assertTrue("dif" in match_rates) self.assertTrue("avg" in match_rates) self.assertTrue("per" in match_rates) self.assertTrue("wav" in match_rates) def test_orb_match_rate(self): match_percent = compare_tools.orb_match_rate(self.img2, self.img3) self.assertTrue(match_percent >= 0 and match_percent <= 100) def test_orb_match_rate_for_equals_img(self): match_percent = compare_tools.orb_match_rate(self.img2, self.img2) self.assertTrue(match_percent >= 97 and match_percent <= 100) def test_image_hash_compare(self): match_threshold_hash_percent = 75 self.assertFalse(compare_tools.image_hash_compare(self.img1, self.img2, match_threshold_hash_percent)) def test_image_hash_compare_low_threshold_percent(self): match_threshold_hash_percent = 0 self.assertTrue(compare_tools.image_hash_compare(self.img1, self.img2, match_threshold_hash_percent)) def test_image_hash_compare_max_threshold_percent(self): match_threshold_hash_percent = 100 self.assertTrue(compare_tools.image_hash_compare(self.img2, self.img2, match_threshold_hash_percent)) def test_image_orb_compare(self): match_threshold_orb_percent = 75 self.assertFalse(compare_tools.image_orb_compare(self.img2, self.img3, match_threshold_orb_percent)) def test_image_orb_compare_low_threshold_percent(self): match_threshold_orb_percent = 0 self.assertTrue(compare_tools.image_orb_compare(self.img2, self.img3, match_threshold_orb_percent)) def test_image_orb_compare_high_threshold_percent(self): match_threshold_orb_percent = 98 self.assertTrue(compare_tools.image_orb_compare(self.img2, self.img2, match_threshold_orb_percent)) def test_hash_metrick_compare(self): img2_metricks = image_metrick.image_metricks(self.img2) img3_metricks = image_metrick.image_metricks(self.img3) self.assertFalse(compare_tools.hash_metrick_compare(img2_metricks, img3_metricks)) def test_hash_metrick_compare_equals(self): img2_metricks = image_metrick.image_metricks(self.img2) self.assertTrue(compare_tools.hash_metrick_compare(img2_metricks, img2_metricks)) def test_orb_metrick_compare(self): img2_metricks = image_metrick.image_metricks(self.img2) img3_metricks = image_metrick.image_metricks(self.img3) self.assertFalse(compare_tools.orb_metrick_compare(img2_metricks, img3_metricks)) def test_orb_metrick_compare_equals(self): img2_metricks = image_metrick.image_metricks(self.img2) self.assertTrue(compare_tools.orb_metrick_compare(img2_metricks, img2_metricks)) def test_grouping_similar_images(self): images = [self.img2, self.img3, self.img4, self.img5] for group in compare_tools.grouping_similar_images(images): self.assertTrue(len(group) > 0) def test_grouping_similar_images_equal(self): images = [self.img2, self.img2, self.img2, self.img2] for group in compare_tools.grouping_similar_images(images): self.assertTrue(len(group) == len(images)) def test_grouping_similar_images_without_orb(self): images = [self.img2, self.img3, self.img4, self.img5] for group in compare_tools.grouping_similar_images(images, with_orb_comparsion=False): self.assertTrue(len(group) > 0) def test_grouping_similar_images_equal_without_orb(self): images = [self.img2, self.img2, self.img2, self.img2] for group in compare_tools.grouping_similar_images(images, with_orb_comparsion=False): self.assertTrue(len(group) == len(images))
true
true
1c3bef769f1d16258c11bb8c78ca85740b02ff61
3,923
py
Python
detect.py
6abi/pi08
fa49d256569ba359ecde0f82a8f03d01db6d6a65
[ "MIT" ]
null
null
null
detect.py
6abi/pi08
fa49d256569ba359ecde0f82a8f03d01db6d6a65
[ "MIT" ]
null
null
null
detect.py
6abi/pi08
fa49d256569ba359ecde0f82a8f03d01db6d6a65
[ "MIT" ]
null
null
null
import tensorflow as tf physical_devices = tf.config.experimental.list_physical_devices('GPU') if len(physical_devices) > 0: tf.config.experimental.set_memory_growth(physical_devices[0], True) from absl import app, flags, logging from absl.flags import FLAGS import core.utils as utils from core.yolov4 import filter_boxes from tensorflow.python.saved_model import tag_constants from PIL import Image import cv2 import numpy as np from tensorflow.compat.v1 import ConfigProto from tensorflow.compat.v1 import InteractiveSession flags.DEFINE_string('framework', 'tflite', '(tf, tflite, trt') flags.DEFINE_string('weights', './checkpoints/yolov4-tiny-416.tflite','path to weights file') flags.DEFINE_integer('size', 416, 'resize images to') flags.DEFINE_boolean('tiny', True, 'yolo or yolo-tiny') flags.DEFINE_string('model', 'yolov4', 'yolov3 or yolov4') flags.DEFINE_string('image', './data/captured_image.jpg', 'path to input image') flags.DEFINE_string('output', './data/result.png', 'path to output image') flags.DEFINE_float('iou', 0.45, 'iou threshold') flags.DEFINE_float('score', 0.60, 'score threshold') def detect_image(_argv): config = ConfigProto() config.gpu_options.allow_growth = True session = InteractiveSession(config=config) STRIDES, ANCHORS, NUM_CLASS, XYSCALE = utils.load_config(FLAGS) input_size = FLAGS.size image_path = FLAGS.image original_image = cv2.imread(image_path) original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB) # image_data = utils.image_preprocess(np.copy(original_image), [input_size, input_size]) image_data = cv2.resize(original_image, (input_size, input_size)) image_data = image_data / 255. # image_data = image_data[np.newaxis, ...].astype(np.float32) images_data = [] for i in range(1): images_data.append(image_data) images_data = np.asarray(images_data).astype(np.float32) if FLAGS.framework == 'tflite': interpreter = tf.lite.Interpreter(model_path=FLAGS.weights) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() print(input_details) print(output_details) interpreter.set_tensor(input_details[0]['index'], images_data) interpreter.invoke() pred = [interpreter.get_tensor(output_details[i]['index']) for i in range(len(output_details))] if FLAGS.model == 'yolov3' and FLAGS.tiny == True: boxes, pred_conf = filter_boxes(pred[1], pred[0], score_threshold=0.60, input_shape=tf.constant([input_size, input_size])) else: boxes, pred_conf = filter_boxes(pred[0], pred[1], score_threshold=0.60, input_shape=tf.constant([input_size, input_size])) else: saved_model_loaded = tf.saved_model.load(FLAGS.weights, tags=[tag_constants.SERVING]) infer = saved_model_loaded.signatures['serving_default'] batch_data = tf.constant(images_data) pred_bbox = infer(batch_data) for key, value in pred_bbox.items(): boxes = value[:, :, 0:4] pred_conf = value[:, :, 4:] boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression( boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)), scores=tf.reshape( pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])), max_output_size_per_class=50, max_total_size=50, iou_threshold=FLAGS.iou, score_threshold=FLAGS.score ) pred_bbox = [boxes.numpy(), scores.numpy(), classes.numpy(), valid_detections.numpy()] image = utils.draw_bbox(original_image, pred_bbox) # image = utils.draw_bbox(image_data*255, pred_bbox) image = Image.fromarray(image.astype(np.uint8)) image.show() image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB) cv2.imwrite(FLAGS.output, image)
42.641304
134
0.708386
import tensorflow as tf physical_devices = tf.config.experimental.list_physical_devices('GPU') if len(physical_devices) > 0: tf.config.experimental.set_memory_growth(physical_devices[0], True) from absl import app, flags, logging from absl.flags import FLAGS import core.utils as utils from core.yolov4 import filter_boxes from tensorflow.python.saved_model import tag_constants from PIL import Image import cv2 import numpy as np from tensorflow.compat.v1 import ConfigProto from tensorflow.compat.v1 import InteractiveSession flags.DEFINE_string('framework', 'tflite', '(tf, tflite, trt') flags.DEFINE_string('weights', './checkpoints/yolov4-tiny-416.tflite','path to weights file') flags.DEFINE_integer('size', 416, 'resize images to') flags.DEFINE_boolean('tiny', True, 'yolo or yolo-tiny') flags.DEFINE_string('model', 'yolov4', 'yolov3 or yolov4') flags.DEFINE_string('image', './data/captured_image.jpg', 'path to input image') flags.DEFINE_string('output', './data/result.png', 'path to output image') flags.DEFINE_float('iou', 0.45, 'iou threshold') flags.DEFINE_float('score', 0.60, 'score threshold') def detect_image(_argv): config = ConfigProto() config.gpu_options.allow_growth = True session = InteractiveSession(config=config) STRIDES, ANCHORS, NUM_CLASS, XYSCALE = utils.load_config(FLAGS) input_size = FLAGS.size image_path = FLAGS.image original_image = cv2.imread(image_path) original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB) image_data = cv2.resize(original_image, (input_size, input_size)) image_data = image_data / 255. images_data = [] for i in range(1): images_data.append(image_data) images_data = np.asarray(images_data).astype(np.float32) if FLAGS.framework == 'tflite': interpreter = tf.lite.Interpreter(model_path=FLAGS.weights) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() print(input_details) print(output_details) interpreter.set_tensor(input_details[0]['index'], images_data) interpreter.invoke() pred = [interpreter.get_tensor(output_details[i]['index']) for i in range(len(output_details))] if FLAGS.model == 'yolov3' and FLAGS.tiny == True: boxes, pred_conf = filter_boxes(pred[1], pred[0], score_threshold=0.60, input_shape=tf.constant([input_size, input_size])) else: boxes, pred_conf = filter_boxes(pred[0], pred[1], score_threshold=0.60, input_shape=tf.constant([input_size, input_size])) else: saved_model_loaded = tf.saved_model.load(FLAGS.weights, tags=[tag_constants.SERVING]) infer = saved_model_loaded.signatures['serving_default'] batch_data = tf.constant(images_data) pred_bbox = infer(batch_data) for key, value in pred_bbox.items(): boxes = value[:, :, 0:4] pred_conf = value[:, :, 4:] boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression( boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)), scores=tf.reshape( pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])), max_output_size_per_class=50, max_total_size=50, iou_threshold=FLAGS.iou, score_threshold=FLAGS.score ) pred_bbox = [boxes.numpy(), scores.numpy(), classes.numpy(), valid_detections.numpy()] image = utils.draw_bbox(original_image, pred_bbox) image = Image.fromarray(image.astype(np.uint8)) image.show() image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB) cv2.imwrite(FLAGS.output, image)
true
true
1c3bf053ead7c364acfd7dd4e6499ef957758d21
2,194
py
Python
cnn_example.py
OleguerCanal/transplanter
854fa727747a484dedde9092eeee6884d7d1b44b
[ "MIT" ]
1
2022-03-23T09:27:56.000Z
2022-03-23T09:27:56.000Z
cnn_example.py
OleguerCanal/transplanter
854fa727747a484dedde9092eeee6884d7d1b44b
[ "MIT" ]
null
null
null
cnn_example.py
OleguerCanal/transplanter
854fa727747a484dedde9092eeee6884d7d1b44b
[ "MIT" ]
null
null
null
import logging from torch.utils.data import DataLoader from src.transplanter import Transplanter from test_models.models import ConvNet from src.datasets import RandomDataset from src.utilities.block_module import BlockModule from src.utilities.helpers import InputShapes from test_models.train_cnn import train logging.basicConfig(level=logging.DEBUG) def print_weights(model): state_dict = {p[0]: p[1] for p in model.named_parameters()} # print(state_dict["hidden_layers.1.conv.weight"].shape) # print(state_dict["hidden_layers.1.conv.bias"].shape) print(state_dict["hidden_layers.0.conv.weight"][0]) print(state_dict["hidden_layers.0.conv.bias"][0]) if __name__ == "__main__": # Intermediate blocks shapes input_shapes_list = [ InputShapes((3, 32, 32), (3, 32, 32)), InputShapes((64, 15, 15), (100, 15, 15)), InputShapes((64, 6, 6), (100, 6, 6)), InputShapes((1024), (1600)), ] teacher_args = {"in_features": 3, "hidden_dim": 64, "out_features": 10, "n_blocks": 3, "flattened_size": 1024} teacher_model = ConvNet.load_from_checkpoint(checkpoint_path="test_models/trained_models/test_1.ckpt", **teacher_args) student_model = ConvNet(3, hidden_dim=100, out_features=10, n_blocks=4, flattened_size=400) print_weights(teacher_model) print_weights(student_model) teacher_block_module = BlockModule(teacher_model) student_block_module = BlockModule(student_model) # print("student_block_module") # print(student_block_module) transplanter = Transplanter() transplanter.transplant(teacher_model=teacher_model, student_model=student_model, input_shapes_list=input_shapes_list) print_weights(student_model) # student_model.out_layer_1.weight.data = teacher_model.out_layer_1.weight.data # # student_model.out_layer_1.bias.data = teacher_model.out_layer_1.bias.data # student_model.out_layer_2.weight.data = teacher_model.out_layer_2.weight.data # # student_model.out_layer_2.bias.data = teacher_model.out_layer_2.bias.data train(student_model, "student_0", data_dir="test_models/data")
38.491228
122
0.72516
import logging from torch.utils.data import DataLoader from src.transplanter import Transplanter from test_models.models import ConvNet from src.datasets import RandomDataset from src.utilities.block_module import BlockModule from src.utilities.helpers import InputShapes from test_models.train_cnn import train logging.basicConfig(level=logging.DEBUG) def print_weights(model): state_dict = {p[0]: p[1] for p in model.named_parameters()} print(state_dict["hidden_layers.0.conv.weight"][0]) print(state_dict["hidden_layers.0.conv.bias"][0]) if __name__ == "__main__": input_shapes_list = [ InputShapes((3, 32, 32), (3, 32, 32)), InputShapes((64, 15, 15), (100, 15, 15)), InputShapes((64, 6, 6), (100, 6, 6)), InputShapes((1024), (1600)), ] teacher_args = {"in_features": 3, "hidden_dim": 64, "out_features": 10, "n_blocks": 3, "flattened_size": 1024} teacher_model = ConvNet.load_from_checkpoint(checkpoint_path="test_models/trained_models/test_1.ckpt", **teacher_args) student_model = ConvNet(3, hidden_dim=100, out_features=10, n_blocks=4, flattened_size=400) print_weights(teacher_model) print_weights(student_model) teacher_block_module = BlockModule(teacher_model) student_block_module = BlockModule(student_model) transplanter = Transplanter() transplanter.transplant(teacher_model=teacher_model, student_model=student_model, input_shapes_list=input_shapes_list) print_weights(student_model)
true
true
1c3bf21f90d9d62e92b23d7aed9f6ad7aecc177a
409
py
Python
python01/PythonCoroutine.py
zhayangtao/HelloPython
e0e8b450afba1382f56411344ad54ef9910a5004
[ "Apache-2.0" ]
null
null
null
python01/PythonCoroutine.py
zhayangtao/HelloPython
e0e8b450afba1382f56411344ad54ef9910a5004
[ "Apache-2.0" ]
1
2017-09-01T03:59:11.000Z
2017-09-01T03:59:11.000Z
python01/PythonCoroutine.py
zhayangtao/HelloPython
e0e8b450afba1382f56411344ad54ef9910a5004
[ "Apache-2.0" ]
null
null
null
# 协程 def consumer(): r = '' while True: n = yield r if not n: return print('[CONSUMER] Consuming %s' % n) r = '200 OK' def produce(c): c.send(None) n = 0 while n < 5: n += 1 print('[PRODUCER] Producing %s' % n) r = c.send(n) print('[PRODUCER] Consumer return: %s' % r) c.close() c = consumer() produce(c)
17.041667
51
0.454768
def consumer(): r = '' while True: n = yield r if not n: return print('[CONSUMER] Consuming %s' % n) r = '200 OK' def produce(c): c.send(None) n = 0 while n < 5: n += 1 print('[PRODUCER] Producing %s' % n) r = c.send(n) print('[PRODUCER] Consumer return: %s' % r) c.close() c = consumer() produce(c)
true
true
1c3bf412148318abb67e3975e1293954678bf770
7,746
py
Python
tdsa_augmentation/data_augmentation/target_extraction_train_predict.py
apmoore1/tdsa_augmentation
71c9ffa79ea48e817408d0dc496cc146ce75a942
[ "Apache-2.0" ]
null
null
null
tdsa_augmentation/data_augmentation/target_extraction_train_predict.py
apmoore1/tdsa_augmentation
71c9ffa79ea48e817408d0dc496cc146ce75a942
[ "Apache-2.0" ]
null
null
null
tdsa_augmentation/data_augmentation/target_extraction_train_predict.py
apmoore1/tdsa_augmentation
71c9ffa79ea48e817408d0dc496cc146ce75a942
[ "Apache-2.0" ]
null
null
null
import argparse from pathlib import Path import json from typing import Iterable import tempfile import random from allennlp.models import Model from sklearn.model_selection import train_test_split import target_extraction from target_extraction.data_types import TargetTextCollection from target_extraction.dataset_parsers import semeval_2014, wang_2017_election_twitter_test, wang_2017_election_twitter_train from target_extraction.tokenizers import spacy_tokenizer, ark_twokenize from target_extraction.allen import AllenNLPModel def parse_path(path_string: str) -> Path: path_string = Path(path_string).resolve() return path_string def text_to_json(text_fp: Path) -> Iterable[str]: with text_fp.open('r') as text_file: for line in text_file: line = line.strip() if line: tokens = line.split() yield {'text': line, 'tokens': tokens} def predict_on_file(input_fp: Path, output_fp: Path, model: Model, batch_size: int) -> None: first = True output_fp.parent.mkdir(parents=True, exist_ok=True) with output_fp.open('w+') as output_data_file: for prediction in model.predict_sequences(text_to_json(input_fp), batch_size=batch_size): prediction_str = json.dumps(prediction) if first: first = False else: prediction_str = f'\n{prediction_str}' output_data_file.write(prediction_str) if __name__ == '__main__': cuda_help = 'If loading the model from a pre-trained model whether that '\ 'model should be loaded on to the GPU or not' parser = argparse.ArgumentParser() parser.add_argument("--train_fp", type=parse_path, help='File path to the train data') parser.add_argument("--test_fp", type=parse_path, help='File path to the test data') parser.add_argument("--number_to_predict_on", type=int, help='Sub sample the data until this number of samples are left') parser.add_argument("--batch_size", type=int, default=64, help='Batch size. Higher this is the more memory you need') parser.add_argument('--cuda', action="store_true", help=cuda_help) parser.add_argument('dataset_name', type=str, choices=['semeval_2014', 'election_twitter'], help='dataset that is to be trained and predicted') parser.add_argument('model_config', type=parse_path, help='File Path to the Model configuration file') parser.add_argument('model_save_dir', type=parse_path, help='Directory to save the trained model') parser.add_argument('data_fp', type=parse_path, help='File Path to the data to predict on') parser.add_argument('output_data_fp', type=parse_path, help='File Path to the output predictions') args = parser.parse_args() dataset_name = args.dataset_name model_name = f'{dataset_name} model' model = AllenNLPModel(model_name, args.model_config, 'target-tagger', args.model_save_dir) if dataset_name == 'semeval_2014': if not args.train_fp or not args.test_fp: raise ValueError('If training and predicting for the SemEval ' 'datasets the training and test file paths must ' 'be given') # As we are performing target extraction we use the conflict polarity # targets like prior work train_data = semeval_2014(args.train_fp, conflict=True) test_data = semeval_2014(args.test_fp, conflict=True) else: temp_election_directory = Path('.', 'data', 'twitter_election_dataset') train_data = wang_2017_election_twitter_train(temp_election_directory) test_data = wang_2017_election_twitter_test(temp_election_directory) if not args.model_save_dir.is_dir(): # Use the same size validation as the test data test_size = len(test_data) # Create the train and validation splits train_data = list(train_data.values()) train_data, val_data = train_test_split(train_data, test_size=test_size) train_data = TargetTextCollection(train_data) val_data = TargetTextCollection(val_data) # Tokenize the data datasets = [train_data, val_data, test_data] tokenizer = spacy_tokenizer() sizes = [] target_sizes = [] for dataset in datasets: dataset.tokenize(tokenizer) returned_errors = dataset.sequence_labels(return_errors=True) if returned_errors: for error in returned_errors: error_id = error['text_id'] del dataset[error_id] returned_errors = dataset.sequence_labels(return_errors=True) if returned_errors: raise ValueError('Sequence label errors are still persisting') sizes.append(len(dataset)) dataset: TargetTextCollection target_sizes.append(dataset.number_targets()) print(f'Lengths Train: {sizes[0]}, Validation: {sizes[1]}, Test: {sizes[2]}') print(f'Number of targets, Train: {target_sizes[0]}, Validation: ' f'{target_sizes[1]}, Test: {target_sizes[2]}') print('Fitting model') model.fit(train_data, val_data, test_data) print('Finished fitting model\nNow Evaluating model:') else: test_data.tokenize(spacy_tokenizer()) device = -1 if args.cuda: device = 0 model.load(cuda_device=device) print('Finished loading model\nNow Evaluating model:') for data in test_data.values(): data['tokens'] = data['tokenized_text'] test_iter = iter(test_data.values()) for test_pred in model.predict_sequences(test_data.values(), batch_size=args.batch_size): relevant_test = next(test_iter) relevant_test['predicted_sequence_labels'] = test_pred['sequence_labels'] test_scores = test_data.exact_match_score('predicted_sequence_labels') print(f'Test F1 scores: {test_scores[2]}') first = True data_fp = args.data_fp from time import time t = time() if args.number_to_predict_on: data_count = 0 with data_fp.open('r') as data_file: for line in data_file: data_count += 1 if data_count <= args.number_to_predict_on: raise ValueError(f'Number of lines in the data file {data_count} ' 'to predict on is less than or equal to the number' f' of lines to sub-sample {args.number_to_predict_on}') lines_numbers_to_subsample = random.sample(range(data_count), k=args.number_to_predict_on) lines_numbers_to_subsample = set(lines_numbers_to_subsample) with tempfile.TemporaryDirectory() as temp_dir: temp_fp = Path(temp_dir, 'temp_input_file.txt') with temp_fp.open('w+') as temp_file: with data_fp.open('r') as data_file: for index, line in enumerate(data_file): if index in lines_numbers_to_subsample: temp_file.write(line) print(f'subsampled data {args.number_to_predict_on} lines') predict_on_file(temp_fp, args.output_data_fp, model, args.batch_size) else: predict_on_file(data_fp, args.output_data_fp, model, args.batch_size) print(f'Done took {time() - t}')
46.945455
125
0.639556
import argparse from pathlib import Path import json from typing import Iterable import tempfile import random from allennlp.models import Model from sklearn.model_selection import train_test_split import target_extraction from target_extraction.data_types import TargetTextCollection from target_extraction.dataset_parsers import semeval_2014, wang_2017_election_twitter_test, wang_2017_election_twitter_train from target_extraction.tokenizers import spacy_tokenizer, ark_twokenize from target_extraction.allen import AllenNLPModel def parse_path(path_string: str) -> Path: path_string = Path(path_string).resolve() return path_string def text_to_json(text_fp: Path) -> Iterable[str]: with text_fp.open('r') as text_file: for line in text_file: line = line.strip() if line: tokens = line.split() yield {'text': line, 'tokens': tokens} def predict_on_file(input_fp: Path, output_fp: Path, model: Model, batch_size: int) -> None: first = True output_fp.parent.mkdir(parents=True, exist_ok=True) with output_fp.open('w+') as output_data_file: for prediction in model.predict_sequences(text_to_json(input_fp), batch_size=batch_size): prediction_str = json.dumps(prediction) if first: first = False else: prediction_str = f'\n{prediction_str}' output_data_file.write(prediction_str) if __name__ == '__main__': cuda_help = 'If loading the model from a pre-trained model whether that '\ 'model should be loaded on to the GPU or not' parser = argparse.ArgumentParser() parser.add_argument("--train_fp", type=parse_path, help='File path to the train data') parser.add_argument("--test_fp", type=parse_path, help='File path to the test data') parser.add_argument("--number_to_predict_on", type=int, help='Sub sample the data until this number of samples are left') parser.add_argument("--batch_size", type=int, default=64, help='Batch size. Higher this is the more memory you need') parser.add_argument('--cuda', action="store_true", help=cuda_help) parser.add_argument('dataset_name', type=str, choices=['semeval_2014', 'election_twitter'], help='dataset that is to be trained and predicted') parser.add_argument('model_config', type=parse_path, help='File Path to the Model configuration file') parser.add_argument('model_save_dir', type=parse_path, help='Directory to save the trained model') parser.add_argument('data_fp', type=parse_path, help='File Path to the data to predict on') parser.add_argument('output_data_fp', type=parse_path, help='File Path to the output predictions') args = parser.parse_args() dataset_name = args.dataset_name model_name = f'{dataset_name} model' model = AllenNLPModel(model_name, args.model_config, 'target-tagger', args.model_save_dir) if dataset_name == 'semeval_2014': if not args.train_fp or not args.test_fp: raise ValueError('If training and predicting for the SemEval ' 'datasets the training and test file paths must ' 'be given') train_data = semeval_2014(args.train_fp, conflict=True) test_data = semeval_2014(args.test_fp, conflict=True) else: temp_election_directory = Path('.', 'data', 'twitter_election_dataset') train_data = wang_2017_election_twitter_train(temp_election_directory) test_data = wang_2017_election_twitter_test(temp_election_directory) if not args.model_save_dir.is_dir(): test_size = len(test_data) train_data = list(train_data.values()) train_data, val_data = train_test_split(train_data, test_size=test_size) train_data = TargetTextCollection(train_data) val_data = TargetTextCollection(val_data) datasets = [train_data, val_data, test_data] tokenizer = spacy_tokenizer() sizes = [] target_sizes = [] for dataset in datasets: dataset.tokenize(tokenizer) returned_errors = dataset.sequence_labels(return_errors=True) if returned_errors: for error in returned_errors: error_id = error['text_id'] del dataset[error_id] returned_errors = dataset.sequence_labels(return_errors=True) if returned_errors: raise ValueError('Sequence label errors are still persisting') sizes.append(len(dataset)) dataset: TargetTextCollection target_sizes.append(dataset.number_targets()) print(f'Lengths Train: {sizes[0]}, Validation: {sizes[1]}, Test: {sizes[2]}') print(f'Number of targets, Train: {target_sizes[0]}, Validation: ' f'{target_sizes[1]}, Test: {target_sizes[2]}') print('Fitting model') model.fit(train_data, val_data, test_data) print('Finished fitting model\nNow Evaluating model:') else: test_data.tokenize(spacy_tokenizer()) device = -1 if args.cuda: device = 0 model.load(cuda_device=device) print('Finished loading model\nNow Evaluating model:') for data in test_data.values(): data['tokens'] = data['tokenized_text'] test_iter = iter(test_data.values()) for test_pred in model.predict_sequences(test_data.values(), batch_size=args.batch_size): relevant_test = next(test_iter) relevant_test['predicted_sequence_labels'] = test_pred['sequence_labels'] test_scores = test_data.exact_match_score('predicted_sequence_labels') print(f'Test F1 scores: {test_scores[2]}') first = True data_fp = args.data_fp from time import time t = time() if args.number_to_predict_on: data_count = 0 with data_fp.open('r') as data_file: for line in data_file: data_count += 1 if data_count <= args.number_to_predict_on: raise ValueError(f'Number of lines in the data file {data_count} ' 'to predict on is less than or equal to the number' f' of lines to sub-sample {args.number_to_predict_on}') lines_numbers_to_subsample = random.sample(range(data_count), k=args.number_to_predict_on) lines_numbers_to_subsample = set(lines_numbers_to_subsample) with tempfile.TemporaryDirectory() as temp_dir: temp_fp = Path(temp_dir, 'temp_input_file.txt') with temp_fp.open('w+') as temp_file: with data_fp.open('r') as data_file: for index, line in enumerate(data_file): if index in lines_numbers_to_subsample: temp_file.write(line) print(f'subsampled data {args.number_to_predict_on} lines') predict_on_file(temp_fp, args.output_data_fp, model, args.batch_size) else: predict_on_file(data_fp, args.output_data_fp, model, args.batch_size) print(f'Done took {time() - t}')
true
true
1c3bf41fff909ff93e310492d5406989841b8adb
7,216
py
Python
tensorflow_datasets/translate/wmt.py
alexalemi/datasets
45282fbf6b42aac0ff58d40a7941a983be7c9f18
[ "Apache-2.0" ]
1
2019-03-19T10:38:38.000Z
2019-03-19T10:38:38.000Z
tensorflow_datasets/translate/wmt.py
alexalemi/datasets
45282fbf6b42aac0ff58d40a7941a983be7c9f18
[ "Apache-2.0" ]
null
null
null
tensorflow_datasets/translate/wmt.py
alexalemi/datasets
45282fbf6b42aac0ff58d40a7941a983be7c9f18
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # Copyright 2019 The TensorFlow Datasets Authors. # # 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. """WMT: Translate dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import collections import json import os import tensorflow as tf from tensorflow_datasets.core import api_utils import tensorflow_datasets.public_api as tfds _DESCRIPTION = """\ Translate dataset based on the data from statmt.org. """ _CITATION = """\ @InProceedings{bojar-EtAl:2018:WMT1, author = {Bojar, Ond\v{r}ej and Federmann, Christian and Fishel, Mark and Graham, Yvette and Haddow, Barry and Huck, Matthias and Koehn, Philipp and Monz, Christof}, title = {Findings of the 2018 Conference on Machine Translation (WMT18)}, booktitle = {Proceedings of the Third Conference on Machine Translation, Volume 2: Shared Task Papers}, month = {October}, year = {2018}, address = {Belgium, Brussels}, publisher = {Association for Computational Linguistics}, pages = {272--307}, url = {http://www.aclweb.org/anthology/W18-6401} } """ # Tuple that describes a single pair of files with matching translations. # language_to_file is the map from language (2 letter string: example 'en') # to the file path in the extracted directory. TranslateData = collections.namedtuple("TranslateData", ["url", "language_to_file"]) class WMTConfig(tfds.core.BuilderConfig): """BuilderConfig for WMT.""" # TODO(tfds): figure out if we want to share vocab between src/target. @api_utils.disallow_positional_args def __init__(self, text_encoder_config=None, language_pair=(None, None), data=None, name_suffix=None, **kwargs): """BuilderConfig for WMT. Args: text_encoder_config: `tfds.features.text.TextEncoderConfig`, configuration for the `tfds.features.text.TextEncoder` used for the features feature. language_pair: pair of languages that will be used for translation. Should contain 2 letter coded strings. For example: ("en", "de"). data: data used for this training. It should be in the dictionary format, with keys matching "train", "test", "dev". Each entry should be a list of strings that are indexes into the self.translate_datasets map. name_suffix: name that should be appended to the dataset name at the end. **kwargs: keyword arguments forwarded to super. """ encoder_name = ( text_encoder_config.name if text_encoder_config else "plain_text") name = "%s%s_%s" % (language_pair[0], language_pair[1], encoder_name) if name_suffix: name += "_%s" % name_suffix description = ( "Translation dataset from %s to %s, uses encoder %s. It uses the " "following data files (see the code for exact contents): %s.") % ( language_pair[0], language_pair[1], encoder_name, json.dumps(data, sort_keys=True)) super(WMTConfig, self).__init__( name=name, description=description, **kwargs) self.text_encoder_config = ( text_encoder_config or tfds.features.text.TextEncoderConfig()) self.language_pair = language_pair self.data = data class WmtTranslate(tfds.core.GeneratorBasedBuilder): """WMT translation dataset.""" _URL = "http://www.statmt.org/wmt18/" IN_DEVELOPMENT = True @abc.abstractproperty def translate_datasets(self): """Datasets used in this class.""" raise NotImplementedError def _info(self): src, target = self.builder_config.language_pair return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.Translation( languages=self.builder_config.language_pair, encoder_config=self.builder_config.text_encoder_config), supervised_keys=(src, target), urls=["http://www.statmt.org/wmt18/"], citation=_CITATION, ) def _vocab_text_gen(self, files, language): for ex in self._generate_examples(files): yield ex[language] def _split_generators(self, dl_manager): urls_to_download = {} for split in ["train", "dev"]: urls_to_download.update({ "%s_%d" % (split, i): self.translate_datasets[entry].url for i, entry in enumerate(self.builder_config.data[split]) }) downloaded_files = dl_manager.download_and_extract(urls_to_download) # Dictionary with file locations for each split. # Inside it contains a list of pairs of files with matching sentences. files = {} for split in ["train", "dev"]: files[split] = [] for i, entry in enumerate(self.builder_config.data[split]): path = os.path.join( downloaded_files["%s_%d" % (split, i)], self.translate_datasets[entry].language_to_file[ self.builder_config.language_pair[1]]) files[split].append((os.path.join( downloaded_files["%s_%d" % (split, i)], self.translate_datasets[entry].language_to_file[ self.builder_config.language_pair[0]]), path)) # Generate vocabulary from training data if SubwordTextEncoder configured for language in self.builder_config.language_pair: self.info.features[language].maybe_build_from_corpus( self._vocab_text_gen(files["train"], language)) return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, num_shards=10, gen_kwargs={"files": files["train"]}), tfds.core.SplitGenerator( name=tfds.Split.VALIDATION, num_shards=1, gen_kwargs={"files": files["dev"]}), ] def _generate_examples(self, files): """This function returns the examples in the raw (text) form.""" for entry in files: with tf.io.gfile.GFile(entry[0]) as f: lang1_sentences = f.read().split("\n") with tf.io.gfile.GFile(entry[1]) as f: lang2_sentences = f.read().split("\n") assert len(lang1_sentences) == len( lang2_sentences), "Sizes do not match: %d vs %d for %s vs %s." % ( len(lang1_sentences), len(lang2_sentences), entry[0], entry[1]) # Skip the last entry (it is usually ('', '') due to the end of file) for l1, l2 in zip(lang1_sentences, lang2_sentences): result = { self.builder_config.language_pair[0]: l1, self.builder_config.language_pair[1]: l2 } # Make sure that both translations are non-empty. if all(result.values()): yield result
37.583333
80
0.667129
from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import collections import json import os import tensorflow as tf from tensorflow_datasets.core import api_utils import tensorflow_datasets.public_api as tfds _DESCRIPTION = """\ Translate dataset based on the data from statmt.org. """ _CITATION = """\ @InProceedings{bojar-EtAl:2018:WMT1, author = {Bojar, Ond\v{r}ej and Federmann, Christian and Fishel, Mark and Graham, Yvette and Haddow, Barry and Huck, Matthias and Koehn, Philipp and Monz, Christof}, title = {Findings of the 2018 Conference on Machine Translation (WMT18)}, booktitle = {Proceedings of the Third Conference on Machine Translation, Volume 2: Shared Task Papers}, month = {October}, year = {2018}, address = {Belgium, Brussels}, publisher = {Association for Computational Linguistics}, pages = {272--307}, url = {http://www.aclweb.org/anthology/W18-6401} } """ TranslateData = collections.namedtuple("TranslateData", ["url", "language_to_file"]) class WMTConfig(tfds.core.BuilderConfig): @api_utils.disallow_positional_args def __init__(self, text_encoder_config=None, language_pair=(None, None), data=None, name_suffix=None, **kwargs): encoder_name = ( text_encoder_config.name if text_encoder_config else "plain_text") name = "%s%s_%s" % (language_pair[0], language_pair[1], encoder_name) if name_suffix: name += "_%s" % name_suffix description = ( "Translation dataset from %s to %s, uses encoder %s. It uses the " "following data files (see the code for exact contents): %s.") % ( language_pair[0], language_pair[1], encoder_name, json.dumps(data, sort_keys=True)) super(WMTConfig, self).__init__( name=name, description=description, **kwargs) self.text_encoder_config = ( text_encoder_config or tfds.features.text.TextEncoderConfig()) self.language_pair = language_pair self.data = data class WmtTranslate(tfds.core.GeneratorBasedBuilder): _URL = "http://www.statmt.org/wmt18/" IN_DEVELOPMENT = True @abc.abstractproperty def translate_datasets(self): raise NotImplementedError def _info(self): src, target = self.builder_config.language_pair return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.Translation( languages=self.builder_config.language_pair, encoder_config=self.builder_config.text_encoder_config), supervised_keys=(src, target), urls=["http://www.statmt.org/wmt18/"], citation=_CITATION, ) def _vocab_text_gen(self, files, language): for ex in self._generate_examples(files): yield ex[language] def _split_generators(self, dl_manager): urls_to_download = {} for split in ["train", "dev"]: urls_to_download.update({ "%s_%d" % (split, i): self.translate_datasets[entry].url for i, entry in enumerate(self.builder_config.data[split]) }) downloaded_files = dl_manager.download_and_extract(urls_to_download) files = {} for split in ["train", "dev"]: files[split] = [] for i, entry in enumerate(self.builder_config.data[split]): path = os.path.join( downloaded_files["%s_%d" % (split, i)], self.translate_datasets[entry].language_to_file[ self.builder_config.language_pair[1]]) files[split].append((os.path.join( downloaded_files["%s_%d" % (split, i)], self.translate_datasets[entry].language_to_file[ self.builder_config.language_pair[0]]), path)) for language in self.builder_config.language_pair: self.info.features[language].maybe_build_from_corpus( self._vocab_text_gen(files["train"], language)) return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, num_shards=10, gen_kwargs={"files": files["train"]}), tfds.core.SplitGenerator( name=tfds.Split.VALIDATION, num_shards=1, gen_kwargs={"files": files["dev"]}), ] def _generate_examples(self, files): for entry in files: with tf.io.gfile.GFile(entry[0]) as f: lang1_sentences = f.read().split("\n") with tf.io.gfile.GFile(entry[1]) as f: lang2_sentences = f.read().split("\n") assert len(lang1_sentences) == len( lang2_sentences), "Sizes do not match: %d vs %d for %s vs %s." % ( len(lang1_sentences), len(lang2_sentences), entry[0], entry[1]) for l1, l2 in zip(lang1_sentences, lang2_sentences): result = { self.builder_config.language_pair[0]: l1, self.builder_config.language_pair[1]: l2 } if all(result.values()): yield result
true
true
1c3bf528230677da54091dd3ef37661d1b3ce393
1,521
py
Python
qurator/dinglehopper/tests/test_integ_character_error_rate_ocr.py
bertsky/dinglehopper
a51f0b3dcdd03105c2d7e352d37503237de3bd48
[ "Apache-2.0" ]
null
null
null
qurator/dinglehopper/tests/test_integ_character_error_rate_ocr.py
bertsky/dinglehopper
a51f0b3dcdd03105c2d7e352d37503237de3bd48
[ "Apache-2.0" ]
null
null
null
qurator/dinglehopper/tests/test_integ_character_error_rate_ocr.py
bertsky/dinglehopper
a51f0b3dcdd03105c2d7e352d37503237de3bd48
[ "Apache-2.0" ]
null
null
null
from __future__ import division, print_function import os import pytest from lxml import etree as ET from uniseg.graphemecluster import grapheme_clusters from .. import character_error_rate, page_text, alto_text data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data') @pytest.mark.integration def test_character_error_rate_between_page_files(): # In the fake OCR file, we changed 2 characters and replaced a fi ligature with fi. # The fi ligature does not count. gt = page_text(ET.parse(os.path.join(data_dir, 'test-gt.page2018.xml'))) ocr = page_text(ET.parse(os.path.join(data_dir, 'test-fake-ocr.page2018.xml'))) gt_len = len(list(grapheme_clusters(gt))) expected_cer = 2/gt_len assert character_error_rate(gt, ocr) == expected_cer @pytest.mark.integration def test_character_error_rate_between_page_alto(): gt = page_text(ET.parse(os.path.join(data_dir, 'lorem-ipsum', 'lorem-ipsum-scan.gt.page.xml'))) ocr = alto_text(ET.parse(os.path.join(data_dir, 'lorem-ipsum', 'lorem-ipsum-scan.ocr.tesseract.alto.xml'))) assert gt == ocr assert character_error_rate(gt, ocr) == 0 @pytest.mark.integration def test_character_error_rate_between_page_alto_2(): gt = page_text(ET.parse(os.path.join(data_dir, 'lorem-ipsum', 'lorem-ipsum-scan-bad.gt.page.xml'))) ocr = alto_text(ET.parse(os.path.join(data_dir, 'lorem-ipsum', 'lorem-ipsum-scan-bad.ocr.tesseract.alto.xml'))) assert character_error_rate(gt, ocr) == 8/591 # Manually verified
36.214286
115
0.745562
from __future__ import division, print_function import os import pytest from lxml import etree as ET from uniseg.graphemecluster import grapheme_clusters from .. import character_error_rate, page_text, alto_text data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data') @pytest.mark.integration def test_character_error_rate_between_page_files(): gt = page_text(ET.parse(os.path.join(data_dir, 'test-gt.page2018.xml'))) ocr = page_text(ET.parse(os.path.join(data_dir, 'test-fake-ocr.page2018.xml'))) gt_len = len(list(grapheme_clusters(gt))) expected_cer = 2/gt_len assert character_error_rate(gt, ocr) == expected_cer @pytest.mark.integration def test_character_error_rate_between_page_alto(): gt = page_text(ET.parse(os.path.join(data_dir, 'lorem-ipsum', 'lorem-ipsum-scan.gt.page.xml'))) ocr = alto_text(ET.parse(os.path.join(data_dir, 'lorem-ipsum', 'lorem-ipsum-scan.ocr.tesseract.alto.xml'))) assert gt == ocr assert character_error_rate(gt, ocr) == 0 @pytest.mark.integration def test_character_error_rate_between_page_alto_2(): gt = page_text(ET.parse(os.path.join(data_dir, 'lorem-ipsum', 'lorem-ipsum-scan-bad.gt.page.xml'))) ocr = alto_text(ET.parse(os.path.join(data_dir, 'lorem-ipsum', 'lorem-ipsum-scan-bad.ocr.tesseract.alto.xml'))) assert character_error_rate(gt, ocr) == 8/591
true
true
1c3bf5961901ee63852fa32b005ee5d138026167
2,537
py
Python
2019/day22/solutions.py
ivobatkovic/advent-of-code
e43489bcd2307f0f3ac8b0ec4e850f0a201f9944
[ "MIT" ]
3
2019-12-14T16:24:50.000Z
2020-12-06T16:40:13.000Z
2019/day22/solutions.py
ivobatkovic/advent-of-code
e43489bcd2307f0f3ac8b0ec4e850f0a201f9944
[ "MIT" ]
4
2019-12-03T14:18:13.000Z
2020-12-03T08:29:32.000Z
2019/day22/solutions.py
ivobatkovic/advent-of-code
e43489bcd2307f0f3ac8b0ec4e850f0a201f9944
[ "MIT" ]
2
2019-12-06T07:25:57.000Z
2020-12-08T12:42:37.000Z
from os.path import dirname from os.path import realpath from os.path import join import time import sys sys.path.append(join(dirname(realpath(__file__)), *[".."])) from day22.deck import Deck def part1(input_): """Part one: apply the linear transformation y = a*x + b to get which position card x ends up in after one shuffle""" n, card = 10007, 2019 deck = Deck(input_, num_cards=10007) return (deck.a * card + deck.b) % n def part2(input_): """Part two: apply the linear transformation y = a*x+b, m times. The solution consists of two parts. First: we can write the m:th shuffle as: y = a^m * x + b * (a^(m-1) +a^2 + a + 1 = a^m * x + b * (a^m-1)/(a-1) Next, we want to apply y % n, to keep the size of the number small. Here, we use the relations for y = a*x + b: y % n == ( (a*x % n) + b % n) % n and (a*b) % n == ((a%n)*(b%n)) % n Since n in this problem is a prime, we can use Fermat's little theorem which says that x^(n-1) % n == 1 % n, hence x^(n-2) % n == x^(-1) % n. We apply this relation to x = (a-1) -> (a-1)^-1 % n == a^(n-2) % n to obtain A = a^m B = ( b * (a^m-1) % n ) * ( a^(n-2) % n ) % n y % n = ( A%n * x + (B % n) ) % n Second: We want to know what card is at position x, hence we need to invert y = A * x + B -> x = (y-B) * A^(-1) x % n <=> ( ((y-B) % n) * (A^(n-2) % n) ) % n""" n, card = 119315717514047, 2020 deck = Deck(input_, num_cards=n) m_times = 101741582076661 A = pow(deck.a, m_times, n) B = ( deck.b * (pow(deck.a, m_times, n) - 1) * pow(deck.a - 1, n - 2, n) ) % n return ((card - B) % n) * pow(A, n - 2, n) % n def main(): # Open data file and read through all lines file_location = "data/input.txt" try: dir_path = dirname(realpath(__file__)) with open(join(dir_path, file_location), "r") as f: input_ = f.read() t0 = time.time() sol_part1 = part1(input_) time_end = round((time.time() - t0) * 1e3) print( "Solution to part one: %s (time taken %s[ms])" % (sol_part1, time_end) ) t0 = time.time() sol_part2 = part2(input_) time_end = round((time.time() - t0) * 1e3) print( "Solution to part two: %s (time taken %s[ms])" % (sol_part2, time_end) ) except IOError: print("Cannot find file at: " + file_location) if __name__ == "__main__": main()
29.847059
79
0.530548
from os.path import dirname from os.path import realpath from os.path import join import time import sys sys.path.append(join(dirname(realpath(__file__)), *[".."])) from day22.deck import Deck def part1(input_): n, card = 10007, 2019 deck = Deck(input_, num_cards=10007) return (deck.a * card + deck.b) % n def part2(input_): n, card = 119315717514047, 2020 deck = Deck(input_, num_cards=n) m_times = 101741582076661 A = pow(deck.a, m_times, n) B = ( deck.b * (pow(deck.a, m_times, n) - 1) * pow(deck.a - 1, n - 2, n) ) % n return ((card - B) % n) * pow(A, n - 2, n) % n def main(): file_location = "data/input.txt" try: dir_path = dirname(realpath(__file__)) with open(join(dir_path, file_location), "r") as f: input_ = f.read() t0 = time.time() sol_part1 = part1(input_) time_end = round((time.time() - t0) * 1e3) print( "Solution to part one: %s (time taken %s[ms])" % (sol_part1, time_end) ) t0 = time.time() sol_part2 = part2(input_) time_end = round((time.time() - t0) * 1e3) print( "Solution to part two: %s (time taken %s[ms])" % (sol_part2, time_end) ) except IOError: print("Cannot find file at: " + file_location) if __name__ == "__main__": main()
true
true
1c3bf5bb31389340de26901c9e03e78d456874a5
731
py
Python
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/video_pipeline/migrations/0002_auto_20171114_0704.py
osoco/better-ways-of-thinking-about-software
83e70d23c873509e22362a09a10d3510e10f6992
[ "MIT" ]
3
2021-12-15T04:58:18.000Z
2022-02-06T12:15:37.000Z
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/video_pipeline/migrations/0002_auto_20171114_0704.py
osoco/better-ways-of-thinking-about-software
83e70d23c873509e22362a09a10d3510e10f6992
[ "MIT" ]
null
null
null
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/video_pipeline/migrations/0002_auto_20171114_0704.py
osoco/better-ways-of-thinking-about-software
83e70d23c873509e22362a09a10d3510e10f6992
[ "MIT" ]
1
2019-01-02T14:38:50.000Z
2019-01-02T14:38:50.000Z
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('video_pipeline', '0001_initial'), ] operations = [ migrations.AddField( model_name='videopipelineintegration', name='client_name', field=models.CharField(default='VEDA-Prod', help_text='Oauth client name of video pipeline service.', max_length=100), ), migrations.AlterField( model_name='videopipelineintegration', name='service_username', field=models.CharField(default='veda_service_user', help_text='Username created for Video Pipeline Integration, e.g. veda_service_user.', max_length=100), ), ]
33.227273
166
0.652531
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('video_pipeline', '0001_initial'), ] operations = [ migrations.AddField( model_name='videopipelineintegration', name='client_name', field=models.CharField(default='VEDA-Prod', help_text='Oauth client name of video pipeline service.', max_length=100), ), migrations.AlterField( model_name='videopipelineintegration', name='service_username', field=models.CharField(default='veda_service_user', help_text='Username created for Video Pipeline Integration, e.g. veda_service_user.', max_length=100), ), ]
true
true
1c3bf6091943521a6f7c5138a45928ad7e7d8eff
1,261
py
Python
pythonaulas/Aula 15/Desafio 068.py
jrwarg/Estudos-Phyton
2207ec1ee9880501e12fbfecf7dfaaf38bb2ebca
[ "MIT" ]
null
null
null
pythonaulas/Aula 15/Desafio 068.py
jrwarg/Estudos-Phyton
2207ec1ee9880501e12fbfecf7dfaaf38bb2ebca
[ "MIT" ]
null
null
null
pythonaulas/Aula 15/Desafio 068.py
jrwarg/Estudos-Phyton
2207ec1ee9880501e12fbfecf7dfaaf38bb2ebca
[ "MIT" ]
null
null
null
""" DESAFIO 068: Jogo do Par ou Ímpar Faça um programa que jogue par ou ímpar com o computador. O jogo só será interrompido quando o jogador PERDER, mostrando o total de vitórias consecutivas que ele conquistou no final do jogo. """ from random import randint sep1 = '-=' * 28 sep2 = '-' * 56 pontos = 0 print(sep1) titulo = 'VAMOS JOGAR PAR OU ÍMPAR' print(f'{titulo:^56}') print(sep1) while True: pc = randint(1, 10) jogada = int(input('Digite um valor: ')) pi = 'X' while pi != 'P' and pi != 'I': pi = str(input('Par ou Ímpar [P/I]? ')).strip().upper()[0].replace('Í', 'I') total = jogada + pc print(sep2) print(f'Você jogou {jogada} e o computador {pc}. Total de {total}.', end=' ') if total % 2 == 0: print('Deu PAR.') rodada = 'P' else: print('Deu ÍMPAR.') rodada = 'I' print(sep2) if pi == rodada: print('Você GANHOU!') print('Vamos jogar novamente...') print(sep1) pontos += 1 else: print('Você PERDEU!') break print(sep1) print('GAME OVER!', end=' ') if pontos == 0: print('Você não ganhou nenhuma vez.') elif pontos == 1: print('Você ganhou somente 1 vez.') else: print(f'Você ganhou {pontos} vezes.')
26.829787
95
0.586043
from random import randint sep1 = '-=' * 28 sep2 = '-' * 56 pontos = 0 print(sep1) titulo = 'VAMOS JOGAR PAR OU ÍMPAR' print(f'{titulo:^56}') print(sep1) while True: pc = randint(1, 10) jogada = int(input('Digite um valor: ')) pi = 'X' while pi != 'P' and pi != 'I': pi = str(input('Par ou Ímpar [P/I]? ')).strip().upper()[0].replace('Í', 'I') total = jogada + pc print(sep2) print(f'Você jogou {jogada} e o computador {pc}. Total de {total}.', end=' ') if total % 2 == 0: print('Deu PAR.') rodada = 'P' else: print('Deu ÍMPAR.') rodada = 'I' print(sep2) if pi == rodada: print('Você GANHOU!') print('Vamos jogar novamente...') print(sep1) pontos += 1 else: print('Você PERDEU!') break print(sep1) print('GAME OVER!', end=' ') if pontos == 0: print('Você não ganhou nenhuma vez.') elif pontos == 1: print('Você ganhou somente 1 vez.') else: print(f'Você ganhou {pontos} vezes.')
true
true
1c3bf78dcebdcc2308b23146529097323402bf79
4,544
py
Python
test2.py
jonathanmagal/BlackJack1
5af0a0c6ce8aabeb4af994ed374b7f8193cb49cf
[ "Unlicense" ]
null
null
null
test2.py
jonathanmagal/BlackJack1
5af0a0c6ce8aabeb4af994ed374b7f8193cb49cf
[ "Unlicense" ]
null
null
null
test2.py
jonathanmagal/BlackJack1
5af0a0c6ce8aabeb4af994ed374b7f8193cb49cf
[ "Unlicense" ]
null
null
null
from blackjack2 import Player, Suit, Card, Deck, Game from hashlib import new def test_repr(): assert str(Card(Suit.HEARTS, 5)) == "Card 5 of HEARTS" assert str(Card(Suit.DIAMONDS, 11)) == "Card Jack of DIAMONDS" assert str(Card(Suit.CLUBS, 12)) == "Card Queen of CLUBS" assert str(Card(Suit.CLUBS, 13)) == "Card King of CLUBS" assert str(Card(Suit.CLUBS, 14)) == "Card Ace of CLUBS" # TDD (TEST DRIVEN DEVELOPMENT) # RED > GREEN > REFACTOR def test_equality(): assert Card(Suit.HEARTS, 5) != "5" assert Card(Suit.HEARTS, 5) != Card(Suit.HEARTS, 6) assert Card(Suit.HEARTS, 5) != Card(Suit.CLUBS, 5) assert Card(Suit.HEARTS, 5) == Card(Suit.HEARTS, 5) def test_set_ace_to_one(): c1 = Card(Suit.HEARTS, 14) c1.set_ace_to_one() c2 = Card(Suit.HEARTS, 1) assert c1.value == c2.value c3 = Card(Suit.HEARTS, 13) c3.set_ace_to_one() assert c1.value != c3.value def test_create_deck(): deck = Deck() assert len(deck.cards) == 52 assert deck.cards[0] == Card(Suit.HEARTS, 2) assert deck.cards[-1] == Card(Suit.CLUBS, 14) def test_shuffle_deck(): deck = Deck() original_order = " ".join(str(card) for card in deck.cards) for _ in range(1000): deck.shuffle() new_order = " ".join(str(card) for card in deck.cards) assert original_order != new_order def test_take_card(): deck = Deck() handed_card = deck.take_card() for card in deck.cards: assert handed_card != card def test_player(): player = Player("Dror") player.get_card(Card(Suit.HEARTS, 14)) player.get_card(Card(Suit.CLUBS, 2)) assert player.get_hand_value() == 16 def test_number_of_players(): game = Game() x = game.number_of_players() assert x > 0 def test_players_names(): game = Game() playerslist = game.players_names(5) assert len(playerslist) == 5 def test_checking21(): game = Game() player1 = Player("yonatan") player2 = Player("dror") player3 = Player("omer") player1.get_card(Card(Suit.DIAMONDS, 11)) player1.get_card(Card(Suit.CLUBS, 14)) player1.get_card(Card(Suit.HEARTS, 13)) player2.get_card(Card(Suit.DIAMONDS, 7)) player2.get_card(Card(Suit.HEARTS, 9)) player3.get_card(Card(Suit.DIAMONDS, 14)) player3.get_card(Card(Suit.CLUBS, 11)) game.players.append(player1) game.players.append(player2) game.players.append(player3) game.checking21() assert player1 not in game.players assert player2 in game.players assert player3 in game.players for p in game.players: if p.name == "dror": assert p.get_hand_value() == 16 if p.name == "omer": assert p.get_hand_value() == 12 def test_checking21_singular(): player1 = Player("adam") player2 = Player("roee") player3 = Player("tamar") player1.get_card(Card(Suit.DIAMONDS, 5)) player1.get_card(Card(Suit.CLUBS, 13)) player1.get_card(Card(Suit.HEARTS, 14)) player2.get_card(Card(Suit.DIAMONDS, 7)) player2.get_card(Card(Suit.HEARTS, 9)) player3.get_card(Card(Suit.DIAMONDS, 14)) player3.get_card(Card(Suit.CLUBS, 13)) player3.get_card(Card(Suit.CLUBS, 12)) assert player1.checking21_singular() == True assert player1.get_hand_value() == 19 assert player2.checking21_singular(player2) == True assert player2.get_hand_value() == 16 assert player3.checking21_singular(player3) == False assert player1.get_hand_value() == 26 def test_game(): game = Game() game.deck.shuffle() values = [[11, 14], [7, 9], [13, 12], [5, 4]] for name in ["jonathan", "dror", "matan", "moshe"]: game.players.append(Player(name)) for player in game.players: for _ in range(2): player.get_card(game.deck.take_card()) for player, value in zip(game.players, values): player.hand[0].value = value[0] player.hand[1].value = value[1] game.checking21() for player1 in game.players: assert player1.name != "matan" for player2 in game.players: player2.get_card(Card(Suit.CLUBS, 14)) player2.checking21_singular() for i in game.players: if i.name == "jonathan": assert i.get_hand_value() == 13 if i.name == "dror": assert i.get_hand_value() == 17 if i.name == "moshe": assert i.get_hand_value() == 10 assert len(game.players) == 3 x = game.deck.take_card() for card in game.deck.cards: assert card != x
30.092715
66
0.638644
from blackjack2 import Player, Suit, Card, Deck, Game from hashlib import new def test_repr(): assert str(Card(Suit.HEARTS, 5)) == "Card 5 of HEARTS" assert str(Card(Suit.DIAMONDS, 11)) == "Card Jack of DIAMONDS" assert str(Card(Suit.CLUBS, 12)) == "Card Queen of CLUBS" assert str(Card(Suit.CLUBS, 13)) == "Card King of CLUBS" assert str(Card(Suit.CLUBS, 14)) == "Card Ace of CLUBS" def test_equality(): assert Card(Suit.HEARTS, 5) != "5" assert Card(Suit.HEARTS, 5) != Card(Suit.HEARTS, 6) assert Card(Suit.HEARTS, 5) != Card(Suit.CLUBS, 5) assert Card(Suit.HEARTS, 5) == Card(Suit.HEARTS, 5) def test_set_ace_to_one(): c1 = Card(Suit.HEARTS, 14) c1.set_ace_to_one() c2 = Card(Suit.HEARTS, 1) assert c1.value == c2.value c3 = Card(Suit.HEARTS, 13) c3.set_ace_to_one() assert c1.value != c3.value def test_create_deck(): deck = Deck() assert len(deck.cards) == 52 assert deck.cards[0] == Card(Suit.HEARTS, 2) assert deck.cards[-1] == Card(Suit.CLUBS, 14) def test_shuffle_deck(): deck = Deck() original_order = " ".join(str(card) for card in deck.cards) for _ in range(1000): deck.shuffle() new_order = " ".join(str(card) for card in deck.cards) assert original_order != new_order def test_take_card(): deck = Deck() handed_card = deck.take_card() for card in deck.cards: assert handed_card != card def test_player(): player = Player("Dror") player.get_card(Card(Suit.HEARTS, 14)) player.get_card(Card(Suit.CLUBS, 2)) assert player.get_hand_value() == 16 def test_number_of_players(): game = Game() x = game.number_of_players() assert x > 0 def test_players_names(): game = Game() playerslist = game.players_names(5) assert len(playerslist) == 5 def test_checking21(): game = Game() player1 = Player("yonatan") player2 = Player("dror") player3 = Player("omer") player1.get_card(Card(Suit.DIAMONDS, 11)) player1.get_card(Card(Suit.CLUBS, 14)) player1.get_card(Card(Suit.HEARTS, 13)) player2.get_card(Card(Suit.DIAMONDS, 7)) player2.get_card(Card(Suit.HEARTS, 9)) player3.get_card(Card(Suit.DIAMONDS, 14)) player3.get_card(Card(Suit.CLUBS, 11)) game.players.append(player1) game.players.append(player2) game.players.append(player3) game.checking21() assert player1 not in game.players assert player2 in game.players assert player3 in game.players for p in game.players: if p.name == "dror": assert p.get_hand_value() == 16 if p.name == "omer": assert p.get_hand_value() == 12 def test_checking21_singular(): player1 = Player("adam") player2 = Player("roee") player3 = Player("tamar") player1.get_card(Card(Suit.DIAMONDS, 5)) player1.get_card(Card(Suit.CLUBS, 13)) player1.get_card(Card(Suit.HEARTS, 14)) player2.get_card(Card(Suit.DIAMONDS, 7)) player2.get_card(Card(Suit.HEARTS, 9)) player3.get_card(Card(Suit.DIAMONDS, 14)) player3.get_card(Card(Suit.CLUBS, 13)) player3.get_card(Card(Suit.CLUBS, 12)) assert player1.checking21_singular() == True assert player1.get_hand_value() == 19 assert player2.checking21_singular(player2) == True assert player2.get_hand_value() == 16 assert player3.checking21_singular(player3) == False assert player1.get_hand_value() == 26 def test_game(): game = Game() game.deck.shuffle() values = [[11, 14], [7, 9], [13, 12], [5, 4]] for name in ["jonathan", "dror", "matan", "moshe"]: game.players.append(Player(name)) for player in game.players: for _ in range(2): player.get_card(game.deck.take_card()) for player, value in zip(game.players, values): player.hand[0].value = value[0] player.hand[1].value = value[1] game.checking21() for player1 in game.players: assert player1.name != "matan" for player2 in game.players: player2.get_card(Card(Suit.CLUBS, 14)) player2.checking21_singular() for i in game.players: if i.name == "jonathan": assert i.get_hand_value() == 13 if i.name == "dror": assert i.get_hand_value() == 17 if i.name == "moshe": assert i.get_hand_value() == 10 assert len(game.players) == 3 x = game.deck.take_card() for card in game.deck.cards: assert card != x
true
true
1c3bf78dcf5f48602ae173f78b1c183288bed5b8
71,367
py
Python
vlcp/service/sdn/ioprocessing.py
geek-plus/vlcp
e7936e00929fcef00c04d4da39b67d9679d5f083
[ "Apache-2.0" ]
1
2016-09-10T12:09:29.000Z
2016-09-10T12:09:29.000Z
vlcp/service/sdn/ioprocessing.py
wan-qy/vlcp
e7936e00929fcef00c04d4da39b67d9679d5f083
[ "Apache-2.0" ]
null
null
null
vlcp/service/sdn/ioprocessing.py
wan-qy/vlcp
e7936e00929fcef00c04d4da39b67d9679d5f083
[ "Apache-2.0" ]
null
null
null
''' Created on 2016/4/13 :author: hubo ''' from vlcp.service.sdn.flowbase import FlowBase from vlcp.server.module import depend, ModuleNotification, callAPI import vlcp.service.sdn.ofpportmanager as ofpportmanager import vlcp.service.sdn.ovsdbportmanager as ovsdbportmanager import vlcp.service.kvdb.objectdb as objectdb from vlcp.event.event import Event, withIndices from vlcp.event.runnable import RoutineContainer, RoutineException from vlcp.config.config import defaultconfig from vlcp.service.sdn.ofpmanager import FlowInitialize from vlcp.utils.networkmodel import PhysicalPort, LogicalPort, PhysicalPortSet, LogicalPortSet, LogicalNetwork, PhysicalNetwork from vlcp.utils.flowupdater import FlowUpdater from vlcp.event.connection import ConnectionResetException from vlcp.protocol.openflow.openflow import OpenflowConnectionStateEvent,\ OpenflowErrorResultException from pprint import pformat from namedstruct import dump @withIndices('datapathid', 'vhost', 'connection', 'logicalportchanged', 'physicalportchanged', 'logicalnetworkchanged', 'physicalnetworkchanged') class DataObjectChanged(Event): pass class IDAssigner(object): def __init__(self): self._indices = {} self._revindices = {} # Reserve 0 and 0xffff self._revindices[0] = '<reserve0>' self._revindices[0xffff] = '<reserve65535>' self._lastindex = 1 def assign(self, key): if key in self._indices: return self._indices[key] else: ind = self._lastindex while ind in self._revindices: ind += 1 ind &= 0xffff self._revindices[ind] = key self._indices[key] = ind self._lastindex = ind + 1 return ind def unassign(self, keys): for k in keys: ind = self._indices.pop(k, None) if ind is not None: del self._revindices[ind] def frozen(self): return dict(self._indices) def _to32bitport(portno): if portno >= 0xff00: portno = 0xffff0000 | portno return portno class IOFlowUpdater(FlowUpdater): def __init__(self, connection, systemid, bridgename, parent): FlowUpdater.__init__(self, connection, (LogicalPortSet.default_key(), PhysicalPortSet.default_key()), ('ioprocessing', connection), parent._logger) self._walkerdict = {LogicalPortSet.default_key(): self._logicalport_walker, PhysicalPortSet.default_key(): self._physicalport_walker } self._systemid = systemid self._bridgename = bridgename self._portnames = {} self._portids = {} self._currentportids = {} self._currentportnames = {} self._lastportids = {} self._lastportnames = {} self._lastnetworkids = {} self._networkids = IDAssigner() self._phynetworkids = IDAssigner() self._physicalnetworkids = {} self._logicalportkeys = set() self._physicalportkeys = set() self._logicalnetworkkeys = set() self._physicalnetworkkeys = set() self._parent = parent def update_ports(self, ports, ovsdb_ports): self._portnames.clear() self._portnames.update((p['name'], _to32bitport(p['ofport'])) for p in ovsdb_ports) self._portids.clear() self._portids.update((p['id'], _to32bitport(p['ofport'])) for p in ovsdb_ports if p['id']) for m in self.restart_walk(): yield m def _logicalport_walker(self, key, value, walk, save): save(key) if value is None: return logset = value.set for id in self._portids: logports = logset.find(LogicalPort, id) for p in logports: try: logp = walk(p.getkey()) except KeyError: pass else: save(logp.getkey()) try: lognet = walk(logp.network.getkey()) except KeyError: pass else: save(lognet.getkey()) try: phynet = walk(lognet.physicalnetwork.getkey()) except KeyError: pass else: save(phynet.getkey()) def _physicalport_walker(self, key, value, walk, save): save(key) if value is None: return physet = value.set for name in self._portnames: phyports = physet.find(PhysicalPort, self._connection.protocol.vhost, self._systemid, self._bridgename, name) # There might be more than one match physical port rule for one port, pick the most specified one namedict = {} for p in phyports: _, inds = PhysicalPort._getIndices(p.getkey()) name = inds[-1] ind_key = [i != '%' for i in inds] if name != '%': if name in namedict: if namedict[name][0] < ind_key: namedict[name] = (ind_key, p) else: namedict[name] = (ind_key, p) phyports = [v[1] for v in namedict.values()] for p in phyports: try: phyp = walk(p.getkey()) except KeyError: pass else: save(phyp.getkey()) try: phynet = walk(phyp.physicalnetwork.getkey()) except KeyError: pass else: save(phynet.getkey()) def walkcomplete(self, keys, values): conn = self._connection dpid = conn.openflow_datapathid vhost = conn.protocol.vhost _currentportids = dict(self._portids) _currentportnames = dict(self._portnames) updated_data = {} current_data = {} for cls, name, idg, assigner in ((LogicalPort, '_logicalportkeys', lambda x: _currentportids[x.id], None), (PhysicalPort, '_physicalportkeys', lambda x: _currentportnames[x.name], None), (LogicalNetwork, '_logicalnetworkkeys', lambda x: self._networkids.assign(x.getkey()), self._networkids), (PhysicalNetwork, '_physicalnetworkkeys', lambda x: self._phynetworkids.assign(x.getkey()), self._phynetworkids), ): objs = [v for v in values if v is not None and not v.isdeleted() and v.isinstance(cls)] objkeys = set([v.getkey() for v in objs]) oldkeys = getattr(self, name) if objkeys != oldkeys: if assigner is not None: assigner.unassign(oldkeys.difference(objkeys)) setattr(self, name, objkeys) updated_data[cls] = True cv = [(o, idg(o)) for o in objs] current_data[cls] = cv if updated_data: for m in self.waitForSend(DataObjectChanged(dpid, vhost, conn, LogicalPort in updated_data, PhysicalPort in updated_data, LogicalNetwork in updated_data, PhysicalNetwork in updated_data, current = (current_data.get(LogicalPort), current_data.get(PhysicalPort), current_data.get(LogicalNetwork), current_data.get(PhysicalNetwork)))): yield m self._currentportids = _currentportids self._currentportnames = _currentportnames def updateflow(self, connection, addvalues, removevalues, updatedvalues): # We must do these in order, each with a batch: # 1. Remove flows # 2. Remove groups # 3. Add groups, modify groups # 4. Add flows, modify flows try: cmds = [] ofdef = connection.openflowdef vhost = connection.protocol.vhost input_table = self._parent._gettableindex('ingress', vhost) input_next = self._parent._getnexttable('', 'ingress', vhost = vhost) output_table = self._parent._gettableindex('egress', vhost) # Cache all IDs, save them into last. We will need them for remove. _lastportids = self._lastportids _lastportnames = self._lastportnames _lastnetworkids = self._lastnetworkids _portids = dict(self._currentportids) _portnames = dict(self._currentportnames) _networkids = self._networkids.frozen() exist_objs = dict((obj.getkey(), obj) for obj in self._savedresult if obj is not None and not obj.isdeleted()) # We must generate actions from network driver phyportset = [obj for obj in self._savedresult if obj is not None and not obj.isdeleted() and obj.isinstance(PhysicalPort)] phynetset = [obj for obj in self._savedresult if obj is not None and not obj.isdeleted() and obj.isinstance(PhysicalNetwork)] lognetset = [obj for obj in self._savedresult if obj is not None and not obj.isdeleted() and obj.isinstance(LogicalNetwork)] logportset = [obj for obj in self._savedresult if obj is not None and not obj.isdeleted() and obj.isinstance(LogicalPort)] # If a port is both a logical port and a physical port, flows may conflict. # Remove the port from dictionary if it is duplicated. logportofps = set(_portids[lp.id] for lp in logportset if lp.id in _portids) _portnames = dict((n,v) for n,v in _portnames.items() if v not in logportofps) self._lastportids = _portids self._lastportnames = _portnames self._lastnetworkids = _networkids # Group current ports by network for further use phyportdict = {} for p in phyportset: phyportdict.setdefault(p.physicalnetwork, []).append(p) lognetdict = {} for n in lognetset: lognetdict.setdefault(n.physicalnetwork, []).append(n) logportdict = {} for p in logportset: logportdict.setdefault(p.network, []).append(p) allapis = [] # Updated networks when: # 1. Network is updated # 2. Physical network of this logical network is updated # 3. Logical port is added or removed from the network # 4. Physical port is added or removed from the physical network group_updates = set([obj for obj in updatedvalues if obj.isinstance(LogicalNetwork)]) group_updates.update(obj.network for obj in addvalues if obj.isinstance(LogicalPort)) #group_updates.update(obj.network for obj in updatedvalues if obj.isinstance(LogicalPort)) group_updates.update(exist_objs[obj.network.getkey()] for obj in removevalues if obj.isinstance(LogicalPort) and obj.network.getkey() in exist_objs) updated_physicalnetworks = set(obj for obj in updatedvalues if obj.isinstance(PhysicalNetwork)) updated_physicalnetworks.update(p.physicalnetwork for p in addvalues if p.isinstance(PhysicalPort)) updated_physicalnetworks.update(exist_objs[p.physicalnetwork.getkey()] for p in removevalues if p.isinstance(PhysicalPort) and p.physicalnetwork.getkey() in exist_objs) updated_physicalnetworks.update(p.physicalnetwork for p in updatedvalues if p.isinstance(PhysicalPort)) group_updates.update(lnet for pnet in updated_physicalnetworks if pnet in lognetdict for lnet in lognetdict[pnet]) for pnet in phynetset: if pnet in lognetdict and pnet in phyportdict: for lognet in lognetdict[pnet]: netid = _networkids.get(lognet.getkey()) if netid is not None: for p in phyportdict[pnet]: if lognet in addvalues or lognet in group_updates or p in addvalues or p in updatedvalues: pid = _portnames.get(p.name) if pid is not None: def subr(lognet, p, netid, pid): try: for m in callAPI(self, 'public', 'createioflowparts', {'connection': connection, 'logicalnetwork': lognet, 'physicalport': p, 'logicalnetworkid': netid, 'physicalportid': pid}): yield m except Exception: self._parent._logger.warning("Create flow parts failed for %r and %r", lognet, p, exc_info = True) self.retvalue = None else: self.retvalue = ((lognet, p), self.retvalue) allapis.append(subr(lognet, p, netid, pid)) for m in self.executeAll(allapis): yield m flowparts = dict(r[0] for r in self.retvalue if r[0] is not None) if connection.protocol.disablenxext: # Nicira extension is disabled, use metadata instead # 64-bit metadata is used as: # | 16-bit input network | 16-bit output network | 16-bit reserved | 16-bit output port | # When first initialized, input network = output network = Logical Network no. # output port = OFPP_ANY, reserved bits are 0x0000 # Currently used reserved bits: # left-most (offset = 15, mask = 0x8000): allow output to IN_PORT # offset = 14, mask = 0x4000: 1 if is IN_PORT is a logical port, 0 else # right-most (offset = 0, mask = 0x0001): VXLAN learned def create_input_instructions(lognetid, extra_actions, is_logport): lognetid = (lognetid & 0xffff) instructions = [ofdef.ofp_instruction_write_metadata( metadata = (lognetid << 48) | (lognetid << 32) | ((0x4000 if is_logport else 0) << 16) | (ofdef.OFPP_ANY & 0xffff), metadata_mask = 0xffffffffffffffff ), ofdef.ofp_instruction_goto_table(table_id = input_next) ] if extra_actions: instructions.insert(0, ofdef.ofp_instruction_actions(actions = list(extra_actions))) return instructions def create_output_oxm(lognetid, portid, in_port = False): r = [ofdef.create_oxm(ofdef.OXM_OF_METADATA_W, (portid & 0xFFFF) | (0x80000000 if in_port else 0) | ((lognetid & 0xFFFF) << 32), 0x0000FFFF8000FFFF)] if in_port: r.append(ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, portid)) return r else: # With nicira extension, we store input network, output network and output port in REG4, REG5 and REG6 # REG7 is used as the reserved bits def create_input_instructions(lognetid, extra_actions, is_logport): lognetid = (lognetid & 0xffff) return [ofdef.ofp_instruction_actions(actions = [ ofdef.ofp_action_set_field( field = ofdef.create_oxm(ofdef.NXM_NX_REG4, lognetid) ), ofdef.ofp_action_set_field( field = ofdef.create_oxm(ofdef.NXM_NX_REG5, lognetid) ), ofdef.ofp_action_set_field( field = ofdef.create_oxm(ofdef.NXM_NX_REG6, ofdef.OFPP_ANY) ), ofdef.ofp_action_set_field( field = ofdef.create_oxm(ofdef.NXM_NX_REG7, (0x4000 if is_logport else 0)) ) ] + list(extra_actions)), ofdef.ofp_instruction_goto_table(table_id = input_next) ] def create_output_oxm(lognetid, portid, in_port = False): r = [ofdef.create_oxm(ofdef.NXM_NX_REG5, lognetid), ofdef.create_oxm(ofdef.NXM_NX_REG6, portid), ofdef.create_oxm(ofdef.NXM_NX_REG7_W, 0x8000 if in_port else 0, 0x8000)] if in_port: r.append(ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, portid)) return r for obj in removevalues: if obj.isinstance(LogicalPort): ofport = _lastportids.get(obj.id) if ofport is not None: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )]) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofport, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm())) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_IN_PORT, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport)]))) elif obj.isinstance(PhysicalPort): ofport = _lastportnames.get(obj.name) if ofport is not None: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )]) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffff0000, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm())) elif obj.isinstance(LogicalNetwork): groupid = _lastnetworkids.get(obj.getkey()) if groupid is not None: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | groupid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm() )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | groupid, cookie_mask = 0xffff00000000ffff, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm() )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(groupid, ofdef.OFPP_ANY)) )) # Never use flow mod to update an input flow of physical port, because the input_oxm may change. for obj in updatedvalues: if obj.isinstance(PhysicalPort): ofport = _portnames.get(obj.name) if ofport is not None: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )]) )) elif obj.isinstance(LogicalNetwork): groupid = _networkids.get(obj.getkey()) if groupid is not None: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | groupid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm() )) elif obj.isinstance(PhysicalNetwork): if obj in phyportdict: for p in phyportdict[obj]: ofport = _portnames.get(p.name) if ofport is not None and p not in addvalues and p not in updatedvalues: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )]) )) for m in self.execute_commands(connection, cmds): yield m del cmds[:] for obj in removevalues: if obj.isinstance(LogicalNetwork): groupid = _lastnetworkids.get(obj.getkey()) if groupid is not None: cmds.append(ofdef.ofp_group_mod(command = ofdef.OFPGC_DELETE, type = ofdef.OFPGT_ALL, group_id = groupid )) for m in self.execute_commands(connection, cmds): yield m del cmds[:] disablechaining = connection.protocol.disablechaining created_groups = {} def create_buckets(obj, groupid): # Generate buckets buckets = [ofdef.ofp_bucket(actions=[ofdef.ofp_action_output(port = _portids[p.id])]) for p in logportdict[obj] if p.id in _portids] allactions = [ofdef.ofp_action_output(port = _portids[p.id]) for p in logportdict[obj] if p.id in _portids] disablegroup = False if obj.physicalnetwork in phyportdict: for p in phyportdict[obj.physicalnetwork]: if (obj, p) in flowparts: fp = flowparts[(obj,p)] allactions.extend(fp[3]) if disablechaining and not disablegroup and any(a.type == ofdef.OFPAT_GROUP for a in fp[3]): # We cannot use chaining. We use a long action list instead, and hope there is no conflicts disablegroup = True else: buckets.append(ofdef.ofp_bucket(actions=list(fp[3]))) if disablegroup: created_groups[groupid] = allactions else: created_groups[groupid] = [ofdef.ofp_action_group(group_id = groupid)] return buckets for obj in addvalues: if obj.isinstance(LogicalNetwork): groupid = _networkids.get(obj.getkey()) if groupid is not None: cmds.append(ofdef.ofp_group_mod(command = ofdef.OFPGC_ADD, type = ofdef.OFPGT_ALL, group_id = groupid, buckets = create_buckets(obj, groupid) )) for obj in group_updates: groupid = _networkids.get(obj.getkey()) if groupid is not None: cmds.append(ofdef.ofp_group_mod(command = ofdef.OFPGC_MODIFY, type = ofdef.OFPGT_ALL, group_id = groupid, buckets = create_buckets(obj, groupid) )) for m in self.execute_commands(connection, cmds): yield m del cmds[:] # There are 5 kinds of flows: # 1. in_port = (Logical Port) # 2. in_port = (Physical_Port), network = (Logical_Network) # 3. out_port = (Logical Port) # 4. out_port = (Physical_Port), network = (Logical_Network) # 5. out_port = OFPP_ANY, network = (Logical_Network) for obj in addvalues: if obj.isinstance(LogicalPort): ofport = _portids.get(obj.id) lognetid = _networkids.get(obj.network.getkey()) if ofport is not None and lognetid is not None: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )]), instructions = create_input_instructions(lognetid, [], True) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport)), instructions = [ofdef.ofp_instruction_actions(actions = [ ofdef.ofp_action_output(port = ofport) ])] )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, True)), instructions = [ofdef.ofp_instruction_actions(actions = [ ofdef.ofp_action_output(port = ofdef.OFPP_IN_PORT) ])] )) # Ignore update of logical port # Physical port: for obj in addvalues: if obj.isinstance(PhysicalPort): ofport = _portnames.get(obj.name) if ofport is not None and obj.physicalnetwork in lognetdict: for lognet in lognetdict[obj.physicalnetwork]: lognetid = _networkids.get(lognet.getkey()) if lognetid is not None and (lognet, obj) in flowparts: input_oxm, input_actions, output_actions, _, output_actions2 = flowparts[(lognet, obj)] cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | lognetid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )] + list(input_oxm)), instructions = create_input_instructions(lognetid, input_actions, False) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, False)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions))] )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, True)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions2))] )) for lognet in addvalues: if lognet.isinstance(LogicalNetwork): lognetid = _networkids.get(lognet.getkey()) if lognetid is not None and lognet.physicalnetwork in phyportdict: for obj in phyportdict[lognet.physicalnetwork]: ofport = _portnames.get(obj.name) if ofport is not None and (lognet, obj) in flowparts and obj not in addvalues: input_oxm, input_actions, output_actions, _, output_actions2 = flowparts[(lognet, obj)] cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | lognetid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )] + input_oxm), instructions = create_input_instructions(lognetid, input_actions, False) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, False)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions))] )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, True)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions2))] )) for obj in updatedvalues: if obj.isinstance(PhysicalPort): ofport = _portnames.get(obj.name) if ofport is not None and obj.physicalnetwork in lognetdict: for lognet in lognetdict[obj.physicalnetwork]: lognetid = _networkids.get(lognet.getkey()) if lognetid is not None and (lognet, obj) in flowparts and not lognet in addvalues: input_oxm, input_actions, output_actions, _, output_actions2 = flowparts[(lognet, obj)] cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | lognetid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )] + input_oxm), instructions = create_input_instructions(lognetid, input_actions, False) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_MODIFY, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, False)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions))] )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_MODIFY, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, True)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions2))] )) for lognet in updatedvalues: if lognet.isinstance(LogicalNetwork): lognetid = _networkids.get(lognet.getkey()) if lognetid is not None and lognet.physicalnetwork in phyportdict: for obj in phyportdict[lognet.physicalnetwork]: ofport = _portnames.get(obj.name) if ofport is not None and (lognet, obj) in flowparts and obj not in addvalues and obj not in updatedvalues: input_oxm, input_actions, output_actions, _, output_actions2 = flowparts[(lognet, obj)] cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | lognetid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )] + input_oxm), instructions = create_input_instructions(lognetid, input_actions, False) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_MODIFY, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions))] )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_MODIFY, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, True)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions2))] )) # Physical network is updated for pnet in updatedvalues: if pnet.isinstance(PhysicalNetwork) and pnet in lognetdict: for lognet in lognetdict[pnet]: if lognet.isinstance(LogicalNetwork): lognetid = _networkids.get(lognet.getkey()) if lognetid is not None and lognet not in updatedvalues and lognet not in addvalues and lognet.physicalnetwork in phyportdict: for obj in phyportdict[lognet.physicalnetwork]: ofport = _portnames.get(obj.name) if ofport is not None and (lognet, obj) in flowparts and obj not in addvalues and obj not in updatedvalues: input_oxm, input_actions, output_actions, _, output_actions2 = flowparts[(lognet, obj)] cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | lognetid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )] + input_oxm), instructions = create_input_instructions(lognetid, input_actions, False) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_MODIFY, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions))] )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_MODIFY, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, True)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions2))] )) # Logical network broadcast for lognet in addvalues: if lognet.isinstance(LogicalNetwork): lognetid = _networkids.get(lognet.getkey()) if lognetid is not None and lognetid in created_groups: cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofdef.OFPP_ANY)), instructions = [ofdef.ofp_instruction_actions(actions = created_groups.pop(lognetid))] )) for lognetid, actions in created_groups.items(): cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofdef.OFPP_ANY)), instructions = [ofdef.ofp_instruction_actions(actions = actions)] )) # Ignore logical network update for m in self.execute_commands(connection, cmds): yield m except Exception: self._parent._logger.warning("Update flow for connection %r failed with exception", connection, exc_info = True) # We don't want the whole flow update stops, so ignore the exception and continue @defaultconfig @depend(ofpportmanager.OpenflowPortManager, ovsdbportmanager.OVSDBPortManager, objectdb.ObjectDB) class IOProcessing(FlowBase): "Ingress and Egress processing" _tablerequest = (("ingress", (), ''), ("egress", ("ingress",),'')) _default_vhostmap = {} def __init__(self, server): FlowBase.__init__(self, server) self.apiroutine = RoutineContainer(self.scheduler) self.apiroutine.main = self._main self.routines.append(self.apiroutine) self._flowupdaters = {} self._portchanging = set() self._portchanged = set() def _main(self): flow_init = FlowInitialize.createMatcher(_ismatch = lambda x: self.vhostbind is None or x.vhost in self.vhostbind) port_change = ModuleNotification.createMatcher("openflowportmanager", "update", _ismatch = lambda x: self.vhostbind is None or x.vhost in self.vhostbind) while True: yield (flow_init, port_change) e = self.apiroutine.event c = e.connection if self.apiroutine.matcher is flow_init: self.apiroutine.subroutine(self._init_conn(self.apiroutine.event.connection)) else: if self.apiroutine.event.reason == 'disconnected': self.apiroutine.subroutine(self._remove_conn(c)) else: self.apiroutine.subroutine(self._portchange(c)) def _init_conn(self, conn): # Default drop for m in conn.protocol.batch((conn.openflowdef.ofp_flow_mod(table_id = self._gettableindex("ingress", conn.protocol.vhost), command = conn.openflowdef.OFPFC_ADD, priority = 0, buffer_id = conn.openflowdef.OFP_NO_BUFFER, match = conn.openflowdef.ofp_match_oxm(), instructions = [conn.openflowdef.ofp_instruction_actions( type = conn.openflowdef.OFPIT_CLEAR_ACTIONS )] ), conn.openflowdef.ofp_flow_mod(table_id = self._gettableindex("egress", conn.protocol.vhost), command = conn.openflowdef.OFPFC_ADD, priority = 0, buffer_id = conn.openflowdef.OFP_NO_BUFFER, match = conn.openflowdef.ofp_match_oxm(), instructions = [conn.openflowdef.ofp_instruction_actions( type = conn.openflowdef.OFPIT_CLEAR_ACTIONS )] )), conn, self.apiroutine): yield m if conn in self._flowupdaters: self._flowupdaters[conn].close() datapath_id = conn.openflow_datapathid ovsdb_vhost = self.vhostmap.get(conn.protocol.vhost, "") for m in callAPI(self.apiroutine, 'ovsdbmanager', 'waitbridgeinfo', {'datapathid': datapath_id, 'vhost': ovsdb_vhost}): yield m bridgename, systemid, _ = self.apiroutine.retvalue new_updater = IOFlowUpdater(conn, systemid, bridgename, self) self._flowupdaters[conn] = new_updater new_updater.start() for m in self._portchange(conn): yield m def _remove_conn(self, conn): # Do not need to modify flows if conn in self._flowupdaters: self._flowupdaters[conn].close() del self._flowupdaters[conn] if False: yield def _portchange(self, conn): # Do not re-enter if conn in self._portchanging: self._portchanged.add(conn) return self._portchanging.add(conn) try: while True: self._portchanged.discard(conn) flow_updater = self._flowupdaters.get(conn) if flow_updater is None: break datapath_id = conn.openflow_datapathid ovsdb_vhost = self.vhostmap.get(conn.protocol.vhost, "") for m in callAPI(self.apiroutine, 'openflowportmanager', 'getports', {'datapathid': datapath_id, 'vhost': conn.protocol.vhost}): yield m ports = self.apiroutine.retvalue if conn in self._portchanged: continue if not conn.connected: self._portchanged.discard(conn) return def ovsdb_info(): resync = 0 while True: try: if conn in self._portchanged: self.apiroutine.retvalue = None return for m in self.apiroutine.executeAll([callAPI(self.apiroutine, 'ovsdbportmanager', 'waitportbyno', {'datapathid': datapath_id, 'vhost': ovsdb_vhost, 'portno': p.port_no, 'timeout': 5 + 5 * min(resync, 5) }) for p in ports]): yield m except StopIteration: break except Exception: self._logger.warning('Cannot retrieve port info from OVSDB for datapathid %016x, vhost = %r', datapath_id, ovsdb_vhost, exc_info = True) for m in callAPI(self.apiroutine, 'ovsdbmanager', 'getconnection', {'datapathid': datapath_id, 'vhost': ovsdb_vhost}): yield m if self.apiroutine.retvalue is None: self._logger.warning("OVSDB connection may not be ready for datapathid %016x, vhost = %r", datapath_id, ovsdb_vhost) trytimes = 0 while True: try: for m in callAPI(self.apiroutine, 'ovsdbmanager', 'waitconnection', {'datapathid': datapath_id, 'vhost': ovsdb_vhost}): yield m except Exception: trytimes += 1 if trytimes > 10: self._logger.warning("OVSDB connection is still not ready after a long time for %016x, vhost = %r. Keep waiting...", datapath_id, ovsdb_vhost) trytimes = 0 else: break else: self._logger.warning('OpenFlow ports may not be synchronized. Try resync...') # Connection is up but ports are not synchronized, try resync for m in self.apiroutine.executeAll([callAPI(self.apiroutine, 'openflowportmanager', 'resync', {'datapathid': datapath_id, 'vhost': conn.protocol.vhost}), callAPI(self.apiroutine, 'ovsdbportmanager', 'resync', {'datapathid': datapath_id, 'vhost': ovsdb_vhost})]): yield m # Do not resync too often for m in self.apiroutine.waitWithTimeout(0.1): yield m resync += 1 else: break self.apiroutine.retvalue = [r[0] for r in self.apiroutine.retvalue] conn_down = conn.protocol.statematcher(conn) try: for m in self.apiroutine.withException(ovsdb_info(), conn_down): yield m except RoutineException: self._portchanged.discard(conn) return if conn in self._portchanged: continue ovsdb_ports = self.apiroutine.retvalue flow_updater = self._flowupdaters.get(conn) if flow_updater is None: break for m in flow_updater.update_ports(ports, ovsdb_ports): yield m if conn not in self._portchanged: break finally: self._portchanging.remove(conn)
71.797787
186
0.402273
from vlcp.service.sdn.flowbase import FlowBase from vlcp.server.module import depend, ModuleNotification, callAPI import vlcp.service.sdn.ofpportmanager as ofpportmanager import vlcp.service.sdn.ovsdbportmanager as ovsdbportmanager import vlcp.service.kvdb.objectdb as objectdb from vlcp.event.event import Event, withIndices from vlcp.event.runnable import RoutineContainer, RoutineException from vlcp.config.config import defaultconfig from vlcp.service.sdn.ofpmanager import FlowInitialize from vlcp.utils.networkmodel import PhysicalPort, LogicalPort, PhysicalPortSet, LogicalPortSet, LogicalNetwork, PhysicalNetwork from vlcp.utils.flowupdater import FlowUpdater from vlcp.event.connection import ConnectionResetException from vlcp.protocol.openflow.openflow import OpenflowConnectionStateEvent,\ OpenflowErrorResultException from pprint import pformat from namedstruct import dump @withIndices('datapathid', 'vhost', 'connection', 'logicalportchanged', 'physicalportchanged', 'logicalnetworkchanged', 'physicalnetworkchanged') class DataObjectChanged(Event): pass class IDAssigner(object): def __init__(self): self._indices = {} self._revindices = {} self._revindices[0] = '<reserve0>' self._revindices[0xffff] = '<reserve65535>' self._lastindex = 1 def assign(self, key): if key in self._indices: return self._indices[key] else: ind = self._lastindex while ind in self._revindices: ind += 1 ind &= 0xffff self._revindices[ind] = key self._indices[key] = ind self._lastindex = ind + 1 return ind def unassign(self, keys): for k in keys: ind = self._indices.pop(k, None) if ind is not None: del self._revindices[ind] def frozen(self): return dict(self._indices) def _to32bitport(portno): if portno >= 0xff00: portno = 0xffff0000 | portno return portno class IOFlowUpdater(FlowUpdater): def __init__(self, connection, systemid, bridgename, parent): FlowUpdater.__init__(self, connection, (LogicalPortSet.default_key(), PhysicalPortSet.default_key()), ('ioprocessing', connection), parent._logger) self._walkerdict = {LogicalPortSet.default_key(): self._logicalport_walker, PhysicalPortSet.default_key(): self._physicalport_walker } self._systemid = systemid self._bridgename = bridgename self._portnames = {} self._portids = {} self._currentportids = {} self._currentportnames = {} self._lastportids = {} self._lastportnames = {} self._lastnetworkids = {} self._networkids = IDAssigner() self._phynetworkids = IDAssigner() self._physicalnetworkids = {} self._logicalportkeys = set() self._physicalportkeys = set() self._logicalnetworkkeys = set() self._physicalnetworkkeys = set() self._parent = parent def update_ports(self, ports, ovsdb_ports): self._portnames.clear() self._portnames.update((p['name'], _to32bitport(p['ofport'])) for p in ovsdb_ports) self._portids.clear() self._portids.update((p['id'], _to32bitport(p['ofport'])) for p in ovsdb_ports if p['id']) for m in self.restart_walk(): yield m def _logicalport_walker(self, key, value, walk, save): save(key) if value is None: return logset = value.set for id in self._portids: logports = logset.find(LogicalPort, id) for p in logports: try: logp = walk(p.getkey()) except KeyError: pass else: save(logp.getkey()) try: lognet = walk(logp.network.getkey()) except KeyError: pass else: save(lognet.getkey()) try: phynet = walk(lognet.physicalnetwork.getkey()) except KeyError: pass else: save(phynet.getkey()) def _physicalport_walker(self, key, value, walk, save): save(key) if value is None: return physet = value.set for name in self._portnames: phyports = physet.find(PhysicalPort, self._connection.protocol.vhost, self._systemid, self._bridgename, name) namedict = {} for p in phyports: _, inds = PhysicalPort._getIndices(p.getkey()) name = inds[-1] ind_key = [i != '%' for i in inds] if name != '%': if name in namedict: if namedict[name][0] < ind_key: namedict[name] = (ind_key, p) else: namedict[name] = (ind_key, p) phyports = [v[1] for v in namedict.values()] for p in phyports: try: phyp = walk(p.getkey()) except KeyError: pass else: save(phyp.getkey()) try: phynet = walk(phyp.physicalnetwork.getkey()) except KeyError: pass else: save(phynet.getkey()) def walkcomplete(self, keys, values): conn = self._connection dpid = conn.openflow_datapathid vhost = conn.protocol.vhost _currentportids = dict(self._portids) _currentportnames = dict(self._portnames) updated_data = {} current_data = {} for cls, name, idg, assigner in ((LogicalPort, '_logicalportkeys', lambda x: _currentportids[x.id], None), (PhysicalPort, '_physicalportkeys', lambda x: _currentportnames[x.name], None), (LogicalNetwork, '_logicalnetworkkeys', lambda x: self._networkids.assign(x.getkey()), self._networkids), (PhysicalNetwork, '_physicalnetworkkeys', lambda x: self._phynetworkids.assign(x.getkey()), self._phynetworkids), ): objs = [v for v in values if v is not None and not v.isdeleted() and v.isinstance(cls)] objkeys = set([v.getkey() for v in objs]) oldkeys = getattr(self, name) if objkeys != oldkeys: if assigner is not None: assigner.unassign(oldkeys.difference(objkeys)) setattr(self, name, objkeys) updated_data[cls] = True cv = [(o, idg(o)) for o in objs] current_data[cls] = cv if updated_data: for m in self.waitForSend(DataObjectChanged(dpid, vhost, conn, LogicalPort in updated_data, PhysicalPort in updated_data, LogicalNetwork in updated_data, PhysicalNetwork in updated_data, current = (current_data.get(LogicalPort), current_data.get(PhysicalPort), current_data.get(LogicalNetwork), current_data.get(PhysicalNetwork)))): yield m self._currentportids = _currentportids self._currentportnames = _currentportnames def updateflow(self, connection, addvalues, removevalues, updatedvalues): try: cmds = [] ofdef = connection.openflowdef vhost = connection.protocol.vhost input_table = self._parent._gettableindex('ingress', vhost) input_next = self._parent._getnexttable('', 'ingress', vhost = vhost) output_table = self._parent._gettableindex('egress', vhost) _lastportids = self._lastportids _lastportnames = self._lastportnames _lastnetworkids = self._lastnetworkids _portids = dict(self._currentportids) _portnames = dict(self._currentportnames) _networkids = self._networkids.frozen() exist_objs = dict((obj.getkey(), obj) for obj in self._savedresult if obj is not None and not obj.isdeleted()) phyportset = [obj for obj in self._savedresult if obj is not None and not obj.isdeleted() and obj.isinstance(PhysicalPort)] phynetset = [obj for obj in self._savedresult if obj is not None and not obj.isdeleted() and obj.isinstance(PhysicalNetwork)] lognetset = [obj for obj in self._savedresult if obj is not None and not obj.isdeleted() and obj.isinstance(LogicalNetwork)] logportset = [obj for obj in self._savedresult if obj is not None and not obj.isdeleted() and obj.isinstance(LogicalPort)] logportofps = set(_portids[lp.id] for lp in logportset if lp.id in _portids) _portnames = dict((n,v) for n,v in _portnames.items() if v not in logportofps) self._lastportids = _portids self._lastportnames = _portnames self._lastnetworkids = _networkids phyportdict = {} for p in phyportset: phyportdict.setdefault(p.physicalnetwork, []).append(p) lognetdict = {} for n in lognetset: lognetdict.setdefault(n.physicalnetwork, []).append(n) logportdict = {} for p in logportset: logportdict.setdefault(p.network, []).append(p) allapis = [] group_updates = set([obj for obj in updatedvalues if obj.isinstance(LogicalNetwork)]) group_updates.update(obj.network for obj in addvalues if obj.isinstance(LogicalPort)) group_updates.update(exist_objs[obj.network.getkey()] for obj in removevalues if obj.isinstance(LogicalPort) and obj.network.getkey() in exist_objs) updated_physicalnetworks = set(obj for obj in updatedvalues if obj.isinstance(PhysicalNetwork)) updated_physicalnetworks.update(p.physicalnetwork for p in addvalues if p.isinstance(PhysicalPort)) updated_physicalnetworks.update(exist_objs[p.physicalnetwork.getkey()] for p in removevalues if p.isinstance(PhysicalPort) and p.physicalnetwork.getkey() in exist_objs) updated_physicalnetworks.update(p.physicalnetwork for p in updatedvalues if p.isinstance(PhysicalPort)) group_updates.update(lnet for pnet in updated_physicalnetworks if pnet in lognetdict for lnet in lognetdict[pnet]) for pnet in phynetset: if pnet in lognetdict and pnet in phyportdict: for lognet in lognetdict[pnet]: netid = _networkids.get(lognet.getkey()) if netid is not None: for p in phyportdict[pnet]: if lognet in addvalues or lognet in group_updates or p in addvalues or p in updatedvalues: pid = _portnames.get(p.name) if pid is not None: def subr(lognet, p, netid, pid): try: for m in callAPI(self, 'public', 'createioflowparts', {'connection': connection, 'logicalnetwork': lognet, 'physicalport': p, 'logicalnetworkid': netid, 'physicalportid': pid}): yield m except Exception: self._parent._logger.warning("Create flow parts failed for %r and %r", lognet, p, exc_info = True) self.retvalue = None else: self.retvalue = ((lognet, p), self.retvalue) allapis.append(subr(lognet, p, netid, pid)) for m in self.executeAll(allapis): yield m flowparts = dict(r[0] for r in self.retvalue if r[0] is not None) if connection.protocol.disablenxext: def create_input_instructions(lognetid, extra_actions, is_logport): lognetid = (lognetid & 0xffff) instructions = [ofdef.ofp_instruction_write_metadata( metadata = (lognetid << 48) | (lognetid << 32) | ((0x4000 if is_logport else 0) << 16) | (ofdef.OFPP_ANY & 0xffff), metadata_mask = 0xffffffffffffffff ), ofdef.ofp_instruction_goto_table(table_id = input_next) ] if extra_actions: instructions.insert(0, ofdef.ofp_instruction_actions(actions = list(extra_actions))) return instructions def create_output_oxm(lognetid, portid, in_port = False): r = [ofdef.create_oxm(ofdef.OXM_OF_METADATA_W, (portid & 0xFFFF) | (0x80000000 if in_port else 0) | ((lognetid & 0xFFFF) << 32), 0x0000FFFF8000FFFF)] if in_port: r.append(ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, portid)) return r else: def create_input_instructions(lognetid, extra_actions, is_logport): lognetid = (lognetid & 0xffff) return [ofdef.ofp_instruction_actions(actions = [ ofdef.ofp_action_set_field( field = ofdef.create_oxm(ofdef.NXM_NX_REG4, lognetid) ), ofdef.ofp_action_set_field( field = ofdef.create_oxm(ofdef.NXM_NX_REG5, lognetid) ), ofdef.ofp_action_set_field( field = ofdef.create_oxm(ofdef.NXM_NX_REG6, ofdef.OFPP_ANY) ), ofdef.ofp_action_set_field( field = ofdef.create_oxm(ofdef.NXM_NX_REG7, (0x4000 if is_logport else 0)) ) ] + list(extra_actions)), ofdef.ofp_instruction_goto_table(table_id = input_next) ] def create_output_oxm(lognetid, portid, in_port = False): r = [ofdef.create_oxm(ofdef.NXM_NX_REG5, lognetid), ofdef.create_oxm(ofdef.NXM_NX_REG6, portid), ofdef.create_oxm(ofdef.NXM_NX_REG7_W, 0x8000 if in_port else 0, 0x8000)] if in_port: r.append(ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, portid)) return r for obj in removevalues: if obj.isinstance(LogicalPort): ofport = _lastportids.get(obj.id) if ofport is not None: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )]) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofport, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm())) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_IN_PORT, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport)]))) elif obj.isinstance(PhysicalPort): ofport = _lastportnames.get(obj.name) if ofport is not None: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )]) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffff0000, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm())) elif obj.isinstance(LogicalNetwork): groupid = _lastnetworkids.get(obj.getkey()) if groupid is not None: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | groupid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm() )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | groupid, cookie_mask = 0xffff00000000ffff, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm() )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(groupid, ofdef.OFPP_ANY)) )) for obj in updatedvalues: if obj.isinstance(PhysicalPort): ofport = _portnames.get(obj.name) if ofport is not None: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )]) )) elif obj.isinstance(LogicalNetwork): groupid = _networkids.get(obj.getkey()) if groupid is not None: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | groupid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm() )) elif obj.isinstance(PhysicalNetwork): if obj in phyportdict: for p in phyportdict[obj]: ofport = _portnames.get(p.name) if ofport is not None and p not in addvalues and p not in updatedvalues: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, command = ofdef.OFPFC_DELETE, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )]) )) for m in self.execute_commands(connection, cmds): yield m del cmds[:] for obj in removevalues: if obj.isinstance(LogicalNetwork): groupid = _lastnetworkids.get(obj.getkey()) if groupid is not None: cmds.append(ofdef.ofp_group_mod(command = ofdef.OFPGC_DELETE, type = ofdef.OFPGT_ALL, group_id = groupid )) for m in self.execute_commands(connection, cmds): yield m del cmds[:] disablechaining = connection.protocol.disablechaining created_groups = {} def create_buckets(obj, groupid): buckets = [ofdef.ofp_bucket(actions=[ofdef.ofp_action_output(port = _portids[p.id])]) for p in logportdict[obj] if p.id in _portids] allactions = [ofdef.ofp_action_output(port = _portids[p.id]) for p in logportdict[obj] if p.id in _portids] disablegroup = False if obj.physicalnetwork in phyportdict: for p in phyportdict[obj.physicalnetwork]: if (obj, p) in flowparts: fp = flowparts[(obj,p)] allactions.extend(fp[3]) if disablechaining and not disablegroup and any(a.type == ofdef.OFPAT_GROUP for a in fp[3]): disablegroup = True else: buckets.append(ofdef.ofp_bucket(actions=list(fp[3]))) if disablegroup: created_groups[groupid] = allactions else: created_groups[groupid] = [ofdef.ofp_action_group(group_id = groupid)] return buckets for obj in addvalues: if obj.isinstance(LogicalNetwork): groupid = _networkids.get(obj.getkey()) if groupid is not None: cmds.append(ofdef.ofp_group_mod(command = ofdef.OFPGC_ADD, type = ofdef.OFPGT_ALL, group_id = groupid, buckets = create_buckets(obj, groupid) )) for obj in group_updates: groupid = _networkids.get(obj.getkey()) if groupid is not None: cmds.append(ofdef.ofp_group_mod(command = ofdef.OFPGC_MODIFY, type = ofdef.OFPGT_ALL, group_id = groupid, buckets = create_buckets(obj, groupid) )) for m in self.execute_commands(connection, cmds): yield m del cmds[:] for obj in addvalues: if obj.isinstance(LogicalPort): ofport = _portids.get(obj.id) lognetid = _networkids.get(obj.network.getkey()) if ofport is not None and lognetid is not None: cmds.append(ofdef.ofp_flow_mod(table_id = input_table, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )]), instructions = create_input_instructions(lognetid, [], True) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport)), instructions = [ofdef.ofp_instruction_actions(actions = [ ofdef.ofp_action_output(port = ofport) ])] )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, True)), instructions = [ofdef.ofp_instruction_actions(actions = [ ofdef.ofp_action_output(port = ofdef.OFPP_IN_PORT) ])] )) for obj in addvalues: if obj.isinstance(PhysicalPort): ofport = _portnames.get(obj.name) if ofport is not None and obj.physicalnetwork in lognetdict: for lognet in lognetdict[obj.physicalnetwork]: lognetid = _networkids.get(lognet.getkey()) if lognetid is not None and (lognet, obj) in flowparts: input_oxm, input_actions, output_actions, _, output_actions2 = flowparts[(lognet, obj)] cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | lognetid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )] + list(input_oxm)), instructions = create_input_instructions(lognetid, input_actions, False) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, False)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions))] )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, True)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions2))] )) for lognet in addvalues: if lognet.isinstance(LogicalNetwork): lognetid = _networkids.get(lognet.getkey()) if lognetid is not None and lognet.physicalnetwork in phyportdict: for obj in phyportdict[lognet.physicalnetwork]: ofport = _portnames.get(obj.name) if ofport is not None and (lognet, obj) in flowparts and obj not in addvalues: input_oxm, input_actions, output_actions, _, output_actions2 = flowparts[(lognet, obj)] cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | lognetid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )] + input_oxm), instructions = create_input_instructions(lognetid, input_actions, False) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, False)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions))] )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, True)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions2))] )) for obj in updatedvalues: if obj.isinstance(PhysicalPort): ofport = _portnames.get(obj.name) if ofport is not None and obj.physicalnetwork in lognetdict: for lognet in lognetdict[obj.physicalnetwork]: lognetid = _networkids.get(lognet.getkey()) if lognetid is not None and (lognet, obj) in flowparts and not lognet in addvalues: input_oxm, input_actions, output_actions, _, output_actions2 = flowparts[(lognet, obj)] cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | lognetid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )] + input_oxm), instructions = create_input_instructions(lognetid, input_actions, False) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_MODIFY, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, False)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions))] )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_MODIFY, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, True)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions2))] )) for lognet in updatedvalues: if lognet.isinstance(LogicalNetwork): lognetid = _networkids.get(lognet.getkey()) if lognetid is not None and lognet.physicalnetwork in phyportdict: for obj in phyportdict[lognet.physicalnetwork]: ofport = _portnames.get(obj.name) if ofport is not None and (lognet, obj) in flowparts and obj not in addvalues and obj not in updatedvalues: input_oxm, input_actions, output_actions, _, output_actions2 = flowparts[(lognet, obj)] cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | lognetid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )] + input_oxm), instructions = create_input_instructions(lognetid, input_actions, False) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_MODIFY, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions))] )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_MODIFY, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, True)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions2))] )) for pnet in updatedvalues: if pnet.isinstance(PhysicalNetwork) and pnet in lognetdict: for lognet in lognetdict[pnet]: if lognet.isinstance(LogicalNetwork): lognetid = _networkids.get(lognet.getkey()) if lognetid is not None and lognet not in updatedvalues and lognet not in addvalues and lognet.physicalnetwork in phyportdict: for obj in phyportdict[lognet.physicalnetwork]: ofport = _portnames.get(obj.name) if ofport is not None and (lognet, obj) in flowparts and obj not in addvalues and obj not in updatedvalues: input_oxm, input_actions, output_actions, _, output_actions2 = flowparts[(lognet, obj)] cmds.append(ofdef.ofp_flow_mod(table_id = input_table, cookie = 0x0001000000000000 | lognetid, cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = [ ofdef.create_oxm(ofdef.OXM_OF_IN_PORT, ofport )] + input_oxm), instructions = create_input_instructions(lognetid, input_actions, False) )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_MODIFY, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions))] )) cmds.append(ofdef.ofp_flow_mod(table_id = output_table, cookie = 0x0001000000000000 | lognetid | ((ofport & 0xffff) << 16), cookie_mask = 0xffffffffffffffff, command = ofdef.OFPFC_MODIFY, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofport, True)), instructions = [ofdef.ofp_instruction_actions(actions = list(output_actions2))] )) for lognet in addvalues: if lognet.isinstance(LogicalNetwork): lognetid = _networkids.get(lognet.getkey()) if lognetid is not None and lognetid in created_groups: cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofdef.OFPP_ANY)), instructions = [ofdef.ofp_instruction_actions(actions = created_groups.pop(lognetid))] )) for lognetid, actions in created_groups.items(): cmds.append(ofdef.ofp_flow_mod(table_id = output_table, command = ofdef.OFPFC_ADD, priority = ofdef.OFP_DEFAULT_PRIORITY, buffer_id = ofdef.OFP_NO_BUFFER, out_port = ofdef.OFPP_ANY, out_group = ofdef.OFPG_ANY, match = ofdef.ofp_match_oxm(oxm_fields = create_output_oxm(lognetid, ofdef.OFPP_ANY)), instructions = [ofdef.ofp_instruction_actions(actions = actions)] )) for m in self.execute_commands(connection, cmds): yield m except Exception: self._parent._logger.warning("Update flow for connection %r failed with exception", connection, exc_info = True) @defaultconfig @depend(ofpportmanager.OpenflowPortManager, ovsdbportmanager.OVSDBPortManager, objectdb.ObjectDB) class IOProcessing(FlowBase): _tablerequest = (("ingress", (), ''), ("egress", ("ingress",),'')) _default_vhostmap = {} def __init__(self, server): FlowBase.__init__(self, server) self.apiroutine = RoutineContainer(self.scheduler) self.apiroutine.main = self._main self.routines.append(self.apiroutine) self._flowupdaters = {} self._portchanging = set() self._portchanged = set() def _main(self): flow_init = FlowInitialize.createMatcher(_ismatch = lambda x: self.vhostbind is None or x.vhost in self.vhostbind) port_change = ModuleNotification.createMatcher("openflowportmanager", "update", _ismatch = lambda x: self.vhostbind is None or x.vhost in self.vhostbind) while True: yield (flow_init, port_change) e = self.apiroutine.event c = e.connection if self.apiroutine.matcher is flow_init: self.apiroutine.subroutine(self._init_conn(self.apiroutine.event.connection)) else: if self.apiroutine.event.reason == 'disconnected': self.apiroutine.subroutine(self._remove_conn(c)) else: self.apiroutine.subroutine(self._portchange(c)) def _init_conn(self, conn): # Default drop for m in conn.protocol.batch((conn.openflowdef.ofp_flow_mod(table_id = self._gettableindex("ingress", conn.protocol.vhost), command = conn.openflowdef.OFPFC_ADD, priority = 0, buffer_id = conn.openflowdef.OFP_NO_BUFFER, match = conn.openflowdef.ofp_match_oxm(), instructions = [conn.openflowdef.ofp_instruction_actions( type = conn.openflowdef.OFPIT_CLEAR_ACTIONS )] ), conn.openflowdef.ofp_flow_mod(table_id = self._gettableindex("egress", conn.protocol.vhost), command = conn.openflowdef.OFPFC_ADD, priority = 0, buffer_id = conn.openflowdef.OFP_NO_BUFFER, match = conn.openflowdef.ofp_match_oxm(), instructions = [conn.openflowdef.ofp_instruction_actions( type = conn.openflowdef.OFPIT_CLEAR_ACTIONS )] )), conn, self.apiroutine): yield m if conn in self._flowupdaters: self._flowupdaters[conn].close() datapath_id = conn.openflow_datapathid ovsdb_vhost = self.vhostmap.get(conn.protocol.vhost, "") for m in callAPI(self.apiroutine, 'ovsdbmanager', 'waitbridgeinfo', {'datapathid': datapath_id, 'vhost': ovsdb_vhost}): yield m bridgename, systemid, _ = self.apiroutine.retvalue new_updater = IOFlowUpdater(conn, systemid, bridgename, self) self._flowupdaters[conn] = new_updater new_updater.start() for m in self._portchange(conn): yield m def _remove_conn(self, conn): # Do not need to modify flows if conn in self._flowupdaters: self._flowupdaters[conn].close() del self._flowupdaters[conn] if False: yield def _portchange(self, conn): # Do not re-enter if conn in self._portchanging: self._portchanged.add(conn) return self._portchanging.add(conn) try: while True: self._portchanged.discard(conn) flow_updater = self._flowupdaters.get(conn) if flow_updater is None: break datapath_id = conn.openflow_datapathid ovsdb_vhost = self.vhostmap.get(conn.protocol.vhost, "") for m in callAPI(self.apiroutine, 'openflowportmanager', 'getports', {'datapathid': datapath_id, 'vhost': conn.protocol.vhost}): yield m ports = self.apiroutine.retvalue if conn in self._portchanged: continue if not conn.connected: self._portchanged.discard(conn) return def ovsdb_info(): resync = 0 while True: try: if conn in self._portchanged: self.apiroutine.retvalue = None return for m in self.apiroutine.executeAll([callAPI(self.apiroutine, 'ovsdbportmanager', 'waitportbyno', {'datapathid': datapath_id, 'vhost': ovsdb_vhost, 'portno': p.port_no, 'timeout': 5 + 5 * min(resync, 5) }) for p in ports]): yield m except StopIteration: break except Exception: self._logger.warning('Cannot retrieve port info from OVSDB for datapathid %016x, vhost = %r', datapath_id, ovsdb_vhost, exc_info = True) for m in callAPI(self.apiroutine, 'ovsdbmanager', 'getconnection', {'datapathid': datapath_id, 'vhost': ovsdb_vhost}): yield m if self.apiroutine.retvalue is None: self._logger.warning("OVSDB connection may not be ready for datapathid %016x, vhost = %r", datapath_id, ovsdb_vhost) trytimes = 0 while True: try: for m in callAPI(self.apiroutine, 'ovsdbmanager', 'waitconnection', {'datapathid': datapath_id, 'vhost': ovsdb_vhost}): yield m except Exception: trytimes += 1 if trytimes > 10: self._logger.warning("OVSDB connection is still not ready after a long time for %016x, vhost = %r. Keep waiting...", datapath_id, ovsdb_vhost) trytimes = 0 else: break else: self._logger.warning('OpenFlow ports may not be synchronized. Try resync...') # Connection is up but ports are not synchronized, try resync for m in self.apiroutine.executeAll([callAPI(self.apiroutine, 'openflowportmanager', 'resync', {'datapathid': datapath_id, 'vhost': conn.protocol.vhost}), callAPI(self.apiroutine, 'ovsdbportmanager', 'resync', {'datapathid': datapath_id, 'vhost': ovsdb_vhost})]): yield m # Do not resync too often for m in self.apiroutine.waitWithTimeout(0.1): yield m resync += 1 else: break self.apiroutine.retvalue = [r[0] for r in self.apiroutine.retvalue] conn_down = conn.protocol.statematcher(conn) try: for m in self.apiroutine.withException(ovsdb_info(), conn_down): yield m except RoutineException: self._portchanged.discard(conn) return if conn in self._portchanged: continue ovsdb_ports = self.apiroutine.retvalue flow_updater = self._flowupdaters.get(conn) if flow_updater is None: break for m in flow_updater.update_ports(ports, ovsdb_ports): yield m if conn not in self._portchanged: break finally: self._portchanging.remove(conn)
true
true
1c3bf793413a01c5a3666ed29a0957de712d44d4
40
py
Python
crslab/data/dataset/durecdial/__init__.py
hcmus-nlp-chatbot/CRSLab
b3ab262a4ad93cbae98fe66541eb735377768a35
[ "MIT" ]
315
2021-01-05T06:31:57.000Z
2022-03-16T21:12:23.000Z
crslab/data/dataset/durecdial/__init__.py
hcmus-nlp-chatbot/CRSLab
b3ab262a4ad93cbae98fe66541eb735377768a35
[ "MIT" ]
23
2021-01-09T05:43:26.000Z
2022-03-28T21:05:49.000Z
crslab/data/dataset/durecdial/__init__.py
hcmus-nlp-chatbot/CRSLab
b3ab262a4ad93cbae98fe66541eb735377768a35
[ "MIT" ]
71
2021-01-05T06:31:59.000Z
2022-03-06T06:30:35.000Z
from .durecdial import DuRecDialDataset
20
39
0.875
from .durecdial import DuRecDialDataset
true
true
1c3bf8ef0212f14efbfd1e0e7d3f8a907c38e4f8
9,060
py
Python
plot_barchart.py
codeformuenster/COVID-19-NRW
6e35f28fc29e76b2839145880f4d796b70950661
[ "Apache-2.0" ]
1
2020-03-21T19:53:26.000Z
2020-03-21T19:53:26.000Z
plot_barchart.py
codeformuenster/COVID-19-NRW
6e35f28fc29e76b2839145880f4d796b70950661
[ "Apache-2.0" ]
5
2020-03-23T07:52:53.000Z
2020-04-16T07:05:46.000Z
plot_barchart.py
codeformuenster/COVID-19-NRW
6e35f28fc29e76b2839145880f4d796b70950661
[ "Apache-2.0" ]
1
2020-03-25T21:43:26.000Z
2020-03-25T21:43:26.000Z
from functools import reduce from datetime import datetime as dt import pandas as pd import numpy as np import seaborn as sns import matplotlib import matplotlib.pyplot as plt from matplotlib.figure import Figure matplotlib.use("agg") COLOR_DEATHS = "#dd6600" COLOR_RECOVERED = "#dbcd00" COLOR_ACTIVE = "#2792cb" COLOR_CONFIRMED_NEW = "#2792cb" # a pattern is added below HATCH_COLOR = 'white' # currently unused, see line 213 def load(kommune): df_confirmed_raw = pd.read_csv( "data/time_series/time_series_covid-19_nrw_confirmed.csv" ) df_confirmed = ( df_confirmed_raw[df_confirmed_raw.Kommune == kommune] .transpose() .reset_index() .drop([0]) ) df_confirmed.columns = ["date", "confirmed"] df_confirmed["confirmed_data_available"] = ~df_confirmed["confirmed"].isna() df_confirmed.fillna(method="ffill", inplace=True) df_confirmed["date"] = pd.to_datetime(df_confirmed["date"]) df_confirmed["confirmed_yesterday"] = ( df_confirmed["confirmed"] - df_confirmed["confirmed"].diff() ) df_confirmed["confirmed_new"] = df_confirmed["confirmed"].diff() df_confirmed.loc[df_confirmed['confirmed_new'] < 0, ['confirmed_new']] = 0 df_confirmed["confirmed_change_rate"] = df_confirmed["confirmed"].pct_change() df_recovered_raw = pd.read_csv( "data/time_series/time_series_covid-19_nrw_recovered.csv" ) df_recovered = ( df_recovered_raw[df_recovered_raw.Kommune == kommune] .transpose() .reset_index() .drop([0]) ) df_recovered.columns = ["date", "recovered"] df_recovered["recovered_data_available"] = ~df_recovered["recovered"].isna() df_recovered.fillna(method="ffill", inplace=True) df_recovered["date"] = pd.to_datetime(df_recovered["date"]) df_recovered["recovered_delta"] = df_recovered["recovered"].diff() df_recovered["recovered_change_rate"] = df_recovered["recovered"].pct_change() df_deaths_raw = pd.read_csv("data/time_series/time_series_covid-19_nrw_deaths.csv") df_deaths = ( df_deaths_raw[df_deaths_raw.Kommune == kommune] .transpose() .reset_index() .drop([0]) ) df_deaths.columns = ["date", "deaths"] df_deaths["deaths_data_available"] = ~df_deaths["deaths"].isna() df_deaths.fillna(method="ffill", inplace=True) df_deaths["date"] = pd.to_datetime(df_deaths["date"]) df_deaths["deaths_delta"] = df_deaths["deaths"].diff() df_deaths["deaths_change_rate"] = df_deaths["deaths"].pct_change() dfs = [df_confirmed, df_recovered, df_deaths] df = reduce(lambda left, right: pd.merge(left, right, on="date"), dfs) df["active"] = df["confirmed"] - df["recovered"] - df["deaths"] df["active_without_new"] = ( df["confirmed"] - df["recovered"] - df["deaths"] - df["confirmed_new"] ) df["active_delta"] = df_deaths["deaths"].diff() df["active_change_rate"] = df_deaths["deaths"].pct_change() df.fillna(value=0, inplace=True) return df def plot(kommune): def plot_label(df, ax): for index, row in df.iterrows(): if row["date"] >= dt.strptime("2020-03-13", "%Y-%m-%d"): if not np.isnan(row["confirmed_new"]): text = "%.0f" % row["confirmed_new"] ax.text( index, df["recovered"].loc[index] + df["active"].loc[index] + df["deaths"].loc[index] + 3, text, horizontalalignment="center", fontsize=10, color="#000000", ) for index, row in df.iterrows(): if row["date"] >= dt.strptime("2020-03-13", "%Y-%m-%d"): text = "%.0f" % row["active_without_new"] ax.text( index, df["recovered"].loc[index] + df["active"].loc[index] / 2, text, horizontalalignment="center", fontsize=10, color="#FFFFFF", ) for index, row in df.iterrows(): if row["date"] >= dt.strptime("2020-03-16", "%Y-%m-%d"): text = int(row["recovered"]) ax.text( index, df["recovered"].loc[index] / 2 + 3.0, text, horizontalalignment="center", fontsize=10, color="#FFFFFF", ) for index, row in df.iterrows(): if row["date"] >= dt.strptime("2020-03-26", "%Y-%m-%d"): text = int(row["deaths"]) ax.text( index, df["deaths"].loc[index] + 3.0, text, horizontalalignment="center", fontsize=10, color="#FFFFFF", ) def plot_doubled_since(df, ax): idx_last_entry = df.index.max() has_doubled = df["confirmed"] <= max(df["confirmed"] / 2) if has_doubled.any(): idx_doubled_since = df[has_doubled].index.max() last_entry_date = df.loc[idx_last_entry]["date"] doubled_since_date = df.loc[idx_doubled_since]["date"] doubled_since_in_days = (last_entry_date - doubled_since_date).days - 1 ax.hlines( max(df["confirmed"]), idx_doubled_since, idx_last_entry, linestyles="dashed", lw=1, color=COLOR_CONFIRMED_NEW, ) ax.vlines( idx_doubled_since, max(df["confirmed"]), max(df["confirmed"] / 2), linestyles="dashed", lw=1, color=COLOR_CONFIRMED_NEW, ) ax.annotate( f"Letzte Verdoppelung aller bestätigten Fälle: \n{doubled_since_in_days} Tage", (idx_doubled_since + 0.5, max(df["confirmed"] / 1.1)), ) def plot_axis(ax): ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.set_xlabel("") ax.set_ylabel("Anzahl an Fällen", fontsize=12) ax.yaxis.set_label_position("right") x_labels = df["date"].dt.strftime("%d.%m.") ax.set_xticklabels(labels=x_labels, rotation=45, ha="right") ax.set(yticks=np.arange(0, max(df["confirmed"]) + 50, step=100)) ax.yaxis.tick_right() def plot_legend(ax): handles, labels = ax.get_legend_handles_labels() ax.legend( reversed(handles), reversed(["Verstorbene", "Genesene", "Bisher Erkrankte", "Neuinfektionen"]), frameon=False, ) def plot_bar(df): return df.plot.bar( x="date", y=["deaths", "recovered", "active_without_new", "confirmed_new"], stacked=True, color=[COLOR_DEATHS, COLOR_RECOVERED, COLOR_ACTIVE, COLOR_CONFIRMED_NEW], figsize=(20, 10), width=0.8, fontsize=13, linewidth=0 ) df = load(kommune) ax = plot_bar(df) # add pattern (hatch) (only) to new infections bar bars = ax.patches patterns = (' ', ' ', ' ','//') # new infections is the last bar edgecolors = (COLOR_DEATHS, COLOR_RECOVERED, COLOR_ACTIVE, HATCH_COLOR) hatches = [p for p in patterns for i in range(len(df))] hatches_colors = [c for c in edgecolors for i in range(len(df))] for bar, hatch, hatch_color in zip(bars, hatches, hatches_colors): # bar.set_edgecolor(hatch_color) # uncomment to use HATCH_COLOR bar.set_hatch(hatch) plot_label(df, ax) plot_axis(ax) plot_legend(ax) plot_doubled_since(df, ax) return ax.get_figure() def save(): def get_kommunen(): df_raw = pd.read_csv("data/time_series/time_series_covid-19_nrw_confirmed.csv") return df_raw["Kommune"].unique() def get_short_name(kommune): return str.split(kommune)[1].lower() def get_image_name(short_name): return "images/covid-19-" + short_name + ".svg" def save_plotted_svg(kommune, image_name): fig = plot(kommune) fig.savefig(image_name, bbox_inches="tight") def generate_html(short_name, image_name): f = open("diff_plot_" + short_name + "_temp.html", "w") f.write('<div style="text-align: center;">') f.write("<img src='" + image_name + "'/>") f.write("</div>") f.close() kommunen = get_kommunen() for kommune in kommunen: short_name = get_short_name(kommune) image_name = get_image_name(short_name) save_plotted_svg(kommune, image_name) generate_html(short_name, image_name) if __name__ == "__main__": save()
33.308824
95
0.566115
from functools import reduce from datetime import datetime as dt import pandas as pd import numpy as np import seaborn as sns import matplotlib import matplotlib.pyplot as plt from matplotlib.figure import Figure matplotlib.use("agg") COLOR_DEATHS = "#dd6600" COLOR_RECOVERED = "#dbcd00" COLOR_ACTIVE = "#2792cb" COLOR_CONFIRMED_NEW = "#2792cb" HATCH_COLOR = 'white' def load(kommune): df_confirmed_raw = pd.read_csv( "data/time_series/time_series_covid-19_nrw_confirmed.csv" ) df_confirmed = ( df_confirmed_raw[df_confirmed_raw.Kommune == kommune] .transpose() .reset_index() .drop([0]) ) df_confirmed.columns = ["date", "confirmed"] df_confirmed["confirmed_data_available"] = ~df_confirmed["confirmed"].isna() df_confirmed.fillna(method="ffill", inplace=True) df_confirmed["date"] = pd.to_datetime(df_confirmed["date"]) df_confirmed["confirmed_yesterday"] = ( df_confirmed["confirmed"] - df_confirmed["confirmed"].diff() ) df_confirmed["confirmed_new"] = df_confirmed["confirmed"].diff() df_confirmed.loc[df_confirmed['confirmed_new'] < 0, ['confirmed_new']] = 0 df_confirmed["confirmed_change_rate"] = df_confirmed["confirmed"].pct_change() df_recovered_raw = pd.read_csv( "data/time_series/time_series_covid-19_nrw_recovered.csv" ) df_recovered = ( df_recovered_raw[df_recovered_raw.Kommune == kommune] .transpose() .reset_index() .drop([0]) ) df_recovered.columns = ["date", "recovered"] df_recovered["recovered_data_available"] = ~df_recovered["recovered"].isna() df_recovered.fillna(method="ffill", inplace=True) df_recovered["date"] = pd.to_datetime(df_recovered["date"]) df_recovered["recovered_delta"] = df_recovered["recovered"].diff() df_recovered["recovered_change_rate"] = df_recovered["recovered"].pct_change() df_deaths_raw = pd.read_csv("data/time_series/time_series_covid-19_nrw_deaths.csv") df_deaths = ( df_deaths_raw[df_deaths_raw.Kommune == kommune] .transpose() .reset_index() .drop([0]) ) df_deaths.columns = ["date", "deaths"] df_deaths["deaths_data_available"] = ~df_deaths["deaths"].isna() df_deaths.fillna(method="ffill", inplace=True) df_deaths["date"] = pd.to_datetime(df_deaths["date"]) df_deaths["deaths_delta"] = df_deaths["deaths"].diff() df_deaths["deaths_change_rate"] = df_deaths["deaths"].pct_change() dfs = [df_confirmed, df_recovered, df_deaths] df = reduce(lambda left, right: pd.merge(left, right, on="date"), dfs) df["active"] = df["confirmed"] - df["recovered"] - df["deaths"] df["active_without_new"] = ( df["confirmed"] - df["recovered"] - df["deaths"] - df["confirmed_new"] ) df["active_delta"] = df_deaths["deaths"].diff() df["active_change_rate"] = df_deaths["deaths"].pct_change() df.fillna(value=0, inplace=True) return df def plot(kommune): def plot_label(df, ax): for index, row in df.iterrows(): if row["date"] >= dt.strptime("2020-03-13", "%Y-%m-%d"): if not np.isnan(row["confirmed_new"]): text = "%.0f" % row["confirmed_new"] ax.text( index, df["recovered"].loc[index] + df["active"].loc[index] + df["deaths"].loc[index] + 3, text, horizontalalignment="center", fontsize=10, color="#000000", ) for index, row in df.iterrows(): if row["date"] >= dt.strptime("2020-03-13", "%Y-%m-%d"): text = "%.0f" % row["active_without_new"] ax.text( index, df["recovered"].loc[index] + df["active"].loc[index] / 2, text, horizontalalignment="center", fontsize=10, color="#FFFFFF", ) for index, row in df.iterrows(): if row["date"] >= dt.strptime("2020-03-16", "%Y-%m-%d"): text = int(row["recovered"]) ax.text( index, df["recovered"].loc[index] / 2 + 3.0, text, horizontalalignment="center", fontsize=10, color="#FFFFFF", ) for index, row in df.iterrows(): if row["date"] >= dt.strptime("2020-03-26", "%Y-%m-%d"): text = int(row["deaths"]) ax.text( index, df["deaths"].loc[index] + 3.0, text, horizontalalignment="center", fontsize=10, color="#FFFFFF", ) def plot_doubled_since(df, ax): idx_last_entry = df.index.max() has_doubled = df["confirmed"] <= max(df["confirmed"] / 2) if has_doubled.any(): idx_doubled_since = df[has_doubled].index.max() last_entry_date = df.loc[idx_last_entry]["date"] doubled_since_date = df.loc[idx_doubled_since]["date"] doubled_since_in_days = (last_entry_date - doubled_since_date).days - 1 ax.hlines( max(df["confirmed"]), idx_doubled_since, idx_last_entry, linestyles="dashed", lw=1, color=COLOR_CONFIRMED_NEW, ) ax.vlines( idx_doubled_since, max(df["confirmed"]), max(df["confirmed"] / 2), linestyles="dashed", lw=1, color=COLOR_CONFIRMED_NEW, ) ax.annotate( f"Letzte Verdoppelung aller bestätigten Fälle: \n{doubled_since_in_days} Tage", (idx_doubled_since + 0.5, max(df["confirmed"] / 1.1)), ) def plot_axis(ax): ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.set_xlabel("") ax.set_ylabel("Anzahl an Fällen", fontsize=12) ax.yaxis.set_label_position("right") x_labels = df["date"].dt.strftime("%d.%m.") ax.set_xticklabels(labels=x_labels, rotation=45, ha="right") ax.set(yticks=np.arange(0, max(df["confirmed"]) + 50, step=100)) ax.yaxis.tick_right() def plot_legend(ax): handles, labels = ax.get_legend_handles_labels() ax.legend( reversed(handles), reversed(["Verstorbene", "Genesene", "Bisher Erkrankte", "Neuinfektionen"]), frameon=False, ) def plot_bar(df): return df.plot.bar( x="date", y=["deaths", "recovered", "active_without_new", "confirmed_new"], stacked=True, color=[COLOR_DEATHS, COLOR_RECOVERED, COLOR_ACTIVE, COLOR_CONFIRMED_NEW], figsize=(20, 10), width=0.8, fontsize=13, linewidth=0 ) df = load(kommune) ax = plot_bar(df) bars = ax.patches patterns = (' ', ' ', ' ','//') edgecolors = (COLOR_DEATHS, COLOR_RECOVERED, COLOR_ACTIVE, HATCH_COLOR) hatches = [p for p in patterns for i in range(len(df))] hatches_colors = [c for c in edgecolors for i in range(len(df))] for bar, hatch, hatch_color in zip(bars, hatches, hatches_colors): plot_label(df, ax) plot_axis(ax) plot_legend(ax) plot_doubled_since(df, ax) return ax.get_figure() def save(): def get_kommunen(): df_raw = pd.read_csv("data/time_series/time_series_covid-19_nrw_confirmed.csv") return df_raw["Kommune"].unique() def get_short_name(kommune): return str.split(kommune)[1].lower() def get_image_name(short_name): return "images/covid-19-" + short_name + ".svg" def save_plotted_svg(kommune, image_name): fig = plot(kommune) fig.savefig(image_name, bbox_inches="tight") def generate_html(short_name, image_name): f = open("diff_plot_" + short_name + "_temp.html", "w") f.write('<div style="text-align: center;">') f.write("<img src='" + image_name + "'/>") f.write("</div>") f.close() kommunen = get_kommunen() for kommune in kommunen: short_name = get_short_name(kommune) image_name = get_image_name(short_name) save_plotted_svg(kommune, image_name) generate_html(short_name, image_name) if __name__ == "__main__": save()
true
true
1c3bf9262057662eec051c8daa4b8632d602656a
5,537
py
Python
cms/blogs/tests.py
dragon-dxw/nhs-ei.website
6b513040f2cbf5c4359dc0f9431712d74bc6aa02
[ "MIT" ]
null
null
null
cms/blogs/tests.py
dragon-dxw/nhs-ei.website
6b513040f2cbf5c4359dc0f9431712d74bc6aa02
[ "MIT" ]
35
2021-06-25T10:22:48.000Z
2022-03-30T11:26:22.000Z
cms/blogs/tests.py
dxw/nhs-ei.website
6b513040f2cbf5c4359dc0f9431712d74bc6aa02
[ "MIT" ]
null
null
null
from bs4 import BeautifulSoup from cms.blogs.models import BlogIndexPage from django.test import TestCase class TestBlogIndexPage(TestCase): # or load whichever file you piped it to fixtures = ["fixtures/testdata.json"] """below was changed""" def test_first_heading(self): response = self.client.get("/blog-index-page/") soup = BeautifulSoup(response.content, "html.parser") heading = soup.select_one("main h1") self.assertEqual(heading.text, "Blog Index Page") def test_first_paragrpah(self): response = self.client.get("/blog-index-page/") soup = BeautifulSoup(response.content, "html.parser") heading = soup.select_one("main p") self.assertEqual(heading.text, "Blog Index Content") def test_blog_list(self): response = self.client.get("/blog-index-page/") soup = BeautifulSoup(response.content, "html.parser") blog_newest = soup.select_one( "main .nhsuk-width-container:nth-child(3) .nhsuk-panel:nth-of-type(1)" ) # heading self.assertEqual(blog_newest.select_one("h2").text.strip(), "Blog Post Two") self.assertEqual( blog_newest.select_one("h2 a")["href"], "/blog-index-page/blog-post-two/" ) # paragraph self.assertGreater( len(blog_newest.select_one("div.nhsuk-u-margin-bottom-3").text.strip()), 0 ) # dates self.assertIn( blog_newest.select_one("p.nhsuk-body-s").text.strip()[:23], "Published: 04 Feb 2021 -", ) # topics self.assertEqual( blog_newest.select_one("p.nhsuk-body-s a:nth-of-type(1)").text.strip(), "Category Two", ) self.assertEqual( blog_newest.select_one("p.nhsuk-body-s a:nth-of-type(1)")["href"], "?category=2", ) blog_oldest = soup.select_one( "main .nhsuk-width-container:nth-child(3) .nhsuk-panel:nth-of-type(2)" ) # heading self.assertEqual(blog_oldest.select_one("h2").text.strip(), "Blog Post One") self.assertEqual( blog_oldest.select_one("h2 a")["href"], "/blog-index-page/blog-post-one/" ) # paragraph self.assertGreater( len(blog_oldest.select_one("div.nhsuk-u-margin-bottom-3").text.strip()), 0 ) # dates self.assertIn( blog_oldest.select_one("p.nhsuk-body-s").text.strip()[:23], "Published: 04 Feb 2021 -", ) # topics self.assertEqual( blog_oldest.select_one("p.nhsuk-body-s a:nth-of-type(1)").text.strip(), "Category One", ) self.assertEqual( blog_oldest.select_one("p.nhsuk-body-s a:nth-of-type(1)")["href"], "?category=1", ) def test_get_latest_blogs(self): index_page = BlogIndexPage.objects.get(slug="blog-index-page") latest = index_page.get_latest_blogs(2) self.assertEqual(latest.count(), 2) def test_get_context(self): response = self.client.get("/blog-index-page/") context = response.context self.assertEqual(context["title"], "Blog Index Page") self.assertEqual(len(context["blogs"]), 2) self.assertEqual(len(context["categories"]), 2, context["categories"]) class TestBlog(TestCase): # or load whichever file you piped it to fixtures = ["fixtures/testdata.json"] # theres a couple of pages worth testing def test_oldest_blog(self): # this page is using a PDF document link response = self.client.get("/blog-index-page/blog-post-one/") soup = BeautifulSoup(response.content, "html.parser") # page title title = soup.select_one("main h1").text.strip() self.assertEqual(title, "Blog Post One") # page content just the first p tag content = soup.select_one("main p").text.strip() self.assertEqual(content, "Blog Post Content") # review date # better to test these actual date objects as unittest I think, one for later date_container = soup.select_one("main .nhsuk-review-date") self.assertIn(date_container.text.strip()[:20], "Published: 04 Feb 2021") # # taxonomy links category_1 = soup.select_one("main a:nth-of-type(1)") self.assertEqual(category_1["href"], "/blog-index-page/?category=1") self.assertEqual(category_1.text.strip(), "Category One") def test_newest_blog(self): # this page is using a PDF document link response = self.client.get("/blog-index-page/blog-post-two/") soup = BeautifulSoup(response.content, "html.parser") # page title title = soup.select_one("main h1").text.strip() self.assertEqual(title, "Blog Post Two") # page content just the first p tag content = soup.select_one("main p").text.strip() self.assertEqual(content, "Blog Post Two") # review date # better to test these actual date objects as unittest I think, one for later date_container = soup.select_one("main .nhsuk-review-date") self.assertIn(date_container.text.strip()[:20], "Published: 04 Feb 2021") # # taxonomy links category_1 = soup.select_one("main a:nth-of-type(1)") self.assertEqual(category_1["href"], "/blog-index-page/?category=2") self.assertEqual(category_1.text.strip(), "Category Two")
34.391304
86
0.613509
from bs4 import BeautifulSoup from cms.blogs.models import BlogIndexPage from django.test import TestCase class TestBlogIndexPage(TestCase): fixtures = ["fixtures/testdata.json"] def test_first_heading(self): response = self.client.get("/blog-index-page/") soup = BeautifulSoup(response.content, "html.parser") heading = soup.select_one("main h1") self.assertEqual(heading.text, "Blog Index Page") def test_first_paragrpah(self): response = self.client.get("/blog-index-page/") soup = BeautifulSoup(response.content, "html.parser") heading = soup.select_one("main p") self.assertEqual(heading.text, "Blog Index Content") def test_blog_list(self): response = self.client.get("/blog-index-page/") soup = BeautifulSoup(response.content, "html.parser") blog_newest = soup.select_one( "main .nhsuk-width-container:nth-child(3) .nhsuk-panel:nth-of-type(1)" ) self.assertEqual(blog_newest.select_one("h2").text.strip(), "Blog Post Two") self.assertEqual( blog_newest.select_one("h2 a")["href"], "/blog-index-page/blog-post-two/" ) self.assertGreater( len(blog_newest.select_one("div.nhsuk-u-margin-bottom-3").text.strip()), 0 ) self.assertIn( blog_newest.select_one("p.nhsuk-body-s").text.strip()[:23], "Published: 04 Feb 2021 -", ) self.assertEqual( blog_newest.select_one("p.nhsuk-body-s a:nth-of-type(1)").text.strip(), "Category Two", ) self.assertEqual( blog_newest.select_one("p.nhsuk-body-s a:nth-of-type(1)")["href"], "?category=2", ) blog_oldest = soup.select_one( "main .nhsuk-width-container:nth-child(3) .nhsuk-panel:nth-of-type(2)" ) self.assertEqual(blog_oldest.select_one("h2").text.strip(), "Blog Post One") self.assertEqual( blog_oldest.select_one("h2 a")["href"], "/blog-index-page/blog-post-one/" ) self.assertGreater( len(blog_oldest.select_one("div.nhsuk-u-margin-bottom-3").text.strip()), 0 ) self.assertIn( blog_oldest.select_one("p.nhsuk-body-s").text.strip()[:23], "Published: 04 Feb 2021 -", ) self.assertEqual( blog_oldest.select_one("p.nhsuk-body-s a:nth-of-type(1)").text.strip(), "Category One", ) self.assertEqual( blog_oldest.select_one("p.nhsuk-body-s a:nth-of-type(1)")["href"], "?category=1", ) def test_get_latest_blogs(self): index_page = BlogIndexPage.objects.get(slug="blog-index-page") latest = index_page.get_latest_blogs(2) self.assertEqual(latest.count(), 2) def test_get_context(self): response = self.client.get("/blog-index-page/") context = response.context self.assertEqual(context["title"], "Blog Index Page") self.assertEqual(len(context["blogs"]), 2) self.assertEqual(len(context["categories"]), 2, context["categories"]) class TestBlog(TestCase): fixtures = ["fixtures/testdata.json"] def test_oldest_blog(self): response = self.client.get("/blog-index-page/blog-post-one/") soup = BeautifulSoup(response.content, "html.parser") title = soup.select_one("main h1").text.strip() self.assertEqual(title, "Blog Post One") content = soup.select_one("main p").text.strip() self.assertEqual(content, "Blog Post Content") date_container = soup.select_one("main .nhsuk-review-date") self.assertIn(date_container.text.strip()[:20], "Published: 04 Feb 2021") y_1 = soup.select_one("main a:nth-of-type(1)") self.assertEqual(category_1["href"], "/blog-index-page/?category=1") self.assertEqual(category_1.text.strip(), "Category One") def test_newest_blog(self): response = self.client.get("/blog-index-page/blog-post-two/") soup = BeautifulSoup(response.content, "html.parser") title = soup.select_one("main h1").text.strip() self.assertEqual(title, "Blog Post Two") content = soup.select_one("main p").text.strip() self.assertEqual(content, "Blog Post Two") date_container = soup.select_one("main .nhsuk-review-date") self.assertIn(date_container.text.strip()[:20], "Published: 04 Feb 2021") y_1 = soup.select_one("main a:nth-of-type(1)") self.assertEqual(category_1["href"], "/blog-index-page/?category=2") self.assertEqual(category_1.text.strip(), "Category Two")
true
true
1c3bfa1e34f27db25293ec754957ea98940d5284
10,638
py
Python
heat/tests/engine/service/test_stack_events.py
itachaaa/heat
a73fa991dbd93fbcfd93c3d19e74f1e8b5a0b870
[ "Apache-2.0" ]
1
2018-07-04T07:59:26.000Z
2018-07-04T07:59:26.000Z
heat/tests/engine/service/test_stack_events.py
ljzjohnson/heat
9e463f4af77513980b1fd215d5d2ad3bf7b979f9
[ "Apache-2.0" ]
null
null
null
heat/tests/engine/service/test_stack_events.py
ljzjohnson/heat
9e463f4af77513980b1fd215d5d2ad3bf7b979f9
[ "Apache-2.0" ]
null
null
null
# # 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 mock from heat.engine import resource as res from heat.engine.resources.aws.ec2 import instance as instances from heat.engine import service from heat.engine import stack as parser from heat.objects import event as event_object from heat.objects import stack as stack_object from heat.tests import common from heat.tests.engine import tools from heat.tests import generic_resource as generic_rsrc from heat.tests import utils class StackEventTest(common.HeatTestCase): def setUp(self): super(StackEventTest, self).setUp() self.ctx = utils.dummy_context(tenant_id='stack_event_test_tenant') self.eng = service.EngineService('a-host', 'a-topic') self.eng.thread_group_mgr = service.ThreadGroupManager() @tools.stack_context('service_event_list_test_stack') @mock.patch.object(service.EngineService, '_get_stack') def test_event_list(self, mock_get): mock_get.return_value = stack_object.Stack.get_by_id(self.ctx, self.stack.id) events = self.eng.list_events(self.ctx, self.stack.identifier()) self.assertEqual(4, len(events)) for ev in events: self.assertNotIn('root_stack_id', ev) self.assertIn('event_identity', ev) self.assertIsInstance(ev['event_identity'], dict) self.assertTrue(ev['event_identity']['path'].rsplit('/', 1)[1]) self.assertIn('resource_name', ev) self.assertIn(ev['resource_name'], ('service_event_list_test_stack', 'WebServer')) self.assertIn('physical_resource_id', ev) self.assertEqual('CREATE', ev['resource_action']) self.assertIn(ev['resource_status'], ('IN_PROGRESS', 'COMPLETE')) self.assertIn('resource_status_reason', ev) self.assertIn(ev['resource_status_reason'], ('state changed', 'Stack CREATE started', 'Stack CREATE completed successfully')) self.assertIn('resource_type', ev) self.assertIn(ev['resource_type'], ('AWS::EC2::Instance', 'OS::Heat::Stack')) self.assertIn('stack_identity', ev) self.assertIn('stack_name', ev) self.assertEqual(self.stack.name, ev['stack_name']) self.assertIn('event_time', ev) mock_get.assert_called_once_with(self.ctx, self.stack.identifier(), show_deleted=True) @tools.stack_context('service_event_list_test_stack') @mock.patch.object(service.EngineService, '_get_stack') def test_event_list_nested_depth(self, mock_get): mock_get.return_value = stack_object.Stack.get_by_id(self.ctx, self.stack.id) events = self.eng.list_events(self.ctx, self.stack.identifier(), nested_depth=1) self.assertEqual(4, len(events)) for ev in events: self.assertIn('root_stack_id', ev) mock_get.assert_called_once_with(self.ctx, self.stack.identifier(), show_deleted=True) @tools.stack_context('service_event_list_deleted_resource') @mock.patch.object(instances.Instance, 'handle_delete') def test_event_list_deleted_resource(self, mock_delete): mock_delete.return_value = None res._register_class('GenericResourceType', generic_rsrc.GenericResource) thread = mock.Mock() thread.link = mock.Mock(return_value=None) def run(stack_id, func, *args, **kwargs): func(*args) return thread self.eng.thread_group_mgr.start = run new_tmpl = {'HeatTemplateFormatVersion': '2012-12-12', 'Resources': {'AResource': {'Type': 'GenericResourceType'}}} result = self.eng.update_stack(self.ctx, self.stack.identifier(), new_tmpl, None, None, {}) # The self.stack reference needs to be updated. Since the underlying # stack is updated in update_stack, the original reference is now # pointing to an orphaned stack object. self.stack = parser.Stack.load(self.ctx, stack_id=result['stack_id']) self.assertEqual(result, self.stack.identifier()) self.assertIsInstance(result, dict) self.assertTrue(result['stack_id']) events = self.eng.list_events(self.ctx, self.stack.identifier()) self.assertEqual(10, len(events)) for ev in events: self.assertIn('event_identity', ev) self.assertIsInstance(ev['event_identity'], dict) self.assertTrue(ev['event_identity']['path'].rsplit('/', 1)[1]) self.assertIn('resource_name', ev) self.assertIn('physical_resource_id', ev) self.assertIn('resource_status_reason', ev) self.assertIn(ev['resource_action'], ('CREATE', 'UPDATE', 'DELETE')) self.assertIn(ev['resource_status'], ('IN_PROGRESS', 'COMPLETE')) self.assertIn('resource_type', ev) self.assertIn(ev['resource_type'], ('AWS::EC2::Instance', 'GenericResourceType', 'OS::Heat::Stack')) self.assertIn('stack_identity', ev) self.assertIn('stack_name', ev) self.assertEqual(self.stack.name, ev['stack_name']) self.assertIn('event_time', ev) mock_delete.assert_called_once_with() expected = [ mock.call(mock.ANY), mock.call(mock.ANY, self.stack.id, mock.ANY) ] self.assertEqual(expected, thread.link.call_args_list) @tools.stack_context('service_event_list_by_tenant') def test_event_list_by_tenant(self): events = self.eng.list_events(self.ctx, None) self.assertEqual(4, len(events)) for ev in events: self.assertIn('event_identity', ev) self.assertIsInstance(ev['event_identity'], dict) self.assertTrue(ev['event_identity']['path'].rsplit('/', 1)[1]) self.assertIn('resource_name', ev) self.assertIn(ev['resource_name'], ('WebServer', 'service_event_list_by_tenant')) self.assertIn('physical_resource_id', ev) self.assertEqual('CREATE', ev['resource_action']) self.assertIn(ev['resource_status'], ('IN_PROGRESS', 'COMPLETE')) self.assertIn('resource_status_reason', ev) self.assertIn(ev['resource_status_reason'], ('state changed', 'Stack CREATE started', 'Stack CREATE completed successfully')) self.assertIn('resource_type', ev) self.assertIn(ev['resource_type'], ('AWS::EC2::Instance', 'OS::Heat::Stack')) self.assertIn('stack_identity', ev) self.assertIn('stack_name', ev) self.assertEqual(self.stack.name, ev['stack_name']) self.assertIn('event_time', ev) @mock.patch.object(event_object.Event, 'get_all_by_stack') @mock.patch.object(service.EngineService, '_get_stack') def test_event_list_with_marker_and_filters(self, mock_get, mock_get_all): limit = object() marker = object() sort_keys = object() sort_dir = object() filters = {} mock_get.return_value = mock.Mock(id=1) self.eng.list_events(self.ctx, 1, limit=limit, marker=marker, sort_keys=sort_keys, sort_dir=sort_dir, filters=filters) mock_get_all.assert_called_once_with(self.ctx, 1, limit=limit, sort_keys=sort_keys, marker=marker, sort_dir=sort_dir, filters=filters) @mock.patch.object(event_object.Event, 'get_all_by_tenant') def test_tenant_events_list_with_marker_and_filters(self, mock_get_all): limit = object() marker = object() sort_keys = object() sort_dir = object() filters = {} self.eng.list_events(self.ctx, None, limit=limit, marker=marker, sort_keys=sort_keys, sort_dir=sort_dir, filters=filters) mock_get_all.assert_called_once_with(self.ctx, limit=limit, sort_keys=sort_keys, marker=marker, sort_dir=sort_dir, filters=filters) @tools.stack_context('service_event_list_single_event') @mock.patch.object(service.EngineService, '_get_stack') def test_event_list_single_has_rsrc_prop_data(self, mock_get): mock_get.return_value = stack_object.Stack.get_by_id(self.ctx, self.stack.id) events = self.eng.list_events(self.ctx, self.stack.identifier()) self.assertEqual(4, len(events)) for ev in events: self.assertNotIn('resource_properties', ev) event_objs = event_object.Event.get_all_by_stack( self.ctx, self.stack.id) for i in range(2): event_uuid = event_objs[i]['uuid'] events = self.eng.list_events(self.ctx, self.stack.identifier(), filters={'uuid': event_uuid}) self.assertEqual(1, len(events)) self.assertIn('resource_properties', events[0]) if i > 0: self.assertEqual(4, len(events[0]['resource_properties']))
41.88189
78
0.586482
import mock from heat.engine import resource as res from heat.engine.resources.aws.ec2 import instance as instances from heat.engine import service from heat.engine import stack as parser from heat.objects import event as event_object from heat.objects import stack as stack_object from heat.tests import common from heat.tests.engine import tools from heat.tests import generic_resource as generic_rsrc from heat.tests import utils class StackEventTest(common.HeatTestCase): def setUp(self): super(StackEventTest, self).setUp() self.ctx = utils.dummy_context(tenant_id='stack_event_test_tenant') self.eng = service.EngineService('a-host', 'a-topic') self.eng.thread_group_mgr = service.ThreadGroupManager() @tools.stack_context('service_event_list_test_stack') @mock.patch.object(service.EngineService, '_get_stack') def test_event_list(self, mock_get): mock_get.return_value = stack_object.Stack.get_by_id(self.ctx, self.stack.id) events = self.eng.list_events(self.ctx, self.stack.identifier()) self.assertEqual(4, len(events)) for ev in events: self.assertNotIn('root_stack_id', ev) self.assertIn('event_identity', ev) self.assertIsInstance(ev['event_identity'], dict) self.assertTrue(ev['event_identity']['path'].rsplit('/', 1)[1]) self.assertIn('resource_name', ev) self.assertIn(ev['resource_name'], ('service_event_list_test_stack', 'WebServer')) self.assertIn('physical_resource_id', ev) self.assertEqual('CREATE', ev['resource_action']) self.assertIn(ev['resource_status'], ('IN_PROGRESS', 'COMPLETE')) self.assertIn('resource_status_reason', ev) self.assertIn(ev['resource_status_reason'], ('state changed', 'Stack CREATE started', 'Stack CREATE completed successfully')) self.assertIn('resource_type', ev) self.assertIn(ev['resource_type'], ('AWS::EC2::Instance', 'OS::Heat::Stack')) self.assertIn('stack_identity', ev) self.assertIn('stack_name', ev) self.assertEqual(self.stack.name, ev['stack_name']) self.assertIn('event_time', ev) mock_get.assert_called_once_with(self.ctx, self.stack.identifier(), show_deleted=True) @tools.stack_context('service_event_list_test_stack') @mock.patch.object(service.EngineService, '_get_stack') def test_event_list_nested_depth(self, mock_get): mock_get.return_value = stack_object.Stack.get_by_id(self.ctx, self.stack.id) events = self.eng.list_events(self.ctx, self.stack.identifier(), nested_depth=1) self.assertEqual(4, len(events)) for ev in events: self.assertIn('root_stack_id', ev) mock_get.assert_called_once_with(self.ctx, self.stack.identifier(), show_deleted=True) @tools.stack_context('service_event_list_deleted_resource') @mock.patch.object(instances.Instance, 'handle_delete') def test_event_list_deleted_resource(self, mock_delete): mock_delete.return_value = None res._register_class('GenericResourceType', generic_rsrc.GenericResource) thread = mock.Mock() thread.link = mock.Mock(return_value=None) def run(stack_id, func, *args, **kwargs): func(*args) return thread self.eng.thread_group_mgr.start = run new_tmpl = {'HeatTemplateFormatVersion': '2012-12-12', 'Resources': {'AResource': {'Type': 'GenericResourceType'}}} result = self.eng.update_stack(self.ctx, self.stack.identifier(), new_tmpl, None, None, {}) self.stack = parser.Stack.load(self.ctx, stack_id=result['stack_id']) self.assertEqual(result, self.stack.identifier()) self.assertIsInstance(result, dict) self.assertTrue(result['stack_id']) events = self.eng.list_events(self.ctx, self.stack.identifier()) self.assertEqual(10, len(events)) for ev in events: self.assertIn('event_identity', ev) self.assertIsInstance(ev['event_identity'], dict) self.assertTrue(ev['event_identity']['path'].rsplit('/', 1)[1]) self.assertIn('resource_name', ev) self.assertIn('physical_resource_id', ev) self.assertIn('resource_status_reason', ev) self.assertIn(ev['resource_action'], ('CREATE', 'UPDATE', 'DELETE')) self.assertIn(ev['resource_status'], ('IN_PROGRESS', 'COMPLETE')) self.assertIn('resource_type', ev) self.assertIn(ev['resource_type'], ('AWS::EC2::Instance', 'GenericResourceType', 'OS::Heat::Stack')) self.assertIn('stack_identity', ev) self.assertIn('stack_name', ev) self.assertEqual(self.stack.name, ev['stack_name']) self.assertIn('event_time', ev) mock_delete.assert_called_once_with() expected = [ mock.call(mock.ANY), mock.call(mock.ANY, self.stack.id, mock.ANY) ] self.assertEqual(expected, thread.link.call_args_list) @tools.stack_context('service_event_list_by_tenant') def test_event_list_by_tenant(self): events = self.eng.list_events(self.ctx, None) self.assertEqual(4, len(events)) for ev in events: self.assertIn('event_identity', ev) self.assertIsInstance(ev['event_identity'], dict) self.assertTrue(ev['event_identity']['path'].rsplit('/', 1)[1]) self.assertIn('resource_name', ev) self.assertIn(ev['resource_name'], ('WebServer', 'service_event_list_by_tenant')) self.assertIn('physical_resource_id', ev) self.assertEqual('CREATE', ev['resource_action']) self.assertIn(ev['resource_status'], ('IN_PROGRESS', 'COMPLETE')) self.assertIn('resource_status_reason', ev) self.assertIn(ev['resource_status_reason'], ('state changed', 'Stack CREATE started', 'Stack CREATE completed successfully')) self.assertIn('resource_type', ev) self.assertIn(ev['resource_type'], ('AWS::EC2::Instance', 'OS::Heat::Stack')) self.assertIn('stack_identity', ev) self.assertIn('stack_name', ev) self.assertEqual(self.stack.name, ev['stack_name']) self.assertIn('event_time', ev) @mock.patch.object(event_object.Event, 'get_all_by_stack') @mock.patch.object(service.EngineService, '_get_stack') def test_event_list_with_marker_and_filters(self, mock_get, mock_get_all): limit = object() marker = object() sort_keys = object() sort_dir = object() filters = {} mock_get.return_value = mock.Mock(id=1) self.eng.list_events(self.ctx, 1, limit=limit, marker=marker, sort_keys=sort_keys, sort_dir=sort_dir, filters=filters) mock_get_all.assert_called_once_with(self.ctx, 1, limit=limit, sort_keys=sort_keys, marker=marker, sort_dir=sort_dir, filters=filters) @mock.patch.object(event_object.Event, 'get_all_by_tenant') def test_tenant_events_list_with_marker_and_filters(self, mock_get_all): limit = object() marker = object() sort_keys = object() sort_dir = object() filters = {} self.eng.list_events(self.ctx, None, limit=limit, marker=marker, sort_keys=sort_keys, sort_dir=sort_dir, filters=filters) mock_get_all.assert_called_once_with(self.ctx, limit=limit, sort_keys=sort_keys, marker=marker, sort_dir=sort_dir, filters=filters) @tools.stack_context('service_event_list_single_event') @mock.patch.object(service.EngineService, '_get_stack') def test_event_list_single_has_rsrc_prop_data(self, mock_get): mock_get.return_value = stack_object.Stack.get_by_id(self.ctx, self.stack.id) events = self.eng.list_events(self.ctx, self.stack.identifier()) self.assertEqual(4, len(events)) for ev in events: self.assertNotIn('resource_properties', ev) event_objs = event_object.Event.get_all_by_stack( self.ctx, self.stack.id) for i in range(2): event_uuid = event_objs[i]['uuid'] events = self.eng.list_events(self.ctx, self.stack.identifier(), filters={'uuid': event_uuid}) self.assertEqual(1, len(events)) self.assertIn('resource_properties', events[0]) if i > 0: self.assertEqual(4, len(events[0]['resource_properties']))
true
true
1c3bfa42909e72f3da5ec15ede1344602925a55d
118
py
Python
ELAB02/02-08.py
tawanchaiii/01204111_63
edf1174f287f5174d93729d9b5c940c74d3b6553
[ "WTFPL" ]
null
null
null
ELAB02/02-08.py
tawanchaiii/01204111_63
edf1174f287f5174d93729d9b5c940c74d3b6553
[ "WTFPL" ]
null
null
null
ELAB02/02-08.py
tawanchaiii/01204111_63
edf1174f287f5174d93729d9b5c940c74d3b6553
[ "WTFPL" ]
null
null
null
x = int(input()) l = [1000,500,100,50,20,10,5,1] for i in range(8): print(f"{l[i]} => {x//l[i]}") x = x%l[i]
16.857143
32
0.466102
x = int(input()) l = [1000,500,100,50,20,10,5,1] for i in range(8): print(f"{l[i]} => {x//l[i]}") x = x%l[i]
true
true
1c3bfbe80ab567fdd06ee0a5a2bf27ffc624e805
6,419
py
Python
lisa/tools/fio.py
tyhicks/lisa
50d07cbd13e4e777eaa211b01387721fe2d2094f
[ "MIT" ]
65
2020-12-15T13:42:29.000Z
2022-03-03T13:14:16.000Z
lisa/tools/fio.py
acidburn0zzz/lisa
3934d0546592d3ff71bc3e2c4aab5d4bc646a3b9
[ "MIT" ]
236
2020-11-24T18:28:26.000Z
2022-03-30T19:19:25.000Z
lisa/tools/fio.py
acidburn0zzz/lisa
3934d0546592d3ff71bc3e2c4aab5d4bc646a3b9
[ "MIT" ]
52
2020-12-08T17:40:46.000Z
2022-03-31T18:24:14.000Z
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import re from decimal import Decimal from enum import Enum from typing import Any, Dict, List, cast from lisa.executable import Tool from lisa.notifier import DiskPerformanceMessage from lisa.operating_system import Debian, Posix, Redhat, Suse from lisa.util import LisaException, dict_to_fields from .git import Git class FIOResult: qdepth: int = 0 mode: str = "" iops: Decimal = Decimal(0) latency: Decimal = Decimal(0) iodepth: int = 0 FIOMODES = Enum( "FIOMODES", [ "randread", "randwrite", "read", "write", ], ) class Fio(Tool): fio_repo = "https://github.com/axboe/fio/" branch = "fio-3.29" # iteration21: (groupid=0, jobs=64): err= 0: pid=6157: Fri Dec 24 08:55:21 2021 # read: IOPS=3533k, BW=13.5GiB/s (14.5GB/s)(1617GiB/120003msec) # slat (nsec): min=1800, max=30492k, avg=11778.91, stdev=18599.91 # clat (nsec): min=500, max=93368k, avg=130105.42, stdev=57833.37 # lat (usec): min=18, max=93375, avg=142.51, stdev=59.57 # get IOPS and total delay _result_pattern = re.compile( r"([\w\W]*?)IOPS=(?P<iops>.+?)," r"([\w\W]*?).* lat.*avg=(?P<latency>.+?),", re.M, ) @property def command(self) -> str: return "fio" @property def can_install(self) -> bool: return True def install(self) -> bool: posix_os: Posix = cast(Posix, self.node.os) posix_os.install_packages("fio") if not self._check_exists(): self._install_from_src() return self._check_exists() def launch( self, name: str, filename: str, mode: str, iodepth: int, numjob: int, time: int = 120, block_size: str = "4K", size_gb: int = 0, direct: bool = True, gtod_reduce: bool = False, ioengine: str = "libaio", group_reporting: bool = True, overwrite: bool = False, ) -> FIOResult: cmd = ( f"--ioengine={ioengine} --bs={block_size} --filename={filename} " f"--readwrite={mode} --runtime={time} --iodepth={iodepth} " f"--numjob={numjob} --name={name}" ) if direct: cmd += " --direct=1" if gtod_reduce: cmd += " --gtod_reduce=1" if size_gb: cmd += f" --size={size_gb}G" if group_reporting: cmd += " --group_reporting" if overwrite: cmd += " --overwrite=1" result = self.run( cmd, force_run=True, sudo=True, expected_exit_code=0, expected_exit_code_failure_message=f"fail to run {cmd}", ) matched_results = self._result_pattern.match(result.stdout) assert matched_results, "not found matched iops and latency from fio results." iops = matched_results.group("iops") if iops.endswith("k"): iops_value = Decimal(iops[:-1]) * 1000 else: iops_value = Decimal(iops) latency = matched_results.group("latency") fio_result = FIOResult() fio_result.iops = iops_value fio_result.latency = Decimal(latency) fio_result.iodepth = iodepth fio_result.qdepth = iodepth * numjob fio_result.mode = mode return fio_result def create_performance_messages( self, fio_results_list: List[FIOResult] ) -> List[DiskPerformanceMessage]: fio_message: List[DiskPerformanceMessage] = [] mode_iops_latency: Dict[int, Dict[str, Any]] = {} for fio_result in fio_results_list: temp: Dict[str, Any] = {} if fio_result.qdepth in mode_iops_latency.keys(): temp = mode_iops_latency[fio_result.qdepth] temp[f"{fio_result.mode}_iops"] = fio_result.iops temp[f"{fio_result.mode}_lat_usec"] = fio_result.latency temp["iodepth"] = fio_result.iodepth temp["qdepth"] = fio_result.qdepth temp["numjob"] = int(fio_result.qdepth / fio_result.iodepth) mode_iops_latency[fio_result.qdepth] = temp for result in mode_iops_latency.values(): fio_result_message = DiskPerformanceMessage() fio_result_message = dict_to_fields(result, fio_result_message) fio_message.append(fio_result_message) return fio_message def _install_dep_packages(self) -> None: posix_os: Posix = cast(Posix, self.node.os) if isinstance(self.node.os, Redhat): package_list = [ "wget", "sysstat", "mdadm", "blktrace", "libaio", "bc", "libaio-devel", "gcc", "gcc-c++", "kernel-devel", "libpmem-devel", ] elif isinstance(self.node.os, Debian): package_list = [ "pciutils", "gawk", "mdadm", "wget", "sysstat", "blktrace", "bc", "libaio-dev", "zlib1g-dev", ] elif isinstance(self.node.os, Suse): package_list = ["wget", "mdadm", "blktrace", "libaio1", "sysstat", "bc"] else: raise LisaException( f"tool {self.command} can't be installed in distro {self.node.os.name}." ) for package in list(package_list): if posix_os.is_package_in_repo(package): posix_os.install_packages(package) def _install_from_src(self) -> bool: self._install_dep_packages() tool_path = self.get_tool_path() self.node.shell.mkdir(tool_path, exist_ok=True) git = self.node.tools[Git] git.clone(self.fio_repo, tool_path) code_path = tool_path.joinpath("fio") git.checkout( ref="refs/heads/master", cwd=code_path, checkout_branch=self.branch ) from .make import Make make = self.node.tools[Make] make.make_install(cwd=code_path) self.node.execute( "ln -s /usr/local/bin/fio /usr/bin/fio", sudo=True, cwd=code_path ).assert_exit_code() return self._check_exists()
32.75
88
0.5599
import re from decimal import Decimal from enum import Enum from typing import Any, Dict, List, cast from lisa.executable import Tool from lisa.notifier import DiskPerformanceMessage from lisa.operating_system import Debian, Posix, Redhat, Suse from lisa.util import LisaException, dict_to_fields from .git import Git class FIOResult: qdepth: int = 0 mode: str = "" iops: Decimal = Decimal(0) latency: Decimal = Decimal(0) iodepth: int = 0 FIOMODES = Enum( "FIOMODES", [ "randread", "randwrite", "read", "write", ], ) class Fio(Tool): fio_repo = "https://github.com/axboe/fio/" branch = "fio-3.29" _result_pattern = re.compile( r"([\w\W]*?)IOPS=(?P<iops>.+?)," r"([\w\W]*?).* lat.*avg=(?P<latency>.+?),", re.M, ) @property def command(self) -> str: return "fio" @property def can_install(self) -> bool: return True def install(self) -> bool: posix_os: Posix = cast(Posix, self.node.os) posix_os.install_packages("fio") if not self._check_exists(): self._install_from_src() return self._check_exists() def launch( self, name: str, filename: str, mode: str, iodepth: int, numjob: int, time: int = 120, block_size: str = "4K", size_gb: int = 0, direct: bool = True, gtod_reduce: bool = False, ioengine: str = "libaio", group_reporting: bool = True, overwrite: bool = False, ) -> FIOResult: cmd = ( f"--ioengine={ioengine} --bs={block_size} --filename={filename} " f"--readwrite={mode} --runtime={time} --iodepth={iodepth} " f"--numjob={numjob} --name={name}" ) if direct: cmd += " --direct=1" if gtod_reduce: cmd += " --gtod_reduce=1" if size_gb: cmd += f" --size={size_gb}G" if group_reporting: cmd += " --group_reporting" if overwrite: cmd += " --overwrite=1" result = self.run( cmd, force_run=True, sudo=True, expected_exit_code=0, expected_exit_code_failure_message=f"fail to run {cmd}", ) matched_results = self._result_pattern.match(result.stdout) assert matched_results, "not found matched iops and latency from fio results." iops = matched_results.group("iops") if iops.endswith("k"): iops_value = Decimal(iops[:-1]) * 1000 else: iops_value = Decimal(iops) latency = matched_results.group("latency") fio_result = FIOResult() fio_result.iops = iops_value fio_result.latency = Decimal(latency) fio_result.iodepth = iodepth fio_result.qdepth = iodepth * numjob fio_result.mode = mode return fio_result def create_performance_messages( self, fio_results_list: List[FIOResult] ) -> List[DiskPerformanceMessage]: fio_message: List[DiskPerformanceMessage] = [] mode_iops_latency: Dict[int, Dict[str, Any]] = {} for fio_result in fio_results_list: temp: Dict[str, Any] = {} if fio_result.qdepth in mode_iops_latency.keys(): temp = mode_iops_latency[fio_result.qdepth] temp[f"{fio_result.mode}_iops"] = fio_result.iops temp[f"{fio_result.mode}_lat_usec"] = fio_result.latency temp["iodepth"] = fio_result.iodepth temp["qdepth"] = fio_result.qdepth temp["numjob"] = int(fio_result.qdepth / fio_result.iodepth) mode_iops_latency[fio_result.qdepth] = temp for result in mode_iops_latency.values(): fio_result_message = DiskPerformanceMessage() fio_result_message = dict_to_fields(result, fio_result_message) fio_message.append(fio_result_message) return fio_message def _install_dep_packages(self) -> None: posix_os: Posix = cast(Posix, self.node.os) if isinstance(self.node.os, Redhat): package_list = [ "wget", "sysstat", "mdadm", "blktrace", "libaio", "bc", "libaio-devel", "gcc", "gcc-c++", "kernel-devel", "libpmem-devel", ] elif isinstance(self.node.os, Debian): package_list = [ "pciutils", "gawk", "mdadm", "wget", "sysstat", "blktrace", "bc", "libaio-dev", "zlib1g-dev", ] elif isinstance(self.node.os, Suse): package_list = ["wget", "mdadm", "blktrace", "libaio1", "sysstat", "bc"] else: raise LisaException( f"tool {self.command} can't be installed in distro {self.node.os.name}." ) for package in list(package_list): if posix_os.is_package_in_repo(package): posix_os.install_packages(package) def _install_from_src(self) -> bool: self._install_dep_packages() tool_path = self.get_tool_path() self.node.shell.mkdir(tool_path, exist_ok=True) git = self.node.tools[Git] git.clone(self.fio_repo, tool_path) code_path = tool_path.joinpath("fio") git.checkout( ref="refs/heads/master", cwd=code_path, checkout_branch=self.branch ) from .make import Make make = self.node.tools[Make] make.make_install(cwd=code_path) self.node.execute( "ln -s /usr/local/bin/fio /usr/bin/fio", sudo=True, cwd=code_path ).assert_exit_code() return self._check_exists()
true
true
1c3bff3506a1d1a7fef511425f2a717b3d9fe8df
1,434
py
Python
day05/main.py
Tessmore/advent-of-code-2021
eb54f77b00bf2540669499318633ab8dbf820420
[ "MIT" ]
null
null
null
day05/main.py
Tessmore/advent-of-code-2021
eb54f77b00bf2540669499318633ab8dbf820420
[ "MIT" ]
null
null
null
day05/main.py
Tessmore/advent-of-code-2021
eb54f77b00bf2540669499318633ab8dbf820420
[ "MIT" ]
null
null
null
class Line: nr = 0 x1 = 0 y1 = 0 x2 = 0 y2 = 0 slope = None def __init__(self, nr): self.nr = nr (x, y)= input().split("->") (x1, y1) = [int(i) for i in x.split(",")] (x2, y2) = [int(i) for i in y.split(",")] self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 if (x2 - x1) > 0: self.slope = (y2 - y1) / (x2 - x1) def is_vertical(self): return self.x1 == self.x2 def is_horizontal(self): return self.y1 == self.y2 def overlap(self, other): print("CHECKING") self.show() other.show() return 0 def show(self): print(self.x1, self.y1, "->", self.x2, self.y2) lines = [] nr = 0 while True: try: tmp = Line(nr) # Part 1: Only horizontal lines if tmp.is_horizontal() or tmp.is_vertical(): lines.append(tmp) nr += 1 except EOFError: break print("LEN", len(lines)) for a in lines: for b in lines: # Ignore comparing a line against itself # Ignore lines with a different slope (part 1) if a.nr <= b.nr: continue if a.is_vertical() and not b.is_vertical(): continue if a.is_horizontal() and not b.is_horizontal(): continue print(a.overlap(b)) print("---") # break
17.487805
55
0.480474
class Line: nr = 0 x1 = 0 y1 = 0 x2 = 0 y2 = 0 slope = None def __init__(self, nr): self.nr = nr (x, y)= input().split("->") (x1, y1) = [int(i) for i in x.split(",")] (x2, y2) = [int(i) for i in y.split(",")] self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 if (x2 - x1) > 0: self.slope = (y2 - y1) / (x2 - x1) def is_vertical(self): return self.x1 == self.x2 def is_horizontal(self): return self.y1 == self.y2 def overlap(self, other): print("CHECKING") self.show() other.show() return 0 def show(self): print(self.x1, self.y1, "->", self.x2, self.y2) lines = [] nr = 0 while True: try: tmp = Line(nr) if tmp.is_horizontal() or tmp.is_vertical(): lines.append(tmp) nr += 1 except EOFError: break print("LEN", len(lines)) for a in lines: for b in lines: if a.nr <= b.nr: continue if a.is_vertical() and not b.is_vertical(): continue if a.is_horizontal() and not b.is_horizontal(): continue print(a.overlap(b)) print("---")
true
true
1c3c002b09572fc0891b800d1b56631ea71d9d56
907
py
Python
rl-rc-car/vis.py
sourav-roni/rl-rc-car
4833ec6bf40b971caeec9bf0eb85a14138f91de4
[ "MIT" ]
47
2016-07-16T22:37:34.000Z
2021-04-13T12:10:04.000Z
rl-rc-car/vis.py
harvitronix/rl-rc-car
4833ec6bf40b971caeec9bf0eb85a14138f91de4
[ "MIT" ]
null
null
null
rl-rc-car/vis.py
harvitronix/rl-rc-car
4833ec6bf40b971caeec9bf0eb85a14138f91de4
[ "MIT" ]
23
2016-07-29T08:18:54.000Z
2022-03-14T20:45:18.000Z
""" Make a "matrix" plot of what the Robocar sees so we can see like it. """ import seaborn as sns import matplotlib.pyplot as plt import math sns.set() def visualize_polar(state): plt.clf() sonar = state[0][-1:] readings = state[0][:-1] r = [] t = [] for i, s in enumerate(readings): r.append(math.radians(i * 6)) t.append(s) ax = plt.subplot(111, polar=True) ax.set_theta_zero_location('W') ax.set_theta_direction(-1) ax.set_ylim(bottom=0, top=105) plt.plot(r, t) plt.scatter(math.radians(90), sonar, s=50) plt.draw() plt.pause(0.1) def visualize_sensors(state): # Clear. sns.plt.clf() # Make a 2d list. cols = [state[0]] # Plot it. sns.heatmap(data=cols, cmap="Blues_r", yticklabels=False) # Draw it. sns.plt.draw() # Add a pause because you're supposed to. sns.plt.pause(0.05)
18.14
68
0.601985
import seaborn as sns import matplotlib.pyplot as plt import math sns.set() def visualize_polar(state): plt.clf() sonar = state[0][-1:] readings = state[0][:-1] r = [] t = [] for i, s in enumerate(readings): r.append(math.radians(i * 6)) t.append(s) ax = plt.subplot(111, polar=True) ax.set_theta_zero_location('W') ax.set_theta_direction(-1) ax.set_ylim(bottom=0, top=105) plt.plot(r, t) plt.scatter(math.radians(90), sonar, s=50) plt.draw() plt.pause(0.1) def visualize_sensors(state): sns.plt.clf() cols = [state[0]] sns.heatmap(data=cols, cmap="Blues_r", yticklabels=False) sns.plt.draw() sns.plt.pause(0.05)
true
true
1c3c003897a1a6088e30c1caded7269e068585a5
5,489
py
Python
rpython/tool/error.py
nanjekyejoannah/pypy
e80079fe13c29eda7b2a6b4cd4557051f975a2d9
[ "Apache-2.0", "OpenSSL" ]
333
2015-08-08T18:03:38.000Z
2022-03-22T18:13:12.000Z
rpython/tool/error.py
nanjekyejoannah/pypy
e80079fe13c29eda7b2a6b4cd4557051f975a2d9
[ "Apache-2.0", "OpenSSL" ]
7
2020-02-16T16:49:05.000Z
2021-11-26T09:00:56.000Z
rpython/tool/error.py
nanjekyejoannah/pypy
e80079fe13c29eda7b2a6b4cd4557051f975a2d9
[ "Apache-2.0", "OpenSSL" ]
55
2015-08-16T02:41:30.000Z
2022-03-20T20:33:35.000Z
""" error handling features, just a way of displaying errors """ import sys import py from rpython.flowspace.model import Variable from rpython.rlib import jit SHOW_TRACEBACK = False SHOW_ANNOTATIONS = True SHOW_DEFAULT_LINES_OF_CODE = 0 def source_lines1(graph, block, operindex=None, offset=None, long=False, show_lines_of_code=SHOW_DEFAULT_LINES_OF_CODE): if block is not None: if block is graph.returnblock: return ['<return block>'] try: source = graph.source except AttributeError: return ['no source!'] else: graph_lines = source.split("\n") if offset is not None: linestart = offset2lineno(graph.func.__code__, offset) linerange = (linestart, linestart) here = None else: if block is None or not block.operations: return [] def toline(operindex): return offset2lineno(graph.func.__code__, block.operations[operindex].offset) if operindex is None: linerange = (toline(0), toline(-1)) if not long: return ['?'] here = None else: operline = toline(operindex) if long: linerange = (toline(0), toline(-1)) here = operline else: linerange = (operline, operline) here = None lines = ["Happened at file %s line %d" % (graph.filename, here or linerange[0]), ""] for n in range(max(0, linerange[0]-show_lines_of_code), min(linerange[1]+1+show_lines_of_code, len(graph_lines)+graph.startline)): if n == here: prefix = '==> ' else: prefix = ' ' lines.append(prefix + graph_lines[n-graph.startline]) lines.append("") return lines def source_lines(graph, *args, **kwds): lines = source_lines1(graph, *args, **kwds) return ['In %r:' % (graph,)] + lines def gather_error(annotator, graph, block, operindex): msg = [""] if operindex is not None: oper = block.operations[operindex] if oper.opname == 'simple_call': format_simple_call(annotator, oper, msg) else: oper = None msg.append(" %s\n" % str(oper)) msg += source_lines(graph, block, operindex, long=True) if oper is not None: if SHOW_ANNOTATIONS: msg += format_annotations(annotator, oper) msg += [''] return "\n".join(msg) def format_annotations(annotator, oper): msg = [] msg.append("Known variable annotations:") for arg in oper.args + [oper.result]: if isinstance(arg, Variable): try: msg.append(" " + str(arg) + " = " + str(annotator.binding(arg))) except KeyError: pass return msg def format_blocked_annotation_error(annotator, blocked_blocks): text = [] for block, (graph, index) in blocked_blocks.items(): text.append("Blocked block -- operation cannot succeed") text.append(gather_error(annotator, graph, block, index)) return '\n'.join(text) def format_simple_call(annotator, oper, msg): msg.append("Occurred processing the following simple_call:") try: descs = annotator.binding(oper.args[0]).descriptions except (KeyError, AttributeError) as e: msg.append(" (%s getting at the binding!)" % ( e.__class__.__name__,)) return for desc in list(descs): func = desc.pyobj if func is None: r = repr(desc) else: try: if isinstance(func, type): func_name = "%s.__init__" % func.__name__ func = func.__init__.im_func else: func_name = func.__name__ r = "function %s <%s, line %s>" % (func_name, func.__code__.co_filename, func.__code__.co_firstlineno) except (AttributeError, TypeError): r = repr(desc) msg.append(" %s returning" % (r,)) msg.append("") def debug(drv, use_pdb=True): # XXX unify some code with rpython.translator.goal.translate from rpython.translator.tool.pdbplus import PdbPlusShow from rpython.translator.driver import log t = drv.translator class options: huge = 100 tb = None import traceback errmsg = ["Error:\n"] exc, val, tb = sys.exc_info() errmsg.extend([" %s" % line for line in traceback.format_exception(exc, val, [])]) block = getattr(val, '__annotator_block', None) if block: class FileLike: def write(self, s): errmsg.append(" %s" % s) errmsg.append("Processing block:\n") t.about(block, FileLike()) log.ERROR(''.join(errmsg)) log.event("start debugger...") if use_pdb: pdb_plus_show = PdbPlusShow(t) pdb_plus_show.start(tb) @jit.elidable def offset2lineno(c, stopat): # even position in lnotab denote byte increments, odd line increments. # see dis.findlinestarts in the python std. library for more details tab = c.co_lnotab line = c.co_firstlineno addr = 0 for i in range(0, len(tab), 2): addr = addr + ord(tab[i]) if addr > stopat: break line = line + ord(tab[i+1]) return line
31.912791
93
0.5726
import sys import py from rpython.flowspace.model import Variable from rpython.rlib import jit SHOW_TRACEBACK = False SHOW_ANNOTATIONS = True SHOW_DEFAULT_LINES_OF_CODE = 0 def source_lines1(graph, block, operindex=None, offset=None, long=False, show_lines_of_code=SHOW_DEFAULT_LINES_OF_CODE): if block is not None: if block is graph.returnblock: return ['<return block>'] try: source = graph.source except AttributeError: return ['no source!'] else: graph_lines = source.split("\n") if offset is not None: linestart = offset2lineno(graph.func.__code__, offset) linerange = (linestart, linestart) here = None else: if block is None or not block.operations: return [] def toline(operindex): return offset2lineno(graph.func.__code__, block.operations[operindex].offset) if operindex is None: linerange = (toline(0), toline(-1)) if not long: return ['?'] here = None else: operline = toline(operindex) if long: linerange = (toline(0), toline(-1)) here = operline else: linerange = (operline, operline) here = None lines = ["Happened at file %s line %d" % (graph.filename, here or linerange[0]), ""] for n in range(max(0, linerange[0]-show_lines_of_code), min(linerange[1]+1+show_lines_of_code, len(graph_lines)+graph.startline)): if n == here: prefix = '==> ' else: prefix = ' ' lines.append(prefix + graph_lines[n-graph.startline]) lines.append("") return lines def source_lines(graph, *args, **kwds): lines = source_lines1(graph, *args, **kwds) return ['In %r:' % (graph,)] + lines def gather_error(annotator, graph, block, operindex): msg = [""] if operindex is not None: oper = block.operations[operindex] if oper.opname == 'simple_call': format_simple_call(annotator, oper, msg) else: oper = None msg.append(" %s\n" % str(oper)) msg += source_lines(graph, block, operindex, long=True) if oper is not None: if SHOW_ANNOTATIONS: msg += format_annotations(annotator, oper) msg += [''] return "\n".join(msg) def format_annotations(annotator, oper): msg = [] msg.append("Known variable annotations:") for arg in oper.args + [oper.result]: if isinstance(arg, Variable): try: msg.append(" " + str(arg) + " = " + str(annotator.binding(arg))) except KeyError: pass return msg def format_blocked_annotation_error(annotator, blocked_blocks): text = [] for block, (graph, index) in blocked_blocks.items(): text.append("Blocked block -- operation cannot succeed") text.append(gather_error(annotator, graph, block, index)) return '\n'.join(text) def format_simple_call(annotator, oper, msg): msg.append("Occurred processing the following simple_call:") try: descs = annotator.binding(oper.args[0]).descriptions except (KeyError, AttributeError) as e: msg.append(" (%s getting at the binding!)" % ( e.__class__.__name__,)) return for desc in list(descs): func = desc.pyobj if func is None: r = repr(desc) else: try: if isinstance(func, type): func_name = "%s.__init__" % func.__name__ func = func.__init__.im_func else: func_name = func.__name__ r = "function %s <%s, line %s>" % (func_name, func.__code__.co_filename, func.__code__.co_firstlineno) except (AttributeError, TypeError): r = repr(desc) msg.append(" %s returning" % (r,)) msg.append("") def debug(drv, use_pdb=True): from rpython.translator.tool.pdbplus import PdbPlusShow from rpython.translator.driver import log t = drv.translator class options: huge = 100 tb = None import traceback errmsg = ["Error:\n"] exc, val, tb = sys.exc_info() errmsg.extend([" %s" % line for line in traceback.format_exception(exc, val, [])]) block = getattr(val, '__annotator_block', None) if block: class FileLike: def write(self, s): errmsg.append(" %s" % s) errmsg.append("Processing block:\n") t.about(block, FileLike()) log.ERROR(''.join(errmsg)) log.event("start debugger...") if use_pdb: pdb_plus_show = PdbPlusShow(t) pdb_plus_show.start(tb) @jit.elidable def offset2lineno(c, stopat): tab = c.co_lnotab line = c.co_firstlineno addr = 0 for i in range(0, len(tab), 2): addr = addr + ord(tab[i]) if addr > stopat: break line = line + ord(tab[i+1]) return line
true
true
1c3c0230a734c982c54b25fd01431cd10dd44691
8,361
py
Python
mabwiser/linear.py
vishalbelsare/mabwiser
b0785a7b1da5342cc9b68be604f8f42f8a67958e
[ "Apache-2.0" ]
60
2020-06-10T11:20:52.000Z
2022-03-25T02:16:47.000Z
mabwiser/linear.py
vishalbelsare/mabwiser
b0785a7b1da5342cc9b68be604f8f42f8a67958e
[ "Apache-2.0" ]
24
2020-06-04T18:40:21.000Z
2022-03-24T16:49:51.000Z
mabwiser/linear.py
vishalbelsare/mabwiser
b0785a7b1da5342cc9b68be604f8f42f8a67958e
[ "Apache-2.0" ]
12
2020-11-30T10:37:05.000Z
2022-03-25T02:16:41.000Z
# -*- coding: utf-8 -*- # SPDX-License-Identifier: Apache-2.0 from copy import deepcopy from typing import Callable, Dict, List, NoReturn, Optional import numpy as np from mabwiser.base_mab import BaseMAB from mabwiser.utils import Arm, Num, argmax, _BaseRNG class _RidgeRegression: def __init__(self, rng: _BaseRNG, l2_lambda: Num = 1.0, alpha: Num = 1.0, scaler: Optional[Callable] = None): # Ridge Regression: https://onlinecourses.science.psu.edu/stat857/node/155/ self.rng = rng # random number generator self.l2_lambda = l2_lambda # regularization parameter self.alpha = alpha # exploration parameter self.scaler = scaler # standard scaler object self.beta = None # (XtX + l2_lambda * I_d)^-1 * Xty = A^-1 * Xty self.A = None # (XtX + l2_lambda * I_d) self.A_inv = None # (XtX + l2_lambda * I_d)^-1 self.Xty = None def init(self, num_features): # By default, assume that # A is the identity matrix and Xty is set to 0 self.Xty = np.zeros(num_features) self.A = self.l2_lambda * np.identity(num_features) self.A_inv = self.A.copy() self.beta = np.dot(self.A_inv, self.Xty) def fit(self, X, y): # Scale if self.scaler is not None: X = self.scaler.transform(X.astype('float64')) # X transpose Xt = X.T # Update A self.A = self.A + np.dot(Xt, X) self.A_inv = np.linalg.inv(self.A) # Add new Xty values to old self.Xty = self.Xty + np.dot(Xt, y) # Recalculate beta coefficients self.beta = np.dot(self.A_inv, self.Xty) def predict(self, x): # Scale if self.scaler is not None: x = self._scale_predict_context(x) # Calculate default expectation y = x * b return np.dot(x, self.beta) def _scale_predict_context(self, x): # Reshape 1D array to 2D x = x.reshape(1, -1) # Transform and return to previous shape. Convert to float64 to suppress any type warnings. return self.scaler.transform(x.astype('float64')).reshape(-1) class _LinTS(_RidgeRegression): def __init__(self, rng: _BaseRNG, l2_lambda: Num = 1.0, alpha: Num = 1.0, scaler: Optional[Callable] = None): super().__init__(rng, l2_lambda, alpha, scaler) # Set covariance to none self.covar_decomposed = None def init(self, num_features): super().init(num_features) # Calculate covariance self.covar_decomposed = self._cholesky() def fit(self, X, y): super().fit(X, y) # Calculate covariance self.covar_decomposed = self._cholesky() def predict(self, x): # Scale if self.scaler is not None: x = self._scale_predict_context(x) # Multivariate Normal Sampling # Adapted from the implementation in numpy.random.generator.multivariate_normal version 1.18.0 # Uses the cholesky implementation from numpy.linalg instead of numpy.dual sampled_norm = self.rng.standard_normal(self.beta.shape[0]) # Randomly sample coefficients from Normal Distribution N(mean=beta, std=covar_decomposed) beta_sampled = self.beta + np.dot(sampled_norm, self.covar_decomposed) # Calculate expectation y = x * beta_sampled return np.dot(x, beta_sampled) def _cholesky(self): # Calculate exploration factor exploration = np.square(self.alpha) * self.A_inv # Covariance using cholesky decomposition covar_decomposed = np.linalg.cholesky(exploration) return covar_decomposed class _LinUCB(_RidgeRegression): def predict(self, x): # Scale if self.scaler is not None: x = self._scale_predict_context(x) # Upper confidence bound = alpha * sqrt(x A^-1 xt). Notice that, x = xt ucb = (self.alpha * np.sqrt(np.dot(np.dot(x, self.A_inv), x))) # Calculate linucb expectation y = x * b + ucb return np.dot(x, self.beta) + ucb class _Linear(BaseMAB): factory = {"ts": _LinTS, "ucb": _LinUCB, "ridge": _RidgeRegression} def __init__(self, rng: _BaseRNG, arms: List[Arm], n_jobs: int, backend: Optional[str], l2_lambda: Num, alpha: Num, regression: str, arm_to_scaler: Optional[Dict[Arm, Callable]] = None): super().__init__(rng, arms, n_jobs, backend) self.l2_lambda = l2_lambda self.alpha = alpha self.regression = regression # Create ridge regression model for each arm self.num_features = None if arm_to_scaler is None: arm_to_scaler = dict((arm, None) for arm in arms) self.arm_to_model = dict((arm, _Linear.factory.get(regression)(rng, l2_lambda, alpha, arm_to_scaler[arm])) for arm in arms) def fit(self, decisions: np.ndarray, rewards: np.ndarray, contexts: np.ndarray = None) -> NoReturn: # Initialize each model by arm self.num_features = contexts.shape[1] for arm in self.arms: self.arm_to_model[arm].init(num_features=self.num_features) # Perform parallel fit self._parallel_fit(decisions, rewards, contexts) def partial_fit(self, decisions: np.ndarray, rewards: np.ndarray, contexts: np.ndarray = None) -> NoReturn: # Perform parallel fit self._parallel_fit(decisions, rewards, contexts) def predict(self, contexts: np.ndarray = None): # Return predict for the given context return self._parallel_predict(contexts, is_predict=True) def predict_expectations(self, contexts: np.ndarray = None): # Return predict expectations for the given context return self._parallel_predict(contexts, is_predict=False) def _uptake_new_arm(self, arm: Arm, binarizer: Callable = None, scaler: Callable = None): # Add to untrained_arms arms self.arm_to_model[arm] = _Linear.factory.get(self.regression)(self.rng, self.l2_lambda, self.alpha, scaler) # If fit happened, initialize the new arm to defaults is_fitted = self.num_features is not None if is_fitted: self.arm_to_model[arm].init(num_features=self.num_features) def _fit_arm(self, arm: Arm, decisions: np.ndarray, rewards: np.ndarray, contexts: Optional[np.ndarray] = None): # Get local copy of model to minimize communication overhead # between arms (processes) using shared object lr = deepcopy(self.arm_to_model[arm]) # Skip the arms with no data indices = np.where(decisions == arm) if indices[0].size == 0: return lr # Fit the regression X = contexts[indices] y = rewards[indices] lr.fit(X, y) self.arm_to_model[arm] = lr def _predict_contexts(self, contexts: np.ndarray, is_predict: bool, seeds: Optional[np.ndarray] = None, start_index: Optional[int] = None) -> List: # Get local copy of model, arm_to_expectation and arms to minimize # communication overhead between arms (processes) using shared objects arm_to_model = deepcopy(self.arm_to_model) arm_to_expectation = deepcopy(self.arm_to_expectation) arms = deepcopy(self.arms) # Create an empty list of predictions predictions = [None] * len(contexts) for index, row in enumerate(contexts): # Each row needs a separately seeded rng for reproducibility in parallel rng = np.random.RandomState(seed=seeds[index]) for arm in arms: # Copy the row rng to the deep copied model in arm_to_model arm_to_model[arm].rng = rng # Get the expectation of each arm from its trained model arm_to_expectation[arm] = arm_to_model[arm].predict(row) if is_predict: predictions[index] = argmax(arm_to_expectation) else: predictions[index] = arm_to_expectation.copy() # Return list of predictions return predictions
35.427966
116
0.621457
from copy import deepcopy from typing import Callable, Dict, List, NoReturn, Optional import numpy as np from mabwiser.base_mab import BaseMAB from mabwiser.utils import Arm, Num, argmax, _BaseRNG class _RidgeRegression: def __init__(self, rng: _BaseRNG, l2_lambda: Num = 1.0, alpha: Num = 1.0, scaler: Optional[Callable] = None): self.rng = rng self.l2_lambda = l2_lambda self.alpha = alpha self.scaler = scaler self.beta = None self.A = None self.A_inv = None self.Xty = None def init(self, num_features): self.Xty = np.zeros(num_features) self.A = self.l2_lambda * np.identity(num_features) self.A_inv = self.A.copy() self.beta = np.dot(self.A_inv, self.Xty) def fit(self, X, y): if self.scaler is not None: X = self.scaler.transform(X.astype('float64')) Xt = X.T self.A = self.A + np.dot(Xt, X) self.A_inv = np.linalg.inv(self.A) self.Xty = self.Xty + np.dot(Xt, y) self.beta = np.dot(self.A_inv, self.Xty) def predict(self, x): if self.scaler is not None: x = self._scale_predict_context(x) return np.dot(x, self.beta) def _scale_predict_context(self, x): x = x.reshape(1, -1) return self.scaler.transform(x.astype('float64')).reshape(-1) class _LinTS(_RidgeRegression): def __init__(self, rng: _BaseRNG, l2_lambda: Num = 1.0, alpha: Num = 1.0, scaler: Optional[Callable] = None): super().__init__(rng, l2_lambda, alpha, scaler) self.covar_decomposed = None def init(self, num_features): super().init(num_features) self.covar_decomposed = self._cholesky() def fit(self, X, y): super().fit(X, y) self.covar_decomposed = self._cholesky() def predict(self, x): if self.scaler is not None: x = self._scale_predict_context(x) sampled_norm = self.rng.standard_normal(self.beta.shape[0]) beta_sampled = self.beta + np.dot(sampled_norm, self.covar_decomposed) return np.dot(x, beta_sampled) def _cholesky(self): exploration = np.square(self.alpha) * self.A_inv covar_decomposed = np.linalg.cholesky(exploration) return covar_decomposed class _LinUCB(_RidgeRegression): def predict(self, x): if self.scaler is not None: x = self._scale_predict_context(x) ucb = (self.alpha * np.sqrt(np.dot(np.dot(x, self.A_inv), x))) return np.dot(x, self.beta) + ucb class _Linear(BaseMAB): factory = {"ts": _LinTS, "ucb": _LinUCB, "ridge": _RidgeRegression} def __init__(self, rng: _BaseRNG, arms: List[Arm], n_jobs: int, backend: Optional[str], l2_lambda: Num, alpha: Num, regression: str, arm_to_scaler: Optional[Dict[Arm, Callable]] = None): super().__init__(rng, arms, n_jobs, backend) self.l2_lambda = l2_lambda self.alpha = alpha self.regression = regression self.num_features = None if arm_to_scaler is None: arm_to_scaler = dict((arm, None) for arm in arms) self.arm_to_model = dict((arm, _Linear.factory.get(regression)(rng, l2_lambda, alpha, arm_to_scaler[arm])) for arm in arms) def fit(self, decisions: np.ndarray, rewards: np.ndarray, contexts: np.ndarray = None) -> NoReturn: self.num_features = contexts.shape[1] for arm in self.arms: self.arm_to_model[arm].init(num_features=self.num_features) self._parallel_fit(decisions, rewards, contexts) def partial_fit(self, decisions: np.ndarray, rewards: np.ndarray, contexts: np.ndarray = None) -> NoReturn: self._parallel_fit(decisions, rewards, contexts) def predict(self, contexts: np.ndarray = None): return self._parallel_predict(contexts, is_predict=True) def predict_expectations(self, contexts: np.ndarray = None): return self._parallel_predict(contexts, is_predict=False) def _uptake_new_arm(self, arm: Arm, binarizer: Callable = None, scaler: Callable = None): self.arm_to_model[arm] = _Linear.factory.get(self.regression)(self.rng, self.l2_lambda, self.alpha, scaler) is_fitted = self.num_features is not None if is_fitted: self.arm_to_model[arm].init(num_features=self.num_features) def _fit_arm(self, arm: Arm, decisions: np.ndarray, rewards: np.ndarray, contexts: Optional[np.ndarray] = None): lr = deepcopy(self.arm_to_model[arm]) indices = np.where(decisions == arm) if indices[0].size == 0: return lr X = contexts[indices] y = rewards[indices] lr.fit(X, y) self.arm_to_model[arm] = lr def _predict_contexts(self, contexts: np.ndarray, is_predict: bool, seeds: Optional[np.ndarray] = None, start_index: Optional[int] = None) -> List: arm_to_model = deepcopy(self.arm_to_model) arm_to_expectation = deepcopy(self.arm_to_expectation) arms = deepcopy(self.arms) predictions = [None] * len(contexts) for index, row in enumerate(contexts): rng = np.random.RandomState(seed=seeds[index]) for arm in arms: arm_to_model[arm].rng = rng arm_to_expectation[arm] = arm_to_model[arm].predict(row) if is_predict: predictions[index] = argmax(arm_to_expectation) else: predictions[index] = arm_to_expectation.copy() return predictions
true
true
1c3c03f2db10438b81045ad71d95cfd8f9dee172
3,911
py
Python
src-tmp/relations2.py
EulerProject/EulerX
49e63e6a27be97ab30832180a47d214494388e15
[ "MIT" ]
15
2016-02-17T20:48:29.000Z
2021-03-05T20:38:05.000Z
src-tmp/relations2.py
eddy7896/EulerX
49e63e6a27be97ab30832180a47d214494388e15
[ "MIT" ]
16
2015-02-05T18:38:48.000Z
2021-06-14T11:38:36.000Z
src-tmp/relations2.py
eddy7896/EulerX
49e63e6a27be97ab30832180a47d214494388e15
[ "MIT" ]
4
2016-01-26T03:24:52.000Z
2020-01-09T07:57:15.000Z
# Copyright (c) 2014 University of California, Davis # # # 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. rcc5 = {} rcc5["equals"] = 1 << 0 rcc5["includes"] = 1 << 1 rcc5["is_included_in"] = 1 << 2 rcc5["disjoint"] = 1 << 3 rcc5["overlaps"] = 1 << 4 rcc5['"="'] = 1 << 0 rcc5['">"'] = 1 << 1 rcc5['"<"'] = 1 << 2 rcc5['"!"'] = 1 << 3 rcc5['"><"'] = 1 << 4 logmap = {} logmap[1<<0] = 0 logmap[1<<1] = 1 logmap[1<<2] = 2 logmap[1<<3] = 3 logmap[1<<4] = 4 relation = {} relation["no"] = 0 relation["="] = 1 << 0 relation[">"] = 1 << 1 relation["<"] = 1 << 2 relation["!"] = 1 << 3 #relation["<>"] = 1 << 3 relation["><"] = 1 << 4 # Imfer bit relation["infer"] = 1 << 5 relation["{=, >}"] = 1 << 0 | 1 << 1 relation["{=, <}"] = 1 << 0 | 1 << 2 relation["{=, !}"] = 1 << 0 | 1 << 3 relation["{=, ><}"] = 1 << 0 | 1 << 4 relation["{>, <}"] = 1 << 1 | 1 << 2 relation["{>, !}"] = 1 << 1 | 1 << 3 relation["{>, ><}"] = 1 << 1 | 1 << 4 relation["{<, !}"] = 1 << 2 | 1 << 3 relation["{<, ><}"] = 1 << 2 | 1 << 4 relation["{!, ><}"] = 1 << 3 | 1 << 4 relation["{=, >, <}"] = 1 << 0 | 1 << 1 | 1 << 2 relation["{=, >, !}"] = 1 << 0 | 1 << 1 | 1 << 3 relation["{=, >, ><}"] = 1 << 0 | 1 << 1 | 1 << 4 relation["{=, <, !}"] = 1 << 0 | 1 << 2 | 1 << 3 relation["{=, <, ><}"] = 1 << 0 | 1 << 2 | 1 << 4 relation["{=, !, ><}"] = 1 << 0 | 1 << 3 | 1 << 4 relation["{>, <, !}"] = 1 << 1 | 1 << 2 | 1 << 3 relation["{>, <, ><}"] = 1 << 1 | 1 << 2 | 1 << 4 relation["{>, !, ><}"] = 1 << 1 | 1 << 3 | 1 << 4 relation["{<, !, ><}"] = 1 << 2 | 1 << 3 | 1 << 4 relation["{=, >, <, !}"] = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 relation["{=, >, <, ><}"] = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 relation["{=, >, !, ><}"] = 1 << 0 | 1 << 1 | 1 << 3 | 1 << 4 relation["{=, <, !, ><}"] = 1 << 0 | 1 << 2 | 1 << 3 | 1 << 4 relation["{>, <, !, ><}"] = 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 relation["{=, >, <, !, ><}"] = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 relation["+="] = 1 << 5 #lsum relation["=+"] = (1 << 5) + 1 #rsum relation["+3="] = 1 << 6 #l3sum relation["=3+"] = (1 << 6) + 1 #r3sum relation["+4="] = 1 << 7 #l4sum relation["-="] = 1 << 8 #ldiff relation["=-"] = (1 << 8) + 1 #rdiff relstr={} relstr[0] = "equals" relstr[1] = "includes" relstr[2] = "is_included_in" relstr[3] = "disjoint" relstr[4] = "overlaps" reasoner={} reasoner["dlv"] = 1 << 0 reasoner["gringo"] = 1 << 1 encode = {} encode[0] = 0 # null encoding encode["dr"] = 1 # direct encoding encode["direct"] = encode["dr"] # direct encoding encode["vr"] = 2 # binary encoding encode["binary"] = encode["vr"] # binary encoding encode["mn"] = 3 # polynomial encoding encode["poly"] = encode["mn"] # polynomial encoding query = {} query[0] = 0 query["pw"] = 1 query["AllPWs"] = query["pw"]
35.554545
73
0.500639
rcc5 = {} rcc5["equals"] = 1 << 0 rcc5["includes"] = 1 << 1 rcc5["is_included_in"] = 1 << 2 rcc5["disjoint"] = 1 << 3 rcc5["overlaps"] = 1 << 4 rcc5['"="'] = 1 << 0 rcc5['">"'] = 1 << 1 rcc5['"<"'] = 1 << 2 rcc5['"!"'] = 1 << 3 rcc5['"><"'] = 1 << 4 logmap = {} logmap[1<<0] = 0 logmap[1<<1] = 1 logmap[1<<2] = 2 logmap[1<<3] = 3 logmap[1<<4] = 4 relation = {} relation["no"] = 0 relation["="] = 1 << 0 relation[">"] = 1 << 1 relation["<"] = 1 << 2 relation["!"] = 1 << 3 relation["><"] = 1 << 4 relation["infer"] = 1 << 5 relation["{=, >}"] = 1 << 0 | 1 << 1 relation["{=, <}"] = 1 << 0 | 1 << 2 relation["{=, !}"] = 1 << 0 | 1 << 3 relation["{=, ><}"] = 1 << 0 | 1 << 4 relation["{>, <}"] = 1 << 1 | 1 << 2 relation["{>, !}"] = 1 << 1 | 1 << 3 relation["{>, ><}"] = 1 << 1 | 1 << 4 relation["{<, !}"] = 1 << 2 | 1 << 3 relation["{<, ><}"] = 1 << 2 | 1 << 4 relation["{!, ><}"] = 1 << 3 | 1 << 4 relation["{=, >, <}"] = 1 << 0 | 1 << 1 | 1 << 2 relation["{=, >, !}"] = 1 << 0 | 1 << 1 | 1 << 3 relation["{=, >, ><}"] = 1 << 0 | 1 << 1 | 1 << 4 relation["{=, <, !}"] = 1 << 0 | 1 << 2 | 1 << 3 relation["{=, <, ><}"] = 1 << 0 | 1 << 2 | 1 << 4 relation["{=, !, ><}"] = 1 << 0 | 1 << 3 | 1 << 4 relation["{>, <, !}"] = 1 << 1 | 1 << 2 | 1 << 3 relation["{>, <, ><}"] = 1 << 1 | 1 << 2 | 1 << 4 relation["{>, !, ><}"] = 1 << 1 | 1 << 3 | 1 << 4 relation["{<, !, ><}"] = 1 << 2 | 1 << 3 | 1 << 4 relation["{=, >, <, !}"] = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 relation["{=, >, <, ><}"] = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 relation["{=, >, !, ><}"] = 1 << 0 | 1 << 1 | 1 << 3 | 1 << 4 relation["{=, <, !, ><}"] = 1 << 0 | 1 << 2 | 1 << 3 | 1 << 4 relation["{>, <, !, ><}"] = 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 relation["{=, >, <, !, ><}"] = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 relation["+="] = 1 << 5 relation["=+"] = (1 << 5) + 1 relation["+3="] = 1 << 6 relation["=3+"] = (1 << 6) + 1 relation["+4="] = 1 << 7 relation["-="] = 1 << 8 relation["=-"] = (1 << 8) + 1 relstr={} relstr[0] = "equals" relstr[1] = "includes" relstr[2] = "is_included_in" relstr[3] = "disjoint" relstr[4] = "overlaps" reasoner={} reasoner["dlv"] = 1 << 0 reasoner["gringo"] = 1 << 1 encode = {} encode[0] = 0 encode["dr"] = 1 encode["direct"] = encode["dr"] encode["vr"] = 2 encode["binary"] = encode["vr"] encode["mn"] = 3 encode["poly"] = encode["mn"] query = {} query[0] = 0 query["pw"] = 1 query["AllPWs"] = query["pw"]
true
true
1c3c040dd71440deedbd87f357b20847ab96f47a
5,488
py
Python
cloudferry/lib/os/discovery/keystone.py
SVilgelm/CloudFerry
4459c0d21ba7ccffe51176932197b352e426ba63
[ "Apache-2.0" ]
6
2017-04-20T00:49:49.000Z
2020-12-20T16:27:10.000Z
cloudferry/lib/os/discovery/keystone.py
SVilgelm/CloudFerry
4459c0d21ba7ccffe51176932197b352e426ba63
[ "Apache-2.0" ]
3
2017-04-08T15:47:16.000Z
2017-05-18T17:40:59.000Z
cloudferry/lib/os/discovery/keystone.py
SVilgelm/CloudFerry
4459c0d21ba7ccffe51176932197b352e426ba63
[ "Apache-2.0" ]
8
2017-04-07T23:42:36.000Z
2021-08-10T11:05:10.000Z
# Copyright 2016 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import logging from keystoneclient import exceptions from cloudferry import discover from cloudferry import model from cloudferry.model import identity from cloudferry.lib.os import clients from cloudferry.lib.os import cloud_db LOG = logging.getLogger(__name__) class BaseKeystoneDiscoverer(discover.Discoverer): @property def _manager(self): raise NotImplementedError() def discover_all(self): raw_objs = self.retry(self._manager.list, returns_iterable=True) with model.Session() as session: for raw_obj in raw_objs: session.store(self.load_from_cloud(raw_obj)) def discover_one(self, uuid): try: raw_obj = self.retry(self._manager.get, uuid, expected_exceptions=[exceptions.NotFound]) with model.Session() as session: obj = self.load_from_cloud(raw_obj) session.store(obj) return obj except exceptions.NotFound: raise discover.NotFound() class UserDiscoverer(BaseKeystoneDiscoverer): discovered_class = identity.User @property def _manager(self): identity_client = clients.identity_client(self.cloud) return identity_client.users def load_from_cloud(self, data): return identity.User.load({ 'object_id': self.make_id(data.id), 'name': data.name, 'enabled': data.enabled, }) class TenantDiscoverer(BaseKeystoneDiscoverer): discovered_class = identity.Tenant @property def _manager(self): identity_client = clients.identity_client(self.cloud) return identity_client.tenants def load_from_cloud(self, data): return identity.Tenant.load({ 'object_id': self.make_id(data.id), 'name': data.name, 'enabled': data.enabled, 'description': data.description, }) class RoleDiscoverer(BaseKeystoneDiscoverer): discovered_class = identity.Role @property def _manager(self): identity_client = clients.identity_client(self.cloud) return identity_client.roles def load_from_cloud(self, data): return identity.Role.load({ 'object_id': self.make_id(data.id), 'name': data.name, }) class UserRoleDiscoverer(discover.Discoverer): discovered_class = identity.UserRole @staticmethod def _is_grizzly(keystone_db): result = keystone_db.query('SHOW TABLES LIKE \'assignment\'') return len(result) == 0 @staticmethod def _iterate_legacy_roles(keystone_db): for row in keystone_db.query( 'SELECT `user_id`, `project_id`, `data` ' 'FROM `user_project_metadata`'): data = json.loads(row['data']) for role_id in data.get('roles', []): yield row['user_id'], row['project_id'], role_id @staticmethod def _iterate_modern_roles(keystone_db): for row in keystone_db.query( 'SELECT `actor_id`, `target_id`, `role_id` ' 'FROM `assignment` WHERE `type`=\'UserProject\''): yield row['actor_id'], row['target_id'], row['role_id'] def _iterate_roles(self, keystone_db): if self._is_grizzly(keystone_db): return self._iterate_legacy_roles(keystone_db) else: return self._iterate_modern_roles(keystone_db) @staticmethod def _make_obj(user_id, tenant_id, role_id): return { 'id': ':'.join([user_id, tenant_id, role_id]), 'tenant_id': tenant_id, 'user_id': user_id, 'role_id': role_id, } def discover_all(self): with cloud_db.connection(self.cloud.keystone_db) as ks_db: with model.Session() as session: for user_id, tenant_id, role_id in self._iterate_roles(ks_db): raw_obj = self._make_obj(user_id, tenant_id, role_id) session.store(self.load_from_cloud(raw_obj, no_check=True)) def discover_one(self, uuid): user_id, tenant_id, role_id = uuid.split(':') raw_obj = self._make_obj(user_id, tenant_id, role_id) with model.Session() as session: user_role = self.load_from_cloud(raw_obj) session.store(user_role) return user_role def load_from_cloud(self, data, no_check=False): # pylint: disable=arguments-differ if no_check: make_ref = self.make_ref else: make_ref = self.find_ref return identity.UserRole.load({ 'object_id': self.make_id(data['id']), 'tenant': make_ref(identity.Tenant, data['tenant_id']), 'user': make_ref(identity.User, data['user_id']), 'role': make_ref(identity.Role, data['role_id']), })
33.060241
79
0.637937
import json import logging from keystoneclient import exceptions from cloudferry import discover from cloudferry import model from cloudferry.model import identity from cloudferry.lib.os import clients from cloudferry.lib.os import cloud_db LOG = logging.getLogger(__name__) class BaseKeystoneDiscoverer(discover.Discoverer): @property def _manager(self): raise NotImplementedError() def discover_all(self): raw_objs = self.retry(self._manager.list, returns_iterable=True) with model.Session() as session: for raw_obj in raw_objs: session.store(self.load_from_cloud(raw_obj)) def discover_one(self, uuid): try: raw_obj = self.retry(self._manager.get, uuid, expected_exceptions=[exceptions.NotFound]) with model.Session() as session: obj = self.load_from_cloud(raw_obj) session.store(obj) return obj except exceptions.NotFound: raise discover.NotFound() class UserDiscoverer(BaseKeystoneDiscoverer): discovered_class = identity.User @property def _manager(self): identity_client = clients.identity_client(self.cloud) return identity_client.users def load_from_cloud(self, data): return identity.User.load({ 'object_id': self.make_id(data.id), 'name': data.name, 'enabled': data.enabled, }) class TenantDiscoverer(BaseKeystoneDiscoverer): discovered_class = identity.Tenant @property def _manager(self): identity_client = clients.identity_client(self.cloud) return identity_client.tenants def load_from_cloud(self, data): return identity.Tenant.load({ 'object_id': self.make_id(data.id), 'name': data.name, 'enabled': data.enabled, 'description': data.description, }) class RoleDiscoverer(BaseKeystoneDiscoverer): discovered_class = identity.Role @property def _manager(self): identity_client = clients.identity_client(self.cloud) return identity_client.roles def load_from_cloud(self, data): return identity.Role.load({ 'object_id': self.make_id(data.id), 'name': data.name, }) class UserRoleDiscoverer(discover.Discoverer): discovered_class = identity.UserRole @staticmethod def _is_grizzly(keystone_db): result = keystone_db.query('SHOW TABLES LIKE \'assignment\'') return len(result) == 0 @staticmethod def _iterate_legacy_roles(keystone_db): for row in keystone_db.query( 'SELECT `user_id`, `project_id`, `data` ' 'FROM `user_project_metadata`'): data = json.loads(row['data']) for role_id in data.get('roles', []): yield row['user_id'], row['project_id'], role_id @staticmethod def _iterate_modern_roles(keystone_db): for row in keystone_db.query( 'SELECT `actor_id`, `target_id`, `role_id` ' 'FROM `assignment` WHERE `type`=\'UserProject\''): yield row['actor_id'], row['target_id'], row['role_id'] def _iterate_roles(self, keystone_db): if self._is_grizzly(keystone_db): return self._iterate_legacy_roles(keystone_db) else: return self._iterate_modern_roles(keystone_db) @staticmethod def _make_obj(user_id, tenant_id, role_id): return { 'id': ':'.join([user_id, tenant_id, role_id]), 'tenant_id': tenant_id, 'user_id': user_id, 'role_id': role_id, } def discover_all(self): with cloud_db.connection(self.cloud.keystone_db) as ks_db: with model.Session() as session: for user_id, tenant_id, role_id in self._iterate_roles(ks_db): raw_obj = self._make_obj(user_id, tenant_id, role_id) session.store(self.load_from_cloud(raw_obj, no_check=True)) def discover_one(self, uuid): user_id, tenant_id, role_id = uuid.split(':') raw_obj = self._make_obj(user_id, tenant_id, role_id) with model.Session() as session: user_role = self.load_from_cloud(raw_obj) session.store(user_role) return user_role def load_from_cloud(self, data, no_check=False): if no_check: make_ref = self.make_ref else: make_ref = self.find_ref return identity.UserRole.load({ 'object_id': self.make_id(data['id']), 'tenant': make_ref(identity.Tenant, data['tenant_id']), 'user': make_ref(identity.User, data['user_id']), 'role': make_ref(identity.Role, data['role_id']), })
true
true
1c3c074720fc037e86fe585d72e59f4145d914a7
1,234
py
Python
DesignPattern/bridge.py
zzragida/PythonExamples
ed94ae2773a580a42e158ebdc7321a89ca4e991b
[ "MIT" ]
null
null
null
DesignPattern/bridge.py
zzragida/PythonExamples
ed94ae2773a580a42e158ebdc7321a89ca4e991b
[ "MIT" ]
null
null
null
DesignPattern/bridge.py
zzragida/PythonExamples
ed94ae2773a580a42e158ebdc7321a89ca4e991b
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Bridge_Pattern#Python""" # ConcreteImplementor 1/2 class DrawingAPI1(object): def draw_circle(self, x, y, radius): print('API1.circle at {}:{} radius {}'.format(x, y, radius)) # ConcreteImplementor 2/2 class DrawingAPI2(object): def draw_circle(self, x, y, radius): print('API2.circle at {}:{} radius {}'.format(x, y, radius)) # Refined Abstraction class CircleShape(object): def __init__(self, x, y, radius, drawing_api): self._x = x self._y = y self._radius = radius self._drawing_api = drawing_api # low-level i.e. Implementation specific def draw(self): self._drawing_api.draw_circle(self._x, self._y, self._radius) # high-level i.e. Abstraction specific def scale(self, pct): self._radius *= pct def main(): shapes = ( CircleShape(1, 2, 3, DrawingAPI1()), CircleShape(5, 7, 11, DrawingAPI2()) ) for shape in shapes: shape.scale(2.5) shape.draw() if __name__ == '__main__': main() ### OUTPUT ### # API1.circle at 1:2 radius 7.5 # API2.circle at 5:7 radius 27.5
22.035714
89
0.623177
class DrawingAPI1(object): def draw_circle(self, x, y, radius): print('API1.circle at {}:{} radius {}'.format(x, y, radius)) class DrawingAPI2(object): def draw_circle(self, x, y, radius): print('API2.circle at {}:{} radius {}'.format(x, y, radius)) class CircleShape(object): def __init__(self, x, y, radius, drawing_api): self._x = x self._y = y self._radius = radius self._drawing_api = drawing_api def draw(self): self._drawing_api.draw_circle(self._x, self._y, self._radius) def scale(self, pct): self._radius *= pct def main(): shapes = ( CircleShape(1, 2, 3, DrawingAPI1()), CircleShape(5, 7, 11, DrawingAPI2()) ) for shape in shapes: shape.scale(2.5) shape.draw() if __name__ == '__main__': main()
true
true
1c3c074b01d2299f1d4162559c1204f13dcc05ed
332
py
Python
currency_converter/conversion.py
Shadwz17/currency-converter
817037ab73412f803e5a2f032c9de5337fe38272
[ "MIT" ]
null
null
null
currency_converter/conversion.py
Shadwz17/currency-converter
817037ab73412f803e5a2f032c9de5337fe38272
[ "MIT" ]
null
null
null
currency_converter/conversion.py
Shadwz17/currency-converter
817037ab73412f803e5a2f032c9de5337fe38272
[ "MIT" ]
null
null
null
dollar_euro = 0.88 euro_pound = 0.84 def dollar_to_euro(amount): amount *= dollar_euro return amount def euro_to_dollar(amount): amount /= dollar_euro return amount def euro_to_pound(amount): amount *= euro_pound return amount def pound_to_euro(amount): amount /= euro_pound return amount
14.434783
28
0.695783
dollar_euro = 0.88 euro_pound = 0.84 def dollar_to_euro(amount): amount *= dollar_euro return amount def euro_to_dollar(amount): amount /= dollar_euro return amount def euro_to_pound(amount): amount *= euro_pound return amount def pound_to_euro(amount): amount /= euro_pound return amount
true
true
1c3c083a00678b16d92e2b26a315d5b428d414f7
922
py
Python
tests/check_contact.py
tinytoon1/python
cc320fddea962fec97eb928e2c4ebbd5bad3ed43
[ "Apache-2.0" ]
null
null
null
tests/check_contact.py
tinytoon1/python
cc320fddea962fec97eb928e2c4ebbd5bad3ed43
[ "Apache-2.0" ]
null
null
null
tests/check_contact.py
tinytoon1/python
cc320fddea962fec97eb928e2c4ebbd5bad3ed43
[ "Apache-2.0" ]
null
null
null
from model.contact import Contact def test_check_contacts_info(app, orm): if len(orm.get_contacts()) == 0: app.contact.add(Contact(firstname='Alex', lastname='Murphy')) contacts_from_homepage = sorted(app.contact.get_contacts(), key=Contact.id_or_max) contacts_from_db = sorted(orm.get_contacts(), key=Contact.id_or_max) assert len(contacts_from_homepage) == len(contacts_from_db) for i in range(len(contacts_from_db)): assert contacts_from_homepage[i].id == contacts_from_db[i].id assert contacts_from_homepage[i].firstname == contacts_from_db[i].firstname assert contacts_from_homepage[i].lastname == contacts_from_db[i].lastname assert contacts_from_homepage[i].address == contacts_from_db[i].address assert contacts_from_homepage[i].phones == contacts_from_db[i].phones assert contacts_from_homepage[i].emails == contacts_from_db[i].emails
54.235294
86
0.745119
from model.contact import Contact def test_check_contacts_info(app, orm): if len(orm.get_contacts()) == 0: app.contact.add(Contact(firstname='Alex', lastname='Murphy')) contacts_from_homepage = sorted(app.contact.get_contacts(), key=Contact.id_or_max) contacts_from_db = sorted(orm.get_contacts(), key=Contact.id_or_max) assert len(contacts_from_homepage) == len(contacts_from_db) for i in range(len(contacts_from_db)): assert contacts_from_homepage[i].id == contacts_from_db[i].id assert contacts_from_homepage[i].firstname == contacts_from_db[i].firstname assert contacts_from_homepage[i].lastname == contacts_from_db[i].lastname assert contacts_from_homepage[i].address == contacts_from_db[i].address assert contacts_from_homepage[i].phones == contacts_from_db[i].phones assert contacts_from_homepage[i].emails == contacts_from_db[i].emails
true
true
1c3c08801649b292a420c115798a8f04cf0701ed
8,334
py
Python
benchmark/fluid/MADDPG/train.py
lp2333/PARL
e4bde1f5b7e69c5f8d3ee3a90a647dfe12204bd3
[ "ECL-2.0", "Apache-2.0" ]
3,172
2018-05-22T02:02:29.000Z
2022-03-31T09:14:56.000Z
benchmark/fluid/MADDPG/train.py
BKBK00/PARL
f508bc6085420431b504441c7ff129e64826603e
[ "Apache-2.0" ]
422
2018-05-17T16:58:45.000Z
2022-03-31T02:03:25.000Z
benchmark/fluid/MADDPG/train.py
BKBK00/PARL
f508bc6085420431b504441c7ff129e64826603e
[ "Apache-2.0" ]
794
2018-05-21T18:33:19.000Z
2022-03-30T13:38:09.000Z
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from parl.utils import check_version_for_fluid # requires parl >= 1.4.1 check_version_for_fluid() import os import time import argparse import numpy as np from simple_model import MAModel from simple_agent import MAAgent import parl from parl.env.multiagent_simple_env import MAenv from parl.utils import logger, summary def run_episode(env, agents): obs_n = env.reset() total_reward = 0 agents_reward = [0 for _ in range(env.n)] steps = 0 while True: steps += 1 action_n = [agent.predict(obs) for agent, obs in zip(agents, obs_n)] next_obs_n, reward_n, done_n, _ = env.step(action_n) done = all(done_n) terminal = (steps >= args.max_step_per_episode) # store experience for i, agent in enumerate(agents): agent.add_experience(obs_n[i], action_n[i], reward_n[i], next_obs_n[i], done_n[i]) # compute reward of every agent obs_n = next_obs_n for i, reward in enumerate(reward_n): total_reward += reward agents_reward[i] += reward # check the end of an episode if done or terminal: break # show animation if args.show: time.sleep(0.1) env.render() # show model effect without training if args.restore and args.show: continue # learn policy for i, agent in enumerate(agents): critic_loss = agent.learn(agents) summary.add_scalar('critic_loss_%d' % i, critic_loss, agent.global_train_step) return total_reward, agents_reward, steps def train_agent(): env = MAenv(args.env) logger.info('agent num: {}'.format(env.n)) logger.info('observation_space: {}'.format(env.observation_space)) logger.info('action_space: {}'.format(env.action_space)) logger.info('obs_shape_n: {}'.format(env.obs_shape_n)) logger.info('act_shape_n: {}'.format(env.act_shape_n)) for i in range(env.n): logger.info('agent {} obs_low:{} obs_high:{}'.format( i, env.observation_space[i].low, env.observation_space[i].high)) logger.info('agent {} act_n:{}'.format(i, env.act_shape_n[i])) if ('low' in dir(env.action_space[i])): logger.info('agent {} act_low:{} act_high:{} act_shape:{}'.format( i, env.action_space[i].low, env.action_space[i].high, env.action_space[i].shape)) logger.info('num_discrete_space:{}'.format( env.action_space[i].num_discrete_space)) from gym import spaces from multiagent.multi_discrete import MultiDiscrete for space in env.action_space: assert (isinstance(space, spaces.Discrete) or isinstance(space, MultiDiscrete)) agents = [] for i in range(env.n): model = MAModel(env.act_shape_n[i]) algorithm = parl.algorithms.MADDPG( model, agent_index=i, act_space=env.action_space, gamma=args.gamma, tau=args.tau, critic_lr=args.critic_lr, actor_lr=args.actor_lr) agent = MAAgent( algorithm, agent_index=i, obs_dim_n=env.obs_shape_n, act_dim_n=env.act_shape_n, batch_size=args.batch_size, speedup=(not args.restore)) agents.append(agent) total_steps = 0 total_episodes = 0 episode_rewards = [] # sum of rewards for all agents agent_rewards = [[] for _ in range(env.n)] # individual agent reward final_ep_rewards = [] # sum of rewards for training curve final_ep_ag_rewards = [] # agent rewards for training curve if args.restore: # restore modle for i in range(len(agents)): model_file = args.model_dir + '/agent_' + str(i) if not os.path.exists(model_file): raise Exception( 'model file {} does not exits'.format(model_file)) agents[i].restore(model_file) t_start = time.time() logger.info('Starting...') while total_episodes <= args.max_episodes: # run an episode ep_reward, ep_agent_rewards, steps = run_episode(env, agents) if args.show: print('episode {}, reward {}, steps {}'.format( total_episodes, ep_reward, steps)) # Record reward total_steps += steps total_episodes += 1 episode_rewards.append(ep_reward) for i in range(env.n): agent_rewards[i].append(ep_agent_rewards[i]) # Keep track of final episode reward if total_episodes % args.stat_rate == 0: mean_episode_reward = np.mean(episode_rewards[-args.stat_rate:]) final_ep_rewards.append(mean_episode_reward) for rew in agent_rewards: final_ep_ag_rewards.append(np.mean(rew[-args.stat_rate:])) use_time = round(time.time() - t_start, 3) logger.info( 'Steps: {}, Episodes: {}, Mean episode reward: {}, Time: {}'. format(total_steps, total_episodes, mean_episode_reward, use_time)) t_start = time.time() summary.add_scalar('mean_episode_reward/episode', mean_episode_reward, total_episodes) summary.add_scalar('mean_episode_reward/steps', mean_episode_reward, total_steps) summary.add_scalar('use_time/1000episode', use_time, total_episodes) # save model if not args.restore: os.makedirs(os.path.dirname(args.model_dir), exist_ok=True) for i in range(len(agents)): model_name = '/agent_' + str(i) agents[i].save(args.model_dir + model_name) if __name__ == '__main__': parser = argparse.ArgumentParser() # Environment parser.add_argument( '--env', type=str, default='simple_speaker_listener', help='scenario of MultiAgentEnv') parser.add_argument( '--max_step_per_episode', type=int, default=25, help='maximum step per episode') parser.add_argument( '--max_episodes', type=int, default=25000, help='stop condition:number of episodes') parser.add_argument( '--stat_rate', type=int, default=1000, help='statistical interval of save model or count reward') # Core training parameters parser.add_argument( '--critic_lr', type=float, default=1e-3, help='learning rate for the critic model') parser.add_argument( '--actor_lr', type=float, default=1e-3, help='learning rate of the actor model') parser.add_argument( '--gamma', type=float, default=0.95, help='discount factor') parser.add_argument( '--batch_size', type=int, default=1024, help='number of episodes to optimize at the same time') parser.add_argument('--tau', type=int, default=0.01, help='soft update') # auto save model, optional restore model parser.add_argument( '--show', action='store_true', default=False, help='display or not') parser.add_argument( '--restore', action='store_true', default=False, help='restore or not, must have model_dir') parser.add_argument( '--model_dir', type=str, default='./model', help='directory for saving model') args = parser.parse_args() train_agent()
35.313559
78
0.605232
from parl.utils import check_version_for_fluid check_version_for_fluid() import os import time import argparse import numpy as np from simple_model import MAModel from simple_agent import MAAgent import parl from parl.env.multiagent_simple_env import MAenv from parl.utils import logger, summary def run_episode(env, agents): obs_n = env.reset() total_reward = 0 agents_reward = [0 for _ in range(env.n)] steps = 0 while True: steps += 1 action_n = [agent.predict(obs) for agent, obs in zip(agents, obs_n)] next_obs_n, reward_n, done_n, _ = env.step(action_n) done = all(done_n) terminal = (steps >= args.max_step_per_episode) for i, agent in enumerate(agents): agent.add_experience(obs_n[i], action_n[i], reward_n[i], next_obs_n[i], done_n[i]) obs_n = next_obs_n for i, reward in enumerate(reward_n): total_reward += reward agents_reward[i] += reward if done or terminal: break if args.show: time.sleep(0.1) env.render() if args.restore and args.show: continue for i, agent in enumerate(agents): critic_loss = agent.learn(agents) summary.add_scalar('critic_loss_%d' % i, critic_loss, agent.global_train_step) return total_reward, agents_reward, steps def train_agent(): env = MAenv(args.env) logger.info('agent num: {}'.format(env.n)) logger.info('observation_space: {}'.format(env.observation_space)) logger.info('action_space: {}'.format(env.action_space)) logger.info('obs_shape_n: {}'.format(env.obs_shape_n)) logger.info('act_shape_n: {}'.format(env.act_shape_n)) for i in range(env.n): logger.info('agent {} obs_low:{} obs_high:{}'.format( i, env.observation_space[i].low, env.observation_space[i].high)) logger.info('agent {} act_n:{}'.format(i, env.act_shape_n[i])) if ('low' in dir(env.action_space[i])): logger.info('agent {} act_low:{} act_high:{} act_shape:{}'.format( i, env.action_space[i].low, env.action_space[i].high, env.action_space[i].shape)) logger.info('num_discrete_space:{}'.format( env.action_space[i].num_discrete_space)) from gym import spaces from multiagent.multi_discrete import MultiDiscrete for space in env.action_space: assert (isinstance(space, spaces.Discrete) or isinstance(space, MultiDiscrete)) agents = [] for i in range(env.n): model = MAModel(env.act_shape_n[i]) algorithm = parl.algorithms.MADDPG( model, agent_index=i, act_space=env.action_space, gamma=args.gamma, tau=args.tau, critic_lr=args.critic_lr, actor_lr=args.actor_lr) agent = MAAgent( algorithm, agent_index=i, obs_dim_n=env.obs_shape_n, act_dim_n=env.act_shape_n, batch_size=args.batch_size, speedup=(not args.restore)) agents.append(agent) total_steps = 0 total_episodes = 0 episode_rewards = [] agent_rewards = [[] for _ in range(env.n)] final_ep_rewards = [] final_ep_ag_rewards = [] if args.restore: for i in range(len(agents)): model_file = args.model_dir + '/agent_' + str(i) if not os.path.exists(model_file): raise Exception( 'model file {} does not exits'.format(model_file)) agents[i].restore(model_file) t_start = time.time() logger.info('Starting...') while total_episodes <= args.max_episodes: ep_reward, ep_agent_rewards, steps = run_episode(env, agents) if args.show: print('episode {}, reward {}, steps {}'.format( total_episodes, ep_reward, steps)) total_steps += steps total_episodes += 1 episode_rewards.append(ep_reward) for i in range(env.n): agent_rewards[i].append(ep_agent_rewards[i]) if total_episodes % args.stat_rate == 0: mean_episode_reward = np.mean(episode_rewards[-args.stat_rate:]) final_ep_rewards.append(mean_episode_reward) for rew in agent_rewards: final_ep_ag_rewards.append(np.mean(rew[-args.stat_rate:])) use_time = round(time.time() - t_start, 3) logger.info( 'Steps: {}, Episodes: {}, Mean episode reward: {}, Time: {}'. format(total_steps, total_episodes, mean_episode_reward, use_time)) t_start = time.time() summary.add_scalar('mean_episode_reward/episode', mean_episode_reward, total_episodes) summary.add_scalar('mean_episode_reward/steps', mean_episode_reward, total_steps) summary.add_scalar('use_time/1000episode', use_time, total_episodes) if not args.restore: os.makedirs(os.path.dirname(args.model_dir), exist_ok=True) for i in range(len(agents)): model_name = '/agent_' + str(i) agents[i].save(args.model_dir + model_name) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--env', type=str, default='simple_speaker_listener', help='scenario of MultiAgentEnv') parser.add_argument( '--max_step_per_episode', type=int, default=25, help='maximum step per episode') parser.add_argument( '--max_episodes', type=int, default=25000, help='stop condition:number of episodes') parser.add_argument( '--stat_rate', type=int, default=1000, help='statistical interval of save model or count reward') parser.add_argument( '--critic_lr', type=float, default=1e-3, help='learning rate for the critic model') parser.add_argument( '--actor_lr', type=float, default=1e-3, help='learning rate of the actor model') parser.add_argument( '--gamma', type=float, default=0.95, help='discount factor') parser.add_argument( '--batch_size', type=int, default=1024, help='number of episodes to optimize at the same time') parser.add_argument('--tau', type=int, default=0.01, help='soft update') parser.add_argument( '--show', action='store_true', default=False, help='display or not') parser.add_argument( '--restore', action='store_true', default=False, help='restore or not, must have model_dir') parser.add_argument( '--model_dir', type=str, default='./model', help='directory for saving model') args = parser.parse_args() train_agent()
true
true
1c3c0a1ec48294d0382bda0f7bd55891216e2a4b
1,199
py
Python
tests/offline/test_main.py
franklouwers/maestral
18434b6f651bdf94bb06dea1575d2c036be1b451
[ "MIT" ]
1,373
2020-04-26T09:13:15.000Z
2021-12-18T07:19:52.000Z
tests/offline/test_main.py
franklouwers/maestral
18434b6f651bdf94bb06dea1575d2c036be1b451
[ "MIT" ]
300
2018-12-08T20:44:39.000Z
2021-12-16T17:42:09.000Z
tests/offline/test_main.py
franklouwers/maestral
18434b6f651bdf94bb06dea1575d2c036be1b451
[ "MIT" ]
36
2020-08-17T18:36:06.000Z
2021-11-23T22:21:51.000Z
# -*- coding: utf-8 -*- import requests import maestral.main from maestral.constants import GITHUB_RELEASES_API def test_check_for_updates(m): # get current releases from GitHub resp = requests.get(GITHUB_RELEASES_API) try: resp.raise_for_status() except Exception: # rate limit etc, connection error, etc return data = resp.json() previous_release = data[1]["tag_name"].lstrip("v") latest_stable_release = data[0]["tag_name"].lstrip("v") # check that no update is offered from current (newest) version maestral.main.__version__ = latest_stable_release update_res = m.check_for_updates() assert update_res["latest_release"] == latest_stable_release assert not update_res["update_available"] assert update_res["release_notes"] == "" assert update_res["error"] is None # check that update is offered from previous release maestral.main.__version__ = previous_release update_res = m.check_for_updates() assert update_res["latest_release"] == latest_stable_release assert update_res["update_available"] assert update_res["release_notes"] != "" assert update_res["error"] is None
26.065217
67
0.710592
import requests import maestral.main from maestral.constants import GITHUB_RELEASES_API def test_check_for_updates(m): resp = requests.get(GITHUB_RELEASES_API) try: resp.raise_for_status() except Exception: return data = resp.json() previous_release = data[1]["tag_name"].lstrip("v") latest_stable_release = data[0]["tag_name"].lstrip("v") maestral.main.__version__ = latest_stable_release update_res = m.check_for_updates() assert update_res["latest_release"] == latest_stable_release assert not update_res["update_available"] assert update_res["release_notes"] == "" assert update_res["error"] is None maestral.main.__version__ = previous_release update_res = m.check_for_updates() assert update_res["latest_release"] == latest_stable_release assert update_res["update_available"] assert update_res["release_notes"] != "" assert update_res["error"] is None
true
true
1c3c0a2de9a7a9a25a23b6dfadc1bc7963a40b1c
646
py
Python
test_save_reload_user.py
afarizap/AirBnB_clone
4155a42f631890824bc6c5613e0e3cb0f9b57069
[ "MIT" ]
1
2021-07-12T00:14:03.000Z
2021-07-12T00:14:03.000Z
test_save_reload_user.py
afarizap/AirBnB_clone
4155a42f631890824bc6c5613e0e3cb0f9b57069
[ "MIT" ]
2
2020-11-12T04:55:58.000Z
2020-11-12T05:00:57.000Z
test_save_reload_user.py
afarizap/AirBnB_clone
4155a42f631890824bc6c5613e0e3cb0f9b57069
[ "MIT" ]
2
2021-02-18T03:36:54.000Z
2021-07-09T21:01:05.000Z
#!/usr/bin/python3 from models import storage from models.base_model import BaseModel from models.user import User all_objs = storage.all() print("-- Reloaded objects --") for obj_id in all_objs.keys(): obj = all_objs[obj_id] print(obj) print("-- Create a new User --") my_user = User() my_user.first_name = "Betty" my_user.last_name = "Holberton" my_user.email = "airbnb@holbertonshool.com" my_user.password = "root" my_user.save() print(my_user) print("-- Create a new User 2 --") my_user2 = User() my_user2.first_name = "John" my_user2.email = "airbnb2@holbertonshool.com" my_user2.password = "root" my_user2.save() print(my_user2)
23.071429
45
0.729102
from models import storage from models.base_model import BaseModel from models.user import User all_objs = storage.all() print("-- Reloaded objects --") for obj_id in all_objs.keys(): obj = all_objs[obj_id] print(obj) print("-- Create a new User --") my_user = User() my_user.first_name = "Betty" my_user.last_name = "Holberton" my_user.email = "airbnb@holbertonshool.com" my_user.password = "root" my_user.save() print(my_user) print("-- Create a new User 2 --") my_user2 = User() my_user2.first_name = "John" my_user2.email = "airbnb2@holbertonshool.com" my_user2.password = "root" my_user2.save() print(my_user2)
true
true
1c3c0aaaed18d6205d74d11aadffa39d5be8f22f
7,721
py
Python
Gds/src/fprime_gds/common/gds_cli/command_send.py
SSteve/fprime
12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8
[ "Apache-2.0" ]
2
2021-02-23T06:56:03.000Z
2021-02-23T07:03:53.000Z
Gds/src/fprime_gds/common/gds_cli/command_send.py
SSteve/fprime
12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8
[ "Apache-2.0" ]
9
2021-02-21T07:27:44.000Z
2021-02-21T07:27:58.000Z
Gds/src/fprime_gds/common/gds_cli/command_send.py
SSteve/fprime
12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8
[ "Apache-2.0" ]
1
2021-02-23T17:10:44.000Z
2021-02-23T17:10:44.000Z
""" The implementation code for the command-send GDS CLI commands """ import difflib from typing import Iterable, List import fprime_gds.common.gds_cli.misc_utils as misc_utils import fprime_gds.common.gds_cli.test_api_utils as test_api_utils from fprime.common.models.serialize.type_exceptions import NotInitializedException from fprime_gds.common.data_types.cmd_data import CommandArgumentsException from fprime_gds.common.gds_cli.base_commands import QueryHistoryCommand from fprime_gds.common.pipeline.dictionaries import Dictionaries from fprime_gds.common.templates.cmd_template import CmdTemplate from fprime_gds.common.testing_fw import predicates class CommandSendCommand(QueryHistoryCommand): """ The implementation for sending a command via the GDS to the spacecraft """ @staticmethod def get_closest_commands( project_dictionary: Dictionaries, command_name: str, num: int = 3 ) -> List[str]: """ Searches for the closest matching known command(s) to the given command name. :param project_dictionary: The dictionary object for this project containing the item type definitions :param command_name: The full string name of the command to search for :param num: The maximum number of near-matches to return :return: A list of the closest matching commands (potentially empty) """ known_commands = project_dictionary.command_name.keys() closest_matches = difflib.get_close_matches(command_name, known_commands, n=num) return closest_matches @staticmethod def get_command_template( project_dictionary: Dictionaries, command_name: str ) -> CmdTemplate: """ Retrieves the command template for the given command name :param project_dictionary: The dictionary object for this project containing the item type definitions :param command_name: The full string name of the command to return a template for :return: The CmdTemplate object for the given command """ return project_dictionary.command_name[command_name] @staticmethod def get_command_help_message( project_dictionary: Dictionaries, command_name: str ) -> str: """ Returns a string showing a help message for the given GDS command. :param project_dictionary: The dictionary object for this project containing the item type definitions :param command_name: The full string name of the command to return a help message for :return: A help string for the command """ command_template = CommandSendCommand.get_command_template( project_dictionary, command_name ) return misc_utils.get_cmd_template_string(command_template) @classmethod def _get_item_list( cls, project_dictionary: Dictionaries, filter_predicate: predicates.predicate, ) -> Iterable[CmdTemplate]: """ Gets a list of available commands in the system and return them in an ID-sorted list. :param project_dictionary: The dictionary object for the project containing the command definitions :param filter_predicate: Test API predicate used to filter shown channels """ # NOTE: Trying to create a blank CmdData causes errors, so currently # just using templates (i.e. this function does nothing) create_empty_command = lambda cmd_template: cmd_template command_list = test_api_utils.get_item_list( item_dictionary=project_dictionary.command_id, search_filter=filter_predicate, template_to_data=create_empty_command, ) return command_list @classmethod def _get_upcoming_item( cls, api, filter_predicate, min_start_time="NOW", timeout=5.0, ): """ NOTE: Doesn't use _get_upcoming_item; sign that this should not use QueryHistory as a base class, and should refactor when time's available """ @classmethod def _get_item_string( cls, item: CmdTemplate, json: bool = False, ) -> str: """ Converts the given command template into a human-readable string. :param item: The CmdTemplate to convert to a string :param json: Whether or not to return a JSON representation of "temp" :return: A readable string version of "item" """ return misc_utils.get_cmd_template_string(item, json) @classmethod def _execute_command( cls, connection_info: misc_utils.ConnectionInfo, search_info: misc_utils.SearchInfo, command_name: str, arguments: List[str], ): """ Handle the command-send arguments to connect to the Test API correctly, then send the command via the Test API. For more details on these arguments, see the command-send definition at: Gds/src/fprime_gds/executables/fprime_cli.py """ dictionary, ip_address, port = tuple(connection_info) is_printing_list, ids, components, search, json = tuple(search_info) search_filter = cls._get_search_filter(ids, components, search, json) if is_printing_list: cls._log(cls._list_all_possible_items(dictionary, search_filter, json)) return # ====================================================================== pipeline, api = test_api_utils.initialize_test_api( dictionary, server_ip=ip_address, server_port=port ) # ====================================================================== try: api.send_command(command_name, arguments) except KeyError: cls._log("'%s' is not a known command" % (command_name)) close_matches = CommandSendCommand.get_closest_commands( pipeline.dictionaries, command_name ) if close_matches: cls._log("Similar known commands: {}".format(close_matches)) except NotInitializedException: temp = CommandSendCommand.get_command_template( pipeline.dictionaries, command_name ) cls._log( "'%s' requires %d arguments (%d given)" % (command_name, len(temp.get_args()), len(arguments)) ) cls._log(cls.get_command_help_message(pipeline.dictionaries, command_name)) except CommandArgumentsException as err: cls._log("Invalid arguments given; %s" % (str(err))) cls._log(cls.get_command_help_message(pipeline.dictionaries, command_name)) # ====================================================================== pipeline.disconnect() api.teardown() # ====================================================================== @classmethod def handle_arguments(cls, *args, **kwargs): """ Handle the given input arguments, then execute the command itself NOTE: This is currently just a pass-through method """ connection_info = misc_utils.ConnectionInfo( kwargs["dictionary"], kwargs["ip_address"], kwargs["port"] ) search_info = misc_utils.SearchInfo( kwargs["is_printing_list"], kwargs["ids"], kwargs["components"], kwargs["search"], kwargs["json"], ) cls._execute_command( connection_info, search_info, kwargs["command_name"], kwargs["arguments"] )
37.848039
147
0.633338
import difflib from typing import Iterable, List import fprime_gds.common.gds_cli.misc_utils as misc_utils import fprime_gds.common.gds_cli.test_api_utils as test_api_utils from fprime.common.models.serialize.type_exceptions import NotInitializedException from fprime_gds.common.data_types.cmd_data import CommandArgumentsException from fprime_gds.common.gds_cli.base_commands import QueryHistoryCommand from fprime_gds.common.pipeline.dictionaries import Dictionaries from fprime_gds.common.templates.cmd_template import CmdTemplate from fprime_gds.common.testing_fw import predicates class CommandSendCommand(QueryHistoryCommand): @staticmethod def get_closest_commands( project_dictionary: Dictionaries, command_name: str, num: int = 3 ) -> List[str]: known_commands = project_dictionary.command_name.keys() closest_matches = difflib.get_close_matches(command_name, known_commands, n=num) return closest_matches @staticmethod def get_command_template( project_dictionary: Dictionaries, command_name: str ) -> CmdTemplate: return project_dictionary.command_name[command_name] @staticmethod def get_command_help_message( project_dictionary: Dictionaries, command_name: str ) -> str: command_template = CommandSendCommand.get_command_template( project_dictionary, command_name ) return misc_utils.get_cmd_template_string(command_template) @classmethod def _get_item_list( cls, project_dictionary: Dictionaries, filter_predicate: predicates.predicate, ) -> Iterable[CmdTemplate]: create_empty_command = lambda cmd_template: cmd_template command_list = test_api_utils.get_item_list( item_dictionary=project_dictionary.command_id, search_filter=filter_predicate, template_to_data=create_empty_command, ) return command_list @classmethod def _get_upcoming_item( cls, api, filter_predicate, min_start_time="NOW", timeout=5.0, ): @classmethod def _get_item_string( cls, item: CmdTemplate, json: bool = False, ) -> str: return misc_utils.get_cmd_template_string(item, json) @classmethod def _execute_command( cls, connection_info: misc_utils.ConnectionInfo, search_info: misc_utils.SearchInfo, command_name: str, arguments: List[str], ): dictionary, ip_address, port = tuple(connection_info) is_printing_list, ids, components, search, json = tuple(search_info) search_filter = cls._get_search_filter(ids, components, search, json) if is_printing_list: cls._log(cls._list_all_possible_items(dictionary, search_filter, json)) return pipeline, api = test_api_utils.initialize_test_api( dictionary, server_ip=ip_address, server_port=port ) try: api.send_command(command_name, arguments) except KeyError: cls._log("'%s' is not a known command" % (command_name)) close_matches = CommandSendCommand.get_closest_commands( pipeline.dictionaries, command_name ) if close_matches: cls._log("Similar known commands: {}".format(close_matches)) except NotInitializedException: temp = CommandSendCommand.get_command_template( pipeline.dictionaries, command_name ) cls._log( "'%s' requires %d arguments (%d given)" % (command_name, len(temp.get_args()), len(arguments)) ) cls._log(cls.get_command_help_message(pipeline.dictionaries, command_name)) except CommandArgumentsException as err: cls._log("Invalid arguments given; %s" % (str(err))) cls._log(cls.get_command_help_message(pipeline.dictionaries, command_name)) pipeline.disconnect() api.teardown() @classmethod def handle_arguments(cls, *args, **kwargs): connection_info = misc_utils.ConnectionInfo( kwargs["dictionary"], kwargs["ip_address"], kwargs["port"] ) search_info = misc_utils.SearchInfo( kwargs["is_printing_list"], kwargs["ids"], kwargs["components"], kwargs["search"], kwargs["json"], ) cls._execute_command( connection_info, search_info, kwargs["command_name"], kwargs["arguments"] )
true
true
1c3c0ac0ba0df2cc9f85fdfde3ef47b426d2b062
916
py
Python
nngen/verify/leaky_relu.py
kindsenior/nngen
cba265b1a140f2aef7208926703782b6dac9e8be
[ "Apache-2.0" ]
null
null
null
nngen/verify/leaky_relu.py
kindsenior/nngen
cba265b1a140f2aef7208926703782b6dac9e8be
[ "Apache-2.0" ]
null
null
null
nngen/verify/leaky_relu.py
kindsenior/nngen
cba265b1a140f2aef7208926703782b6dac9e8be
[ "Apache-2.0" ]
null
null
null
from __future__ import absolute_import from __future__ import print_function from __future__ import division import numpy as np import functools def leaky_relu(features, slope, rshift, dtype=None, name=None, par=1, features_dtype=None): if rshift is None: rshift = dtype.width if dtype is not None else 31 features_point = 0 if features_dtype is None else features_dtype.point out_point = 0 if dtype is None else dtype.point out_shift = out_point - features_point negs = (features * slope) >> rshift comp = features >= 0 out_op = ((lambda x: x << out_shift) if out_shift >= 0 else (lambda x: x >> -out_shift)) ret = out_op(np.where(comp, features, negs)) return ret def get_leaky_relu_op(slope, rshift=None, dtype=None): return functools.partial(leaky_relu, slope=slope, rshift=rshift, dtype=dtype)
27.757576
74
0.676856
from __future__ import absolute_import from __future__ import print_function from __future__ import division import numpy as np import functools def leaky_relu(features, slope, rshift, dtype=None, name=None, par=1, features_dtype=None): if rshift is None: rshift = dtype.width if dtype is not None else 31 features_point = 0 if features_dtype is None else features_dtype.point out_point = 0 if dtype is None else dtype.point out_shift = out_point - features_point negs = (features * slope) >> rshift comp = features >= 0 out_op = ((lambda x: x << out_shift) if out_shift >= 0 else (lambda x: x >> -out_shift)) ret = out_op(np.where(comp, features, negs)) return ret def get_leaky_relu_op(slope, rshift=None, dtype=None): return functools.partial(leaky_relu, slope=slope, rshift=rshift, dtype=dtype)
true
true
1c3c0ac91f87c00934ec7a861efe77d8c6e2ce91
7,875
py
Python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_10_01/aio/operations/_express_route_ports_locations_operations.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
8
2021-01-13T23:44:08.000Z
2021-03-17T10:13:36.000Z
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_10_01/aio/operations/_express_route_ports_locations_operations.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
null
null
null
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_10_01/aio/operations/_express_route_ports_locations_operations.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
null
null
null
# 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 typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ExpressRoutePortsLocationsOperations: """ExpressRoutePortsLocationsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2018_10_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, **kwargs ) -> AsyncIterable["models.ExpressRoutePortsLocationListResult"]: """Retrieves all ExpressRoutePort peering locations. Does not return available bandwidths for each location. Available bandwidths can only be obtained when retrieving a specific peering location. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExpressRoutePortsLocationListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2018_10_01.models.ExpressRoutePortsLocationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.ExpressRoutePortsLocationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-10-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ExpressRoutePortsLocationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations'} # type: ignore async def get( self, location_name: str, **kwargs ) -> "models.ExpressRoutePortsLocation": """Retrieves a single ExpressRoutePort peering location, including the list of available bandwidths available at said peering location. :param location_name: Name of the requested ExpressRoutePort peering location. :type location_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ExpressRoutePortsLocation, or the result of cls(response) :rtype: ~azure.mgmt.network.v2018_10_01.models.ExpressRoutePortsLocation :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.ExpressRoutePortsLocation"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-10-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'locationName': self._serialize.url("location_name", location_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRoutePortsLocation', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations/{locationName}'} # type: ignore
47.439759
147
0.673651
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ExpressRoutePortsLocationsOperations: models = models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, **kwargs ) -> AsyncIterable["models.ExpressRoutePortsLocationListResult"]: cls = kwargs.pop('cls', None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-10-01" accept = "application/json" def prepare_request(next_link=None): header_parameters = {} header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: url = self.list.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ExpressRoutePortsLocationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations'} async def get( self, location_name: str, **kwargs ) -> "models.ExpressRoutePortsLocation": cls = kwargs.pop('cls', None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-10-01" accept = "application/json" url = self.get.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'locationName': self._serialize.url("location_name", location_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') header_parameters = {} header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRoutePortsLocation', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations/{locationName}'}
true
true
1c3c0b0b3fe76d7836b1ccbf0ff20dbbb1690314
609
py
Python
268. Missing Number.py
Muthu2093/Algorithms-practice
999434103a9098a4361104fd39cba5913860fa9d
[ "MIT" ]
null
null
null
268. Missing Number.py
Muthu2093/Algorithms-practice
999434103a9098a4361104fd39cba5913860fa9d
[ "MIT" ]
null
null
null
268. Missing Number.py
Muthu2093/Algorithms-practice
999434103a9098a4361104fd39cba5913860fa9d
[ "MIT" ]
null
null
null
## ## Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. ## Example 1: ## Input: [3,0,1] ## Output: 2 ## Example 2: ## Input: [9,6,4,2,3,5,7,0,1] ## Output: 8 ## Note: ## Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? ## class Solution: def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ exp_sum = len(nums) * (len(nums)+1)//2 actual_sum = sum(nums) return exp_sum - actual_sum
24.36
125
0.604269
true
true
1c3c0b481b5224d69161eb95f3073cb1eb07956b
6,128
py
Python
rust_ext.py
Lukasa/certitude
33845ae0a6b123f084f10c7dd27f11485dd73ca6
[ "MIT" ]
22
2015-12-23T22:30:13.000Z
2019-02-09T02:49:53.000Z
rust_ext.py
Lukasa/certitude
33845ae0a6b123f084f10c7dd27f11485dd73ca6
[ "MIT" ]
12
2015-12-23T22:31:15.000Z
2020-10-27T21:05:34.000Z
rust_ext.py
Lukasa/certitude
33845ae0a6b123f084f10c7dd27f11485dd73ca6
[ "MIT" ]
1
2016-04-25T13:12:31.000Z
2016-04-25T13:12:31.000Z
# From https://github.com/novocaine/rust-python-ext # The MIT License (MIT) # # Copyright (c) 2015 James Salter # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import print_function import platform import sys import subprocess import os.path import glob from distutils.cmd import Command from distutils.command.install_lib import install_lib import shutil class RustBuildCommand(Command): """ Command for building rust crates via cargo. Don't use this directly; use the build_rust_cmdclass factory method. """ description = "build rust crates into Python extensions" user_options = [] def _unpack_classargs(self): for k, v in self.__class__.args.items(): setattr(self, k, v) def initialize_options(self): self._unpack_classargs() def finalize_options(self): pass def run(self): if self.debug: self.debug_or_release = "--debug" else: self.debug_or_release = "--release" # Make sure that if pythonXX-sys is used, it builds against the current # executing python interpreter. bindir = os.path.dirname(sys.executable) env = os.environ # disables rust's pkg-config seeking for specified packages, # which causes pythonXX-sys to fall back to detecting the # interpreter from the path. env["PYTHON_2.7_NO_PKG_CONFIG"] = "1" env["PATH"] = bindir + os.pathsep + os.environ.get("PATH", "") # Execute cargo. try: args = (["cargo", "build", "--manifest-path", self.cargo_toml_path, self.debug_or_release, "--verbose"] + list(self.extra_cargo_args or [])) if not self.quiet: print(" ".join(args), file=sys.stderr) output = subprocess.check_output( ' '.join(args), env=env, shell=True, stderr=subprocess.STDOUT ) except subprocess.CalledProcessError as e: msg = "cargo failed with code: %d\n%s" % (e.returncode, e.output) raise Exception(msg) except OSError: raise Exception("Unable to execute 'cargo' - this package " "requires rust to be installed and cargo to be on the PATH") if not self.quiet: print(output, file=sys.stderr) # Find the shared library that cargo hopefully produced and copy # it into the build directory as if it were produced by build_cext. if self.debug: suffix = "debug" else: suffix = "release" target_dir = os.path.join(os.path.dirname(self.cargo_toml_path), "target/", suffix) if sys.platform == "win32": wildcard_so = "*.dll" elif sys.platform == "darwin": wildcard_so = "*.dylib" else: wildcard_so = "*.so" try: dylib_path = glob.glob(os.path.join(target_dir, wildcard_so))[0] except IndexError: raise Exception("rust build failed; unable to find any .dylib in %s" % target_dir) # Ask build_ext where the shared library would go if it had built it, # then copy it there. build_ext = self.get_finalized_command('build_ext') target_fname = os.path.splitext(os.path.basename(dylib_path)[3:])[0] ext_path = build_ext.get_ext_fullpath(os.path.basename(target_fname)) try: os.makedirs(os.path.dirname(ext_path)) except OSError: pass shutil.copyfile(dylib_path, ext_path) def build_rust_cmdclass(cargo_toml_path, debug=False, extra_cargo_args=None, quiet=False): """ Args: cargo_toml_path (str) The path to the cargo.toml manifest (--manifest) debug (boolean) Controls whether --debug or --release is passed to cargo. extra_carg_args (list) A list of extra argumenents to be passed to cargo. quiet (boolean) If True, doesn't echo cargo's output. Returns: A Command subclass suitable for passing to the cmdclass argument of distutils. """ # Manufacture a once-off command class here and set the params on it as # class members, which it can retrieve later in initialize_options. # This is clumsy, but distutils doesn't give you an appropriate # hook for passing params to custom command classes (and it does the # instantiation). _args = locals() class RustBuildCommand_Impl(RustBuildCommand): args = _args return RustBuildCommand_Impl class install_lib_including_rust(install_lib): """ A replacement install_lib cmdclass that remembers to build_rust during install_lib. Typically you want to use this so that the usual 'setup.py install' just works. """ def build(self): install_lib.build(self) if not self.skip_build: self.run_command('build_rust')
35.836257
88
0.640503
from __future__ import print_function import platform import sys import subprocess import os.path import glob from distutils.cmd import Command from distutils.command.install_lib import install_lib import shutil class RustBuildCommand(Command): description = "build rust crates into Python extensions" user_options = [] def _unpack_classargs(self): for k, v in self.__class__.args.items(): setattr(self, k, v) def initialize_options(self): self._unpack_classargs() def finalize_options(self): pass def run(self): if self.debug: self.debug_or_release = "--debug" else: self.debug_or_release = "--release" bindir = os.path.dirname(sys.executable) env = os.environ # which causes pythonXX-sys to fall back to detecting the # interpreter from the path. env["PYTHON_2.7_NO_PKG_CONFIG"] = "1" env["PATH"] = bindir + os.pathsep + os.environ.get("PATH", "") # Execute cargo. try: args = (["cargo", "build", "--manifest-path", self.cargo_toml_path, self.debug_or_release, "--verbose"] + list(self.extra_cargo_args or [])) if not self.quiet: print(" ".join(args), file=sys.stderr) output = subprocess.check_output( ' '.join(args), env=env, shell=True, stderr=subprocess.STDOUT ) except subprocess.CalledProcessError as e: msg = "cargo failed with code: %d\n%s" % (e.returncode, e.output) raise Exception(msg) except OSError: raise Exception("Unable to execute 'cargo' - this package " "requires rust to be installed and cargo to be on the PATH") if not self.quiet: print(output, file=sys.stderr) # Find the shared library that cargo hopefully produced and copy # it into the build directory as if it were produced by build_cext. if self.debug: suffix = "debug" else: suffix = "release" target_dir = os.path.join(os.path.dirname(self.cargo_toml_path), "target/", suffix) if sys.platform == "win32": wildcard_so = "*.dll" elif sys.platform == "darwin": wildcard_so = "*.dylib" else: wildcard_so = "*.so" try: dylib_path = glob.glob(os.path.join(target_dir, wildcard_so))[0] except IndexError: raise Exception("rust build failed; unable to find any .dylib in %s" % target_dir) # Ask build_ext where the shared library would go if it had built it, # then copy it there. build_ext = self.get_finalized_command('build_ext') target_fname = os.path.splitext(os.path.basename(dylib_path)[3:])[0] ext_path = build_ext.get_ext_fullpath(os.path.basename(target_fname)) try: os.makedirs(os.path.dirname(ext_path)) except OSError: pass shutil.copyfile(dylib_path, ext_path) def build_rust_cmdclass(cargo_toml_path, debug=False, extra_cargo_args=None, quiet=False): # Manufacture a once-off command class here and set the params on it as # class members, which it can retrieve later in initialize_options. # This is clumsy, but distutils doesn't give you an appropriate _args = locals() class RustBuildCommand_Impl(RustBuildCommand): args = _args return RustBuildCommand_Impl class install_lib_including_rust(install_lib): def build(self): install_lib.build(self) if not self.skip_build: self.run_command('build_rust')
true
true
1c3c0b517e48c8f1a6cbd38886cbcfed7779cf9b
2,500
py
Python
Data Structure/Binary Tree/Height of Binary Tree.py
smsubham/Data-Structure-Algorithms-Questions
45da68231907068ef4e4a0444ffdac69b337fa7c
[ "Apache-2.0" ]
null
null
null
Data Structure/Binary Tree/Height of Binary Tree.py
smsubham/Data-Structure-Algorithms-Questions
45da68231907068ef4e4a0444ffdac69b337fa7c
[ "Apache-2.0" ]
null
null
null
Data Structure/Binary Tree/Height of Binary Tree.py
smsubham/Data-Structure-Algorithms-Questions
45da68231907068ef4e4a0444ffdac69b337fa7c
[ "Apache-2.0" ]
null
null
null
# https://practice.geeksforgeeks.org/problems/height-of-binary-tree #User function Template for python3 ''' # Node Class: class Node: def _init_(self,val): self.data = val self.left = None self.right = None ''' class Solution: #Function to find the height of a binary tree. def maximum(a, b): if a >= b: return a else: return b def height(self, root): if node == None: return 0 return (1 + max(self.height(root.left), self.height(root.right))) #{ # Driver Code Starts #Initial Template for Python 3 from collections import deque # Tree Node class Node: def __init__(self, val): self.right = None self.data = val self.left = None # Function to Build Tree def buildTree(s): #Corner Case if(len(s)==0 or s[0]=="N"): return None # Creating list of strings from input # string after spliting by space ip=list(map(str,s.split())) # Create the root of the tree root=Node(int(ip[0])) size=0 q=deque() # Push the root to the queue q.append(root) size=size+1 # Starting from the second element i=1 while(size>0 and i<len(ip)): # Get and remove the front of the queue currNode=q[0] q.popleft() size=size-1 # Get the current node's value from the string currVal=ip[i] # If the left child is not null if(currVal!="N"): # Create the left child for the current node currNode.left=Node(int(currVal)) # Push it to the queue q.append(currNode.left) size=size+1 # For the right child i=i+1 if(i>=len(ip)): break currVal=ip[i] # If the right child is not null if(currVal!="N"): # Create the right child for the current node currNode.right=Node(int(currVal)) # Push it to the queue q.append(currNode.right) size=size+1 i=i+1 return root if __name__=="__main__": t=int(input()) for _ in range(0,t): s=input() root=buildTree(s) ob = Solution() print(ob.height(root)) # } Driver Code Ends
24.271845
73
0.5084
class Solution: def maximum(a, b): if a >= b: return a else: return b def height(self, root): if node == None: return 0 return (1 + max(self.height(root.left), self.height(root.right))) from collections import deque class Node: def __init__(self, val): self.right = None self.data = val self.left = None def buildTree(s): if(len(s)==0 or s[0]=="N"): return None ip=list(map(str,s.split())) root=Node(int(ip[0])) size=0 q=deque() q.append(root) size=size+1 i=1 while(size>0 and i<len(ip)): currNode=q[0] q.popleft() size=size-1 currVal=ip[i] # If the left child is not null if(currVal!="N"): # Create the left child for the current node currNode.left=Node(int(currVal)) # Push it to the queue q.append(currNode.left) size=size+1 # For the right child i=i+1 if(i>=len(ip)): break currVal=ip[i] # If the right child is not null if(currVal!="N"): # Create the right child for the current node currNode.right=Node(int(currVal)) # Push it to the queue q.append(currNode.right) size=size+1 i=i+1 return root if __name__=="__main__": t=int(input()) for _ in range(0,t): s=input() root=buildTree(s) ob = Solution() print(ob.height(root)) # } Driver Code Ends
true
true
1c3c0b61a272f2fc4da9624add2db582ffc59577
62,321
py
Python
web_app_utilities.py
Tak-Man/ML-rapid-text-labeling-app
3741253c4fadef6e4450ad1874c40c311344b309
[ "MIT" ]
null
null
null
web_app_utilities.py
Tak-Man/ML-rapid-text-labeling-app
3741253c4fadef6e4450ad1874c40c311344b309
[ "MIT" ]
null
null
null
web_app_utilities.py
Tak-Man/ML-rapid-text-labeling-app
3741253c4fadef6e4450ad1874c40c311344b309
[ "MIT" ]
null
null
null
import pandas as pd import random import sklearn.preprocessing as pp from datetime import datetime import itertools import re from scipy.stats import entropy import uuid import pickle import os from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans import sqlite3 from collections import Counter import numpy as np from sklearn.linear_model import SGDClassifier pd.options.display.max_columns = 50 pd.options.display.max_colwidth = 200 pd.options.display.max_colwidth = 200 pd.set_option('display.max_rows', None) RND_SEED = 45822 random.seed(RND_SEED) np.random.seed(RND_SEED) connection = sqlite3.connect('database.db', timeout=30) with open("schema.sql") as f: connection.executescript(f.read()) def get_db_connection(): conn = sqlite3.connect('database.db', timeout=30) conn.row_factory = sqlite3.Row return conn def populate_texts_table_sql(texts_list, table_name="texts", reset_labels=True): conn = get_db_connection() cur = conn.cursor() cur.execute("DELETE FROM " + table_name + ";") conn.commit() if reset_labels: for text_record in texts_list: cur.execute("INSERT INTO " + table_name + " (id, text, label) VALUES (?, ?, ?)", (text_record["id"], text_record["text"], "-")) else: for text_record in texts_list: cur.execute("INSERT INTO " + table_name + " (id, text, label) VALUES (?, ?, ?)", (text_record["id"], text_record["text"], text_record["label"])) conn.commit() conn.close() return None def get_decimal_value(name): conn = get_db_connection() query = "SELECT name, value FROM decimalValues WHERE name = '%s' ;" % name sql_table = conn.execute(query).fetchall() decimal_value = [dict(row)["value"] for row in sql_table][0] conn.close() return decimal_value def set_decimal_value(name, value): conn = get_db_connection() query = "UPDATE decimalValues SET value = %s WHERE name = '%s' ;" % (value, name) conn.execute(query) conn.commit() conn.close() return None def update_overall_quality_scores(value): current_score = get_decimal_value(name="OVERALL_QUALITY_SCORE_DECIMAL") set_decimal_value(name="OVERALL_QUALITY_SCORE_DECIMAL_PREVIOUS", value=current_score) set_decimal_value(name="OVERALL_QUALITY_SCORE_DECIMAL", value=value) return None def set_pkl(name, pkl_data, reset=False): conn = get_db_connection() cur = conn.cursor() if not reset: test_query = cur.execute('SELECT * FROM pkls WHERE name = ?', (name,)).fetchall() if len(test_query) > 0: cur.execute('DELETE FROM pkls WHERE name = ?', (name,)) query = "INSERT INTO pkls (name, data) VALUES (?, ?)" pkl_data_ = pickle.dumps(pkl_data) cur.execute(query, (name, pkl_data_)) # test_query = cur.execute('SELECT * FROM pkls WHERE name = ?', (name,)).fetchall() # test_data = pickle.loads([dict(row)["data"] for row in test_query][0]) else: cur.execute("DELETE FROM pkls WHERE name = '" + name + "';") conn.commit() conn.close() return None def get_pkl(name): try: conn = get_db_connection() cur = conn.cursor() query = "SELECT * FROM pkls WHERE name = '" + name + "';" pkl_table = cur.execute(query).fetchall() data = [dict(row)["data"] for row in pkl_table] if len(data) > 0: pkl_data = pickle.loads(data[0]) else: pkl_data = None conn.close() return pkl_data except: return None def get_text_list(table_name="texts"): conn = get_db_connection() text_list_sql = conn.execute("SELECT * FROM " + table_name).fetchall() text_list_sql = [dict(row) for row in text_list_sql] conn.close() return text_list_sql def set_text_list(label, table_name="searchResults"): conn = get_db_connection() conn.execute("UPDATE " + table_name + " SET label = '" + label + "'") conn.commit() conn.close() return None def clear_text_list(table_name="searchResults"): conn = get_db_connection() cur = conn.cursor() cur.execute("DELETE FROM " + table_name + ";") conn.commit() conn.close() return None def get_appropriate_text_list_list(text_list_full_sql, total_pages_sql, search_results_length_sql, table_limit_sql): if search_results_length_sql > 0: text_list_full_sql = get_text_list(table_name="searchResults") total_pages_sql = get_variable_value(name="SEARCH_TOTAL_PAGES") text_list_list_sql = create_text_list_list(text_list_full_sql=text_list_full_sql, sub_list_limit=table_limit_sql) return text_list_list_sql, text_list_full_sql, total_pages_sql def get_y_classes(): conn = get_db_connection() y_classes_sql = conn.execute('SELECT className FROM yClasses;').fetchall() y_classes_sql = [dict(row)["className"] for row in y_classes_sql] conn.close() return y_classes_sql def clear_y_classes(): conn = get_db_connection() conn.execute('DELETE FROM yClasses;') conn.commit() conn.close() return [] def add_y_classes(y_classses_list, begin_fresh=True): conn = get_db_connection() cur = conn.cursor() if begin_fresh: cur.execute("DELETE FROM yClasses;") for i, value in enumerate(y_classses_list): cur.execute("INSERT INTO yClasses (classId, className) VALUES (?, ?)", (i, value)) conn.commit() conn.close() return 1 def get_click_log(): conn = get_db_connection() sql_table = \ conn.execute('SELECT click_id, click_location, click_type, click_object, click_date_time FROM clickRecord;').fetchall() click_log_sql = list() for row in sql_table: dict_row = {"click_id": dict(row)["click_id"], "click_location": dict(row)["click_location"], "click_type": dict(row)["click_type"], "click_object": dict(row)["click_object"], "click_date_time" : dict(row)["click_date_time"]} click_log_sql.append(dict_row) conn.close() return click_log_sql def get_value_log(): conn = get_db_connection() sql_table = \ conn.execute('SELECT click_id, value_type, value FROM valueRecord;').fetchall() click_log_sql = list() for row in sql_table: dict_row = {"click_id": dict(row)["click_id"], "value_type": dict(row)["value_type"], "value": dict(row)["value"]} click_log_sql.append(dict_row) conn.close() return click_log_sql def reset_log_click_record_sql(): conn = get_db_connection() conn.execute("DELETE FROM clickRecord") conn.commit() conn.close() return None def reset_log_click_value_sql(): conn = get_db_connection() conn.execute("DELETE FROM valueRecord") conn.commit() conn.close() return None def add_log_click_record_sql(records): conn = get_db_connection() cur = conn.cursor() for record in records: cur.execute("""INSERT INTO clickRecord (click_id, click_location, click_type, click_object, click_date_time) VALUES (?, ?, ?, ?, ?)""", (record["click_id"], record["click_location"], record["click_type"], record["click_object"], record["click_date_time"])) conn.commit() conn.close() return None def add_log_click_value_sql(records): conn = get_db_connection() cur = conn.cursor() for record in records: cur.execute("""INSERT INTO valueRecord (click_id, value_type, value) VALUES (?, ?, ?)""", (record["click_id"], record["value_type"], record["value"])) conn.commit() conn.close() return None def get_panel_flags(): conn = get_db_connection() sql_table = conn.execute('SELECT name, value FROM initializeFlags;').fetchall() panel_flags = {dict(row)["name"]: dict(row)["value"] for row in sql_table} conn.close() return panel_flags def update_panel_flags_sql(update_flag): conn = get_db_connection() cur = conn.cursor() update_query = "UPDATE initializeFlags SET value = ? WHERE name = ?;" for name, value in update_flag.items(): cur.execute(update_query, (value, name)) conn.commit() conn.close() return None def get_texts_group_x(table_name="group1Texts"): conn = get_db_connection() sql_table = conn.execute("SELECT id, text, label FROM " + table_name + ";").fetchall() conn.close() if len(sql_table) > 0: texts_group_2 = [{"id": dict(row)["id"], "text": dict(row)["text"], "label": dict(row)["label"]} for row in sql_table] else: texts_group_2 = [] return texts_group_2 def set_texts_group_x(top_texts, table_name="group1Texts"): conn = get_db_connection() cur = conn.cursor() cur.execute("DELETE FROM " + table_name + ";") if top_texts: for record in top_texts: cur.execute("INSERT INTO " + table_name + " (id, text, label) VALUES (?, ?, ?)", (record["id"], record["text"], record["label"])) conn.commit() conn.close() return None def get_total_summary_sql(): conn = get_db_connection() sql_table = conn.execute('SELECT name, number, percentage FROM totalSummary;').fetchall() total_summary = [{"name": dict(row)["name"], "number": dict(row)["number"], "percentage": dict(row)["percentage"]} for row in sql_table] conn.close() return total_summary def set_total_summary(text_lists): labels = [text_obj["label"] for text_obj in text_lists] label_counter = Counter(labels) total_texts = len(text_lists) number_unlabeled = label_counter["-"] number_labeled = total_texts - number_unlabeled total_texts_percentage = "100.00%" if total_texts > 0: number_unlabeled_percentage = "{:.2%}".format(number_unlabeled / total_texts) number_labeled_percentage = "{:.2%}".format(number_labeled / total_texts) else: number_unlabeled_percentage = "{:.2%}".format(1.0) number_labeled_percentage = "{:.2%}".format(0.0) total_summary = list() total_summary.append({"name": "Total Texts", "number": "{:,}".format(total_texts), "percentage": total_texts_percentage}) total_summary.append({"name": "Total Unlabeled", "number": "{:,}".format(number_unlabeled), "percentage": number_unlabeled_percentage}) total_summary.append({"name": "Total Labeled", "number": "{:,}".format(number_labeled), "percentage": number_labeled_percentage}) conn = get_db_connection() cur = conn.cursor() cur.execute("DELETE FROM totalSummary;") for record in total_summary: cur.execute("INSERT INTO totalSummary (name, number, percentage) VALUES (?, ?, ?)", (record["name"], record["number"], record["percentage"])) conn.commit() conn.close() return None def get_label_summary_sql(): conn = get_db_connection() sql_table = conn.execute('SELECT name, number, percentage FROM labelSummary;').fetchall() label_summary = [{"name": dict(row)["name"], "number": dict(row)["number"], "percentage": dict(row)["percentage"]} for row in sql_table] conn.close() return label_summary def set_label_summary(text_lists): labels = [text_obj["label"] for text_obj in text_lists] label_counter = Counter(labels) total_texts = len(text_lists) label_summary = [] for key, value in label_counter.items(): label_summary.append({"name": key, "number": "{:,}".format(value), "percentage": "{:.2%}".format(value / total_texts)}) conn = get_db_connection() cur = conn.cursor() cur.execute("DELETE FROM labelSummary;") for record in label_summary: cur.execute("INSERT INTO labelSummary (name, number, percentage) VALUES (?, ?, ?)", (record["name"], record["number"], record["percentage"])) conn.commit() conn.close() return None def get_selected_text(selected_text_id, text_list_full_sql): selected_text_test = [text["text"] for text in text_list_full_sql if text["id"] == selected_text_id] if selected_text_id: if len(selected_text_test) == 0: selected_text = "" else: selected_text = selected_text_test[0] else: selected_text = "" return selected_text def create_text_list_list(text_list_full_sql, sub_list_limit): texts_list_list = \ [text_list_full_sql[i:i + sub_list_limit] for i in range(0, len(text_list_full_sql), sub_list_limit)] return texts_list_list def update_texts_list_by_id_sql(update_objs=None, selected_label=None, update_ids=None, sub_list_limit=10, update_in_place=True): conn = get_db_connection() cur = conn.cursor() if selected_label and update_ids and not update_objs: if update_in_place: update_query = "UPDATE texts SET label = ? WHERE id IN (%s)" % ",".join("?"*len(update_ids)) update_values = [selected_label] update_values.extend(update_ids) cur.execute(update_query, update_values) conn.commit() conn.close() else: cur.execute("DROP TABLE IF EXISTS temp_table;") cur.execute(""" CREATE TABLE temp_table ( id TEXT NOT NULL, text TEXT NOT NULL, label TEXT NOT NULL ); """) query = "INSERT INTO temp_table SELECT * FROM texts WHERE id IN (%s)" % ",".join("?" * len(update_ids)) cur.execute(query, update_ids) cur.execute("UPDATE temp_table SET label = ?", (selected_label, )) cur.execute("DELETE FROM texts WHERE id IN (%s)" % ",".join("?" * len(update_ids)), update_ids) cur.execute("INSERT INTO texts SELECT * FROM temp_table;") conn.commit() conn.close() elif update_objs and not selected_label and not update_ids: if update_in_place: labels = set([obj["label"] for obj in update_objs]) for label in labels: update_ids = [obj["id"] for obj in update_objs if obj["label"] == label] update_ids_sql = ", ".join(update_ids) update_query = "UPDATE texts SET label = ? WHERE id IN (%s)" % update_ids_sql conn.execute(update_query, (label, )) conn.commit() conn.close() else: cur.execute("DROP TABLE IF EXISTS temp_table;") cur.execute(""" CREATE TABLE temp_table ( id TEXT NOT NULL, text TEXT NOT NULL, label TEXT NOT NULL ); """) all_update_ids = [obj["id"] for obj in update_objs] query = "INSERT INTO temp_table SELECT * FROM texts WHERE id IN (%s)" % ",".join("?" * len(all_update_ids)) cur.execute(query, all_update_ids) labels = set([obj["label"] for obj in update_objs]) for label in labels: update_ids = [obj["id"] for obj in update_objs if obj["label"] == label] update_ids_sql = ", ".join(update_ids) update_query = "UPDATE temp_table SET label = ? WHERE id IN (%s)" % update_ids_sql conn.execute(update_query, (label,)) delete_query = "DELETE FROM texts WHERE id IN (%s)" % ",".join("?" * len(all_update_ids)) cur.execute(delete_query, all_update_ids) cur.execute("INSERT INTO texts SELECT * FROM temp_table;") conn.commit() conn.close() text_list_full = get_text_list(table_name="texts") texts_list_list = create_text_list_list(text_list_full_sql=text_list_full, sub_list_limit=sub_list_limit) return text_list_full, texts_list_list def label_all_sql(fitted_classifier, sparse_vectorized_corpus, corpus_text_ids, texts_list, label_only_unlabeled=True, sub_list_limit=50, update_in_place=True): texts_list_df = pd.DataFrame(texts_list) if not label_only_unlabeled: predictions = fitted_classifier.predict(sparse_vectorized_corpus) predictions_df = pd.DataFrame(predictions) predictions_df["id"] = corpus_text_ids labeled_text_ids = corpus_text_ids number_to_label = len(labeled_text_ids) else: label_only_these_ids = texts_list_df[texts_list_df["label"] == "-"]["id"].values keep_indices = [corpus_text_ids.index(x) for x in label_only_these_ids] number_to_label = len(keep_indices) if number_to_label > 0: if label_only_unlabeled: sparse_vectorized_corpus_alt = sparse_vectorized_corpus[keep_indices, :] predictions = fitted_classifier.predict(sparse_vectorized_corpus_alt) predictions_df = pd.DataFrame(predictions) predictions_df["id"] = label_only_these_ids labeled_text_ids = label_only_these_ids predictions_df = predictions_df.rename(columns={0: "label"}) predictions_df = predictions_df.merge(texts_list_df[["id", "text"]], left_on="id", right_on="id", how="left") predictions_df = predictions_df[["id", "text", "label"]] update_objects = predictions_df.to_dict("records") text_list_full, texts_list_list = \ update_texts_list_by_id_sql(update_objs=update_objects, selected_label=None, update_ids=None, sub_list_limit=sub_list_limit, update_in_place=update_in_place) else: text_list_full = get_text_list(table_name="texts") texts_list_list = create_text_list_list(text_list_full_sql=text_list_full, sub_list_limit=sub_list_limit) labeled_text_ids = [] return text_list_full, texts_list_list, labeled_text_ids def generate_summary_sql(text_lists): labels = [text_obj["label"] for text_obj in text_lists] label_counter = Counter(labels) total_texts = len(text_lists) number_unlabeled = label_counter["-"] number_labeled = total_texts - number_unlabeled set_total_summary(text_lists=text_lists) set_label_summary(text_lists=text_lists) set_variable(name="NUMBER_UNLABELED_TEXTS", value=number_unlabeled) summary_headline = \ "Total Labeled : {:,} / {:,} {:.1%}".format(number_labeled, total_texts, number_labeled / total_texts) set_variable(name="LABEL_SUMMARY_STRING", value=summary_headline) total_summary_sql = get_total_summary_sql() label_summary_sql = get_label_summary_sql() number_unlabeled_texts_sql = number_unlabeled label_summary_string_sql = summary_headline return total_summary_sql, label_summary_sql, number_unlabeled_texts_sql, label_summary_string_sql def set_variable(name, value): conn = get_db_connection() cur = conn.cursor() test_query = cur.execute('SELECT * FROM variables WHERE name = ?', (name,)).fetchall() if len(test_query) > 0: cur.execute('DELETE FROM variables WHERE name = ?', (name,)) query = """INSERT INTO variables (name, value) VALUES (?, ?) """ else: query = """INSERT INTO variables (name, value) VALUES (?, ?) """ cur.execute(query, (name, value)) conn.commit() conn.close() return 1 def get_variable_value(name): conn = get_db_connection() cur = conn.cursor() query = cur.execute('SELECT value FROM variables WHERE name = ?', (name,)).fetchall() value = [dict(row)["value"] for row in query] value = value[0] if name in ["TOTAL_PAGES", "NUMBER_UNLABELED_TEXTS", "MAX_CONTENT_PATH", "TEXTS_LIMIT", "TABLE_LIMIT", "MAX_FEATURES", "RND_STATE", "PREDICTIONS_NUMBER", "SEARCH_RESULTS_LENGTH", "GROUP_1_KEEP_TOP", "GROUP_3_KEEP_TOP", "CONFIRM_LABEL_ALL_TEXTS_COUNTS", "SEARCH_TOTAL_PAGES", "LABEL_ALL_BATCH_NO", "LABEL_ALL_TOTAL_BATCHES", "NUMBER_AUTO_LABELED", "LABEL_ALL_BATCH_SIZE"]: value = int(value) if name in ["KEEP_ORIGINAL", "GROUP_1_EXCLUDE_ALREADY_LABELED", "GROUP_2_EXCLUDE_ALREADY_LABELED", "PREDICTIONS_VERBOSE", "SIMILAR_TEXT_VERBOSE", "FIT_CLASSIFIER_VERBOSE", "FIRST_LABELING_FLAG", "FULL_FIT_IF_LABELS_GOT_OVERRIDDEN", "FORCE_FULL_FIT_FOR_DIFFICULT_TEXTS", "LABELS_GOT_OVERRIDDEN_FLAG", "UPDATE_TEXTS_IN_PLACE"]: if value == "True": value = True else: value = False if name in ["PREDICTIONS_PROBABILITY"]: value = float(value) conn.commit() conn.close() return value def get_difficult_texts_sql(): try: conn = get_db_connection() select_diff_texts_query = get_variable_value(name="SELECT_DIFF_TEXTS_QUERY") sql_cols_list_y_classes = get_pkl(name="SQL_COLS_LIST_Y_CLASSES") sql_table = conn.execute(select_diff_texts_query).fetchall() total_summary = list() for row in sql_table: temp_row = {col: dict(row)[col] for col in sql_cols_list_y_classes} total_summary.append(temp_row) conn.close() return total_summary except: return [] def reset_difficult_texts_sql(): try: conn = get_db_connection() cur = conn.cursor() cur.execute('DELETE FROM difficultTexts') conn.commit() conn.close() return None except: return None def get_available_datasets(): conn = get_db_connection() cur = conn.cursor() cur.execute("DELETE FROM availableDatasets;") cur.execute("INSERT INTO availableDatasets SELECT * FROM fixedDatasets;") conn.commit() conn.close() dataset_name, dataset_url, date_time, y_classes, total_summary = has_save_data() if dataset_name and date_time and y_classes and total_summary: date_at_end_check = re.findall(r"(.*)\-[0-9]{4}\-[0-9]{2}\-[0-9]{2}\-\-[0-9]{2}\-[0-9]{2}\-[0-9]{2}", dataset_name) if len(date_at_end_check) > 0: dataset_name_alt = date_at_end_check[0] else: dataset_name_alt = dataset_name conn = get_db_connection() cur = conn.cursor() cur.execute("INSERT INTO availableDatasets (name, description, url) VALUES (?, ?, ?)", (dataset_name_alt + "-" + date_time, "A partially labeled dataset having " + total_summary[2]["percentage"] + " of " + total_summary[0]["number"] + " texts labeled.", dataset_url)) conn.commit() conn.close() conn = get_db_connection() available_datasets_sql = conn.execute('SELECT * FROM availableDatasets').fetchall() conn.close() return available_datasets_sql def has_save_data(): try: dataset_name = get_pkl(name="DATASET_NAME") dataset_url = get_pkl(name="DATASET_URL") date_time = get_pkl(name="DATE_TIME") y_classes = get_pkl(name="Y_CLASSES") total_summary = get_pkl(name="TOTAL_SUMMARY") return dataset_name, dataset_url, date_time, y_classes, total_summary except: return None, None, None, None, None def get_all_predictions_sql(fitted_classifier, sparse_vectorized_corpus, corpus_text_ids, texts_list, top=5, y_classes=["earthquake", "fire", "flood", "hurricane"], verbose=False, round_to=2, format_as_percentage=False): predictions = fitted_classifier.predict_proba(sparse_vectorized_corpus) predictions_df = pd.DataFrame(predictions) y_classes = [x.replace(" ", "_") for x in y_classes] predictions_df.columns = y_classes predictions_summary = predictions_df.replace(0.0, np.NaN).mean(axis=0) predictions_df["id"] = corpus_text_ids texts_list_df = pd.DataFrame(texts_list) predictions_df = predictions_df.merge(texts_list_df, left_on="id", right_on="id") keep_cols = ["id", "text"] keep_cols.extend(y_classes) predictions_df = predictions_df[keep_cols] pred_scores = score_predictions(predictions_df[y_classes], use_entropy=True, num_labels=len(y_classes)) overall_quality = np.mean(pred_scores) overall_quality_score_decimal_sql = overall_quality predictions_df["pred_scores"] = pred_scores if round_to and not format_as_percentage: predictions_df[y_classes] = predictions_df[y_classes].round(round_to) predictions_summary = predictions_summary.round(round_to) overall_quality = overall_quality.round(round_to) if format_as_percentage: if verbose: print(">> get_all_predictions > predictions_df.head() :") print(predictions_df.head(top)) predictions_df[y_classes] = predictions_df[y_classes]\ .astype(float)\ .applymap(lambda x: "{0:.0%}".format(x)) # predictions_summary = (predictions_summary.astype(float) * 100).round(1).astype(str) + "%" overall_quality = (overall_quality.astype(float) * 100).round(1).astype(str) + "%" predictions_df = predictions_df.sort_values(["pred_scores"], ascending=[True]) if verbose: print(">> get_all_predictions > predictions_df.head() :") print(predictions_df.head(top)) print(">> get_all_predictions > predictions_df.tail() :") print(predictions_df.tail(top)) keep_cols = ["id", "text"] keep_cols.extend(y_classes) sql_cols_list = [x + ' TEXT NOT NULL' for x in keep_cols] sql_cols = ", ".join(sql_cols_list) top_texts = predictions_df.head(top)[keep_cols].to_dict("records") sql_query_1 = """ DROP TABLE IF EXISTS difficultTexts; """ sql_query_2 = """ CREATE TABLE difficultTexts ( """ + sql_cols + """ ); """ conn = get_db_connection() cur = conn.cursor() cur.execute(sql_query_1) conn.commit() cur.execute(sql_query_2) conn.commit() parameters = ", ".join(["?"] * len(keep_cols)) query = "INSERT INTO difficultTexts (" + ", ".join(keep_cols) + ") VALUES (%s)" % parameters for record in top_texts: insert_values = [value for key, value in record.items()] cur.execute(query, (insert_values)) conn.commit() conn.close() conn = get_db_connection() select_diff_texts_query = "SELECT " + ", ".join(keep_cols) + " FROM difficultTexts;" set_variable(name="SELECT_DIFF_TEXTS_QUERY", value=select_diff_texts_query) set_pkl(name="SQL_COLS_LIST_Y_CLASSES", pkl_data=keep_cols, reset=None) sql_table = conn.execute(select_diff_texts_query).fetchall() texts_group_3_sql = [] for row in sql_table: texts_group_3_sql.append({key: value for key, value in dict(row).items()}) conn.close() update_overall_quality_scores(value=overall_quality_score_decimal_sql) set_variable(name="OVERALL_QUALITY_SCORE", value=overall_quality) overall_quality_score_sql = overall_quality overall_quality_score_decimal_previous_sql = get_decimal_value(name="OVERALL_QUALITY_SCORE_DECIMAL_PREVIOUS") return texts_group_3_sql, overall_quality_score_sql, \ overall_quality_score_decimal_sql, overall_quality_score_decimal_previous_sql def get_top_predictions_sql(selected_class, fitted_classifier, sparse_vectorized_corpus, corpus_text_ids, texts_list, top=5, cutoff_proba=0.95, y_classes=["earthquake", "fire", "flood", "hurricane"], verbose=False, exclude_already_labeled=True): predictions = fitted_classifier.predict_proba(sparse_vectorized_corpus) predictions_df = pd.DataFrame(predictions) predictions_df.columns = y_classes predictions_df["id"] = corpus_text_ids keep_cols = ["id"] keep_cols.extend([selected_class]) predictions_df = predictions_df[keep_cols] predictions_df = predictions_df[predictions_df[selected_class] > cutoff_proba] predictions_df = predictions_df.sort_values([selected_class], ascending=False) if exclude_already_labeled: texts_list_df = pd.DataFrame.from_dict(texts_list) predictions_df = predictions_df.merge(texts_list_df, left_on="id", right_on="id", how="left") predictions_df = predictions_df[predictions_df["label"].isin(["-"])] if verbose: print(">> get_top_predictions > predictions_df :") print(predictions_df.head(top)) filter_list = predictions_df.head(top)["id"].values top_texts = filter_all_texts(texts_list, filter_list, exclude_already_labeled=False) set_texts_group_x(top_texts=top_texts, table_name="group2Texts") texts_group_3_sql = get_texts_group_x(table_name="group2Texts") return texts_group_3_sql def fit_classifier_sql(sparse_vectorized_corpus, corpus_text_ids, texts_list, texts_list_labeled, y_classes=["earthquake", "fire", "flood", "hurricane"], verbose=False, random_state=2584, n_jobs=-1, labels_got_overridden_flag=False, full_fit_if_labels_got_overridden=False): texts_list_labeled_df = pd.DataFrame.from_dict(texts_list_labeled) if verbose: print("texts_list_labeled_df :") print(texts_list_labeled_df.head()) ids = texts_list_labeled_df["id"].values y_train = texts_list_labeled_df["label"].values indices = [corpus_text_ids.index(x) for x in ids] X_train = sparse_vectorized_corpus[indices, :] classifier_sql = get_pkl(name="CLASSIFIER") if classifier_sql: clf = classifier_sql else: # clf = make_pipeline(StandardScaler(), SGDClassifier(max_iter=1000, tol=1e-3, random_state=2584)) clf = SGDClassifier(loss="modified_huber", max_iter=1000, tol=1e-3, random_state=random_state, n_jobs=n_jobs) if labels_got_overridden_flag: if full_fit_if_labels_got_overridden: all_texts_list_labeled_df = pd.DataFrame.from_dict(texts_list) all_texts_list_labeled_df = all_texts_list_labeled_df[~all_texts_list_labeled_df["label"].isin(["-"])] y_classes_labeled = list(set(all_texts_list_labeled_df["label"].values)) all_classes_present = all(label in y_classes_labeled for label in y_classes) clf = SGDClassifier(loss="modified_huber", max_iter=1000, tol=1e-3, random_state=random_state, n_jobs=n_jobs) ids_all = all_texts_list_labeled_df["id"].values y_train_all = all_texts_list_labeled_df["label"].values indices_all = [corpus_text_ids.index(x) for x in ids_all] X_train_all = sparse_vectorized_corpus[indices_all, :] if all_classes_present: clf.fit(X_train_all, y_train_all) else: clf.partial_fit(X_train_all, y_train_all, classes=y_classes) else: clf.partial_fit(X_train, y_train, classes=y_classes) else: clf.partial_fit(X_train, y_train, classes=y_classes) set_pkl(name="CLASSIFIER", pkl_data=clf, reset=False) return clf def load_new_data_sql(source_file, text_id_col, text_value_col, source_folder="./output/upload/", shuffle_by="kmeans", table_limit=50, texts_limit=1000, max_features=100, y_classes=["Label 1", "Label 2", "Label 3", "Label 4"], rnd_state=258): data_df = get_new_data(source_file=source_file, source_folder=source_folder, number_samples=None, random_state=rnd_state) corpus_text_ids = [str(x) for x in data_df[text_id_col].values] vectorizer = TfidfVectorizer(ngram_range=(1, 2), stop_words="english", max_features=max_features) vectorized_corpus = vectorizer.fit_transform(data_df[text_value_col].values) if shuffle_by == "kmeans": kmeans = KMeans(n_clusters=len(y_classes), random_state=rnd_state).fit(vectorized_corpus) kmeans_labels = kmeans.labels_ texts_list, adj_text_ids = convert_new_data_into_list_json(data_df, limit=texts_limit, shuffle_list=kmeans_labels, random_shuffle=False, random_state=rnd_state, id_col=text_id_col, text_col=text_value_col, label_col="label") else: texts_list, adj_text_ids = convert_new_data_into_list_json(data_df, limit=texts_limit, shuffle_list=[], random_shuffle=True, random_state=rnd_state, id_col=text_id_col, text_col=text_value_col, label_col="label") populate_texts_table_sql(texts_list=texts_list, table_name="texts") set_pkl(name="DATASET_NAME", pkl_data=None, reset=True) set_pkl(name="DATASET_NAME", pkl_data=source_file, reset=False) set_pkl(name="DATASET_URL", pkl_data=None, reset=True) set_pkl(name="DATASET_URL", pkl_data="-", reset=False) set_pkl(name="CORPUS_TEXT_IDS", pkl_data=None, reset=True) set_pkl(name="CORPUS_TEXT_IDS", pkl_data=adj_text_ids, reset=False) texts_list_list = [texts_list[i:i + table_limit] for i in range(0, len(texts_list), table_limit)] total_pages = len(texts_list_list) set_variable(name="TOTAL_PAGES", value=total_pages) set_pkl(name="TEXTS_LIST_LIST", pkl_data=None, reset=True) set_pkl(name="TEXTS_LIST_LIST", pkl_data=texts_list_list, reset=False) set_pkl(name="VECTORIZED_CORPUS", pkl_data=None, reset=True) set_pkl(name="VECTORIZED_CORPUS", pkl_data=vectorized_corpus, reset=False) set_pkl(name="VECTORIZER", pkl_data=None, reset=True) set_pkl(name="VECTORIZER", pkl_data=vectorizer, reset=False) return texts_list, texts_list_list, adj_text_ids, total_pages, vectorized_corpus, vectorizer, corpus_text_ids def load_demo_data_sql(dataset_name="Disaster Tweets Dataset", shuffle_by="kmeans", table_limit=50, texts_limit=1000, max_features=100, y_classes=["Earthquake", "Fire", "Flood", "Hurricane"], rnd_state=258): if dataset_name == "Disaster Tweets Dataset": consolidated_disaster_tweet_data_df = get_disaster_tweet_demo_data(number_samples=None, filter_data_types=["train"], random_state=rnd_state) corpus_text_ids = [str(x) for x in consolidated_disaster_tweet_data_df["tweet_id"].values] set_pkl(name="CORPUS_TEXT_IDS", pkl_data=corpus_text_ids, reset=False) vectorizer = TfidfVectorizer(ngram_range=(1, 2), stop_words="english", max_features=max_features) # https://stackoverflow.com/questions/69326639/sklearn-warnings-in-version-1-0 vectorized_corpus = \ vectorizer.fit_transform(consolidated_disaster_tweet_data_df["tweet_text"].values) set_pkl(name="VECTORIZER", pkl_data=vectorizer, reset=False) set_pkl(name="VECTORIZED_CORPUS", pkl_data=vectorized_corpus, reset=False) if shuffle_by == "kmeans": kmeans = KMeans(n_clusters=len(y_classes), random_state=rnd_state).fit(vectorized_corpus) kmeans_labels = kmeans.labels_ texts_list, adj_text_ids = convert_demo_data_into_list_json(consolidated_disaster_tweet_data_df, limit=texts_limit, keep_labels=False, shuffle_list=kmeans_labels, random_shuffle=False, random_state=rnd_state) else: texts_list, adj_text_ids = convert_demo_data_into_list_json(consolidated_disaster_tweet_data_df, limit=texts_limit, keep_labels=False, shuffle_list=[], random_shuffle=True, random_state=rnd_state) texts_list_list = [texts_list[i:i + table_limit] for i in range(0, len(texts_list), table_limit)] total_pages = len(texts_list_list) set_variable(name="TOTAL_PAGES", value=total_pages) return texts_list, texts_list_list, adj_text_ids, total_pages, vectorized_corpus, vectorizer, corpus_text_ids def generate_all_predictions_if_appropriate(n_jobs=-1, labels_got_overridden_flag=True, full_fit_if_labels_got_overridden=True, round_to=1, format_as_percentage=True): classifier_sql = get_pkl(name="CLASSIFIER") try: if classifier_sql: label_summary_sql = get_label_summary_sql() label_summary_df = pd.DataFrame.from_dict(label_summary_sql) y_classes_labeled = label_summary_df["name"].values y_classes_sql = get_y_classes() all_classes_present = all(label in y_classes_labeled for label in y_classes_sql) if all_classes_present: force_full_fit_for_difficult_texts_sql = get_variable_value(name="FORCE_FULL_FIT_FOR_DIFFICULT_TEXTS") random_state_sql = get_variable_value(name="RND_STATE") corpus_text_ids_sql = get_pkl(name="CORPUS_TEXT_IDS") vectorized_corpus_sql = get_pkl(name="VECTORIZED_CORPUS") predictions_verbose_sql = get_variable_value(name="PREDICTIONS_VERBOSE") fit_classifier_verbose_sql = get_variable_value(name="FIT_CLASSIFIER_VERBOSE") text_list_full_sql = get_text_list(table_name="texts") if force_full_fit_for_difficult_texts_sql: fit_classifier_sql(sparse_vectorized_corpus=vectorized_corpus_sql, corpus_text_ids=corpus_text_ids_sql, texts_list=text_list_full_sql, texts_list_labeled=text_list_full_sql, y_classes=y_classes_sql, verbose=fit_classifier_verbose_sql, random_state=random_state_sql, n_jobs=n_jobs, labels_got_overridden_flag=labels_got_overridden_flag, full_fit_if_labels_got_overridden=full_fit_if_labels_got_overridden) top_sql = get_variable_value(name="GROUP_3_KEEP_TOP") texts_group_3_sql, overall_quality_score_sql, \ overall_quality_score_decimal_sql, overall_quality_score_decimal_previous_sql = \ get_all_predictions_sql(fitted_classifier=classifier_sql, sparse_vectorized_corpus=vectorized_corpus_sql, corpus_text_ids=corpus_text_ids_sql, texts_list=text_list_full_sql, top=top_sql, y_classes=y_classes_sql, verbose=predictions_verbose_sql, round_to=round_to, format_as_percentage=format_as_percentage) return 1, "The difficult texts list has been generated.", \ texts_group_3_sql, overall_quality_score_sql, \ overall_quality_score_decimal_sql, overall_quality_score_decimal_previous_sql else: return 0, """Examples of all labels are not present. Label more texts then try generating the difficult text list.""", [], "-", 0.0, 0.0 else: return 0, "Label more texts then try generating the difficult text list.", [], "-", 0.0, 0.0 except: return -1, "An error occurred when trying to generate the difficult texts.", [], "-", 0.0, 0.0 def get_top_similar_texts_sql(all_texts_json, similarities_series, top=5, exclude_already_labeled=False, verbose=True): if exclude_already_labeled: all_texts_df = pd.DataFrame.from_dict(all_texts_json) similarities_df = pd.DataFrame(similarities_series).reset_index().rename(columns={0: "proba", "index": "id"}) if verbose: print(">> get_top_similar_texts > similarities_df :") print(similarities_df.head()) print(">> all_texts_df > all_texts_df :") print(all_texts_df.head()) similarities_df = similarities_df.merge(all_texts_df, left_on="id", right_on="id") similarities_df = similarities_df[similarities_df["label"].isin(["-"])] filter_list = similarities_df.head(top)["id"].values else: filter_list = similarities_series.head(top).index.values top_texts = filter_all_texts(all_texts_json, filter_list, exclude_already_labeled=False) if verbose: print(">> all_texts_df > len(top_texts) :", len(top_texts)) set_texts_group_x(top_texts=top_texts, table_name="group1Texts") return top_texts def read_new_dataset(source_file_name, text_id_col, text_value_col, source_dir="./output/upload"): try: dataset_df = pd.read_csv(os.path.join(source_dir, source_file_name)) dataset_df = dataset_df[[text_id_col, text_value_col]] dataset_df.rename(columns={text_id_col: "id", text_value_col: "text"}, inplace=True) dataset_df["label"] = "-" return 1, dataset_df except: return 0, None def load_save_state_sql(): try: save_state_json = get_pkl(name="SAVE_STATE") set_variable(name="TOTAL_PAGES", value=save_state_json["TOTAL_PAGES"]) add_y_classes(y_classses_list=save_state_json["Y_CLASSES"], begin_fresh=True) set_variable(name="SHUFFLE_BY", value=save_state_json["SHUFFLE_BY"]) set_variable(name="HTML_CONFIG_TEMPLATE", value=save_state_json["HTML_CONFIG_TEMPLATE"]) set_variable(name="DATASET_NAME", value=save_state_json["DATASET_NAME"]) set_variable(name="LABEL_ALL_BATCH_NO", value=-99) set_variable(name="LABEL_ALL_TOTAL_BATCHES", value=0) set_variable(name="NUMBER_AUTO_LABELED", value=0) set_variable(name="SEARCH_MESSAGE", value=save_state_json["SEARCH_MESSAGE"]) set_variable(name="NUMBER_UNLABELED_TEXTS", value=save_state_json["NUMBER_UNLABELED_TEXTS"]) set_variable(name="LABEL_SUMMARY_STRING", value=save_state_json["LABEL_SUMMARY_STRING"]) set_variable(name="OVERALL_QUALITY_SCORE", value=save_state_json["OVERALL_QUALITY_SCORE"]) set_variable(name="OVERALL_QUALITY_SCORE_DECIMAL", value=save_state_json["OVERALL_QUALITY_SCORE_DECIMAL"]) set_variable(name="OVERALL_QUALITY_SCORE_DECIMAL_PREVIOUS", value=save_state_json["OVERALL_QUALITY_SCORE_DECIMAL_PREVIOUS"]) set_variable(name="ALLOW_SEARCH_TO_OVERRIDE_EXISTING_LABELS", value=save_state_json["ALLOW_SEARCH_TO_OVERRIDE_EXISTING_LABELS"]) texts_list_sql = get_pkl(name="TEXTS_LIST") populate_texts_table_sql(texts_list=texts_list_sql, table_name="texts", reset_labels=False) generate_summary_sql(text_lists=texts_list_sql) return 1 except: return 0 def get_disaster_tweet_demo_data(number_samples=None, filter_data_types=None, random_state=1144, source_file="./data/consolidated_disaster_tweet_data.tsv", retry_count=5): data_df = pd.read_csv(source_file, sep="\t") for count in range(0, retry_count): if len(data_df) == 0: data_df = pd.read_csv(source_file, sep="\t") else: print("len(data_df) :", len(data_df)) break if filter_data_types: data_df = data_df[data_df["data_type"].isin(filter_data_types)] if number_samples: data_df = data_df.sample(number_samples, random_state=random_state) if filter_data_types or number_samples: data_df = data_df.reset_index(drop=True) return data_df def get_new_data(source_file, source_folder="./output/upload/", number_samples=None, random_state=1144): full_source_file_name = os.path.join(source_folder, source_file) data_df = pd.read_csv(full_source_file_name, sep=",") if number_samples: data_df = data_df.sample(number_samples, random_state=random_state) data_df = data_df.reset_index(drop=True) return data_df def convert_demo_data_into_list_json(data_df, limit=50, keep_labels=False, shuffle_list=[], random_shuffle=False, random_state=21524, new_label_col_name="assigned_label", old_label_col_name="event_type", id_col="tweet_id", text_col="tweet_text", label_col="assigned_label"): if keep_labels: data_df[new_label_col_name] = data_df[old_label_col_name] else: data_df[new_label_col_name] = "-" data_df[id_col] = data_df[id_col].values.astype(str) if len(shuffle_list) > 0: sort_index = data_df.index.values group_dict = {} for group in set(shuffle_list): group_dict[group] = [] for (group, index) in zip(shuffle_list, sort_index): group_dict[group].append(index) dictionaries = list(group_dict.values()) sort_indices = [] for sort_indices_tuple in itertools.zip_longest(*dictionaries): temp_list = [x for x in [*sort_indices_tuple] if x is not None] sort_indices.extend(temp_list) data_df = data_df.iloc[sort_indices, :] if len(shuffle_list) == 0 and random_shuffle: data_df = data_df.sample(frac=1, random_state=random_state).reset_index(drop=True) all_texts = data_df[[id_col, text_col, label_col]].values.tolist() max_length = len(all_texts) if limit < max_length: all_texts_adj = random.sample(all_texts, limit) else: all_texts_adj = all_texts all_texts_json = [{"id": text[0], "text": text[1], "label": text[2]} for text in all_texts_adj] adj_text_ids = [text[0] for text in all_texts_adj] return all_texts_json, adj_text_ids def convert_new_data_into_list_json(data_df, limit=50, shuffle_list=[], random_shuffle=False, random_state=21524, id_col="id", text_col="text", label_col="label"): data_df[id_col] = data_df[id_col].values.astype(str) data_df[label_col] = "-" if len(shuffle_list) > 0: sort_index = data_df.index.values group_dict = {} for group in set(shuffle_list): group_dict[group] = [] for (group, index) in zip(shuffle_list, sort_index): group_dict[group].append(index) dictionaries = list(group_dict.values()) sort_indices = [] for sort_indices_tuple in itertools.zip_longest(*dictionaries): temp_list = [x for x in [*sort_indices_tuple] if x is not None] sort_indices.extend(temp_list) data_df = data_df.iloc[sort_indices, :] if len(shuffle_list) == 0 and random_shuffle: data_df = data_df.sample(frac=1, random_state=random_state).reset_index(drop=True) all_texts = data_df[[id_col, text_col, label_col]].values.tolist() max_length = len(all_texts) if limit < max_length: all_texts_adj = random.sample(all_texts, limit) else: all_texts_adj = all_texts all_texts_json = [{"id": text[0], "text": text[1], "label": text[2]} for text in all_texts_adj] adj_text_ids = [text[0] for text in all_texts_adj] return all_texts_json, adj_text_ids def update_all_texts(all_texts, text_id, label): all_texts_df = pd.DataFrame(all_texts, columns=["tweet_id", "tweet_text", "assigned_label"]) all_texts_df.loc[all_texts_df["tweet_id"] == str(text_id), "assigned_label"] = label all_texts_updated = all_texts_df.values return all_texts_updated def filter_all_texts(all_text, filter_list, exclude_already_labeled=False): filtered_all_text = [] # Slow - 10,000 records - duration 0:00:31.719903 # for filter_id in filter_list: # for text in all_text: # if text["id"] == filter_id: # filtered_all_text.append(text) # Faster - 10,000 records - duration 0:00:07.619622 # [filtered_all_text.append(text) for text in all_text if text["id"] in filter_list] # Fastest - 10,000 records - duration 0:00:00.102955 all_text_df = pd.DataFrame(all_text) filtered_all_text_df = all_text_df[all_text_df["id"].isin(filter_list)] if exclude_already_labeled: filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["label"].isin(["-"])] filtered_all_text = filtered_all_text_df.to_dict("records") return filtered_all_text def search_all_texts_sql(all_text, include_search_term, exclude_search_term, allow_search_to_override_existing_labels="No", include_behavior="conjunction", exclude_behavior="disjunction", all_upper=True): all_text_df = pd.DataFrame(all_text) if allow_search_to_override_existing_labels == "No": filtered_all_text_df = all_text_df[all_text_df["label"].isin(["-"])] else: filtered_all_text_df = all_text_df if include_search_term and len(include_search_term) > 0: include_search_terms = include_search_term.split() if all_upper: if include_behavior == "disjunction": filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).str.upper().apply( lambda text: any(word.upper() in text for word in include_search_terms))] else: filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).str.upper().apply( lambda text: all(word.upper() in text for word in include_search_terms))] else: if include_behavior == "disjunction": filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).apply( lambda text: any(word in text for word in include_search_terms))] else: filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).apply( lambda text: all(word in text for word in include_search_terms))] if exclude_search_term and len(exclude_search_term) > 0: exclude_search_terms = exclude_search_term.split() if all_upper: if exclude_behavior == "disjunction": filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).str.upper().apply( lambda text: any(word.upper() not in text for word in exclude_search_terms))] else: filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).str.upper().apply( lambda text: all(word.upper() not in text for word in exclude_search_terms))] else: if exclude_behavior == "disjunction": filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).apply( lambda text: any(word not in text for word in exclude_search_terms))] else: filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).apply( lambda text: all(word not in text for word in exclude_search_terms))] filtered_all_text = filtered_all_text_df.to_dict("records") search_results_sql = filtered_all_text search_results_length_sql = len(filtered_all_text) populate_texts_table_sql(filtered_all_text, table_name="searchResults") set_variable(name="SEARCH_RESULT_LENGTH", value=search_results_length_sql) return search_results_sql, search_results_length_sql def update_texts_list(texts_list, sub_list_limit, old_obj_lst=[], new_obj_lst=[], texts_list_list=[]): updated_texts_list = texts_list if len(old_obj_lst) > 0 or len(new_obj_lst) > 0: if len(old_obj_lst) > 0: for old_obj in old_obj_lst: updated_texts_list.remove(old_obj) if len(new_obj_lst) > 0: for new_obj in new_obj_lst: updated_texts_list.append(new_obj) texts_list_list.clear() updated_texts_list_list = \ [updated_texts_list[i:i + sub_list_limit] for i in range(0, len(updated_texts_list), sub_list_limit)] texts_list_list.extend(updated_texts_list_list) return updated_texts_list, updated_texts_list_list def cosine_similarities(mat): # https://stackoverflow.com/questions/17627219/whats-the-fastest-way-in-python-to-calculate-cosine-similarity-given-sparse-mat col_normed_mat = pp.normalize(mat.tocsc(), axis=1) return col_normed_mat * col_normed_mat.T def get_all_similarities(sparse_vectorized_corpus, corpus_text_ids): # Slow - vectorized_corpus.shape : (76484, 10) - Unable to allocate 43.6 GiB for an array with shape (76484, 76484) and data type float64 # similarities = cosine_similarity(sparse_vectorized_corpus) # similarities_df = pd.DataFrame(similarities, columns=corpus_text_ids) # Faster - vectorized_corpus.shape : (76484, 10) - duration 0:01:43.129781 # similarities = cosine_similarity(sparse_vectorized_corpus, dense_output=False) # similarities_df = pd.DataFrame.sparse.from_spmatrix(similarities, columns=corpus_text_ids) # Faster - vectorized_corpus.shape : (76484, 10) - duration 0:02:03.657139 # similarities = np.dot(sparse_vectorized_corpus, sparse_vectorized_corpus.T) # similarities_df = pd.DataFrame.sparse.from_spmatrix(similarities, columns=corpus_text_ids) # Fastest - vectorized_corpus.shape : (76484, 10) - duration 0:01:59.331099 similarities = cosine_similarities(sparse_vectorized_corpus) similarities_df = pd.DataFrame.sparse.from_spmatrix(similarities, columns=corpus_text_ids) similarities_df["id"] = corpus_text_ids similarities_df = similarities_df.set_index(["id"]) return similarities_df def get_all_similarities_one_at_a_time(sparse_vectorized_corpus, corpus_text_ids, text_id, keep_original=False): text_id_index = corpus_text_ids.index(text_id) # Fastest - vectorized_corpus.shape : (76484, 10) - duration 0:01:59.331099 single_vectorized_record = sparse_vectorized_corpus[text_id_index, :] similarities = np.dot(single_vectorized_record, sparse_vectorized_corpus.T).toarray().ravel() similarities_series = pd.Series(similarities, index=corpus_text_ids) corpus_text_ids_adj = corpus_text_ids.copy() corpus_text_ids_adj.remove(text_id) similarities_series = similarities_series.filter(corpus_text_ids_adj) similarities_series.index.name = "id" similarities_series = similarities_series.sort_values(ascending=False) if keep_original: similarities_series = pd.concat([pd.Series(99.0, index=[text_id]), similarities_series]) return similarities_series def score_predictions(predictions_df, use_entropy=True, num_labels=5): prediction_values = predictions_df.values if use_entropy: all_score_combined = [] for prediction in prediction_values: qk = [1/num_labels] * num_labels all_score_combined.append(entropy(prediction, base=num_labels, qk=qk)) else: all_scores_num_non_zero = [] all_scores_std = [] for prediction in prediction_values: score_std = np.std(prediction) all_scores_std.append(score_std) score_num_non_zero = len([x for x in prediction if x > 0.0]) all_scores_num_non_zero.append(score_num_non_zero) all_score_combined = np.array(all_scores_std) / np.array(all_scores_num_non_zero) return all_score_combined def get_similarities_single_record(similarities_df, corpus_text_id): keep_indices = [x for x in similarities_df.index.values if x not in [corpus_text_id]] similarities = similarities_df[corpus_text_id] similarities = similarities.filter(keep_indices) similarities = similarities.sort_values(ascending=False) return similarities def generate_click_record(click_location, click_type, click_object, guid=None): time_stamp = datetime.now() if not guid: guid = uuid.uuid4() click_record = {"click_id": str(guid), "click_location": click_location, "click_type": click_type, "click_object": click_object, "click_date_time": time_stamp} return click_record, guid def generate_value_record(guid, value_type, value): value_record = {"click_id": str(guid), "value_type": value_type, "value": value} return value_record def add_log_record(record, log=[]): log.extend(record) return None def get_alert_message(label_summary_sql, overall_quality_score_decimal_sql, overall_quality_score_decimal_previous_sql, texts_group_3_sql): # **** Future development ************************************************************************ # This section will use these variables for future development. # The purpose is to give the user more sophisticated feedback while the user labels texts. # print("texts_group_3_sql :") # print(texts_group_3_sql) # # print(">> get_alert_message >> label_summary_sql :") # print(label_summary_sql) # **** Future development ************************************************************************ if not overall_quality_score_decimal_previous_sql and not overall_quality_score_decimal_sql: alert_message = "" elif not overall_quality_score_decimal_previous_sql and overall_quality_score_decimal_sql: if overall_quality_score_decimal_sql < 0.60: alert_message = "More labels are required to improve the overall quality score." elif overall_quality_score_decimal_sql < 0.80: alert_message = "This is a fairly good start. Keep labeling to try to get the quality score close to 100%" else: alert_message = "This is a reasonable quality score. Click on the score above to go to the difficult text section." elif overall_quality_score_decimal_previous_sql < overall_quality_score_decimal_sql: alert_message = "The quality score is improving. Keep labeling." elif overall_quality_score_decimal_previous_sql > overall_quality_score_decimal_sql: alert_message = "The quality score has dropped. Examine the texts more carefully before assigning a label." else: alert_message = "" return alert_message if __name__ == "__main__": start_time = datetime.now() print(">> Start time :", start_time.strftime("%m/%d/%Y %H:%M:%S"), "*"*100) # ***** Add code for testing the functions here ******************************************************************** # ****************************************************************************************************************** end_time = datetime.now() duration = end_time - start_time print(">> End time :", end_time.strftime("%m/%d/%Y @ %H:%M:%S"), "*"*100) print(">> Duration :", duration, "*"*100)
41.71419
141
0.631456
import pandas as pd import random import sklearn.preprocessing as pp from datetime import datetime import itertools import re from scipy.stats import entropy import uuid import pickle import os from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans import sqlite3 from collections import Counter import numpy as np from sklearn.linear_model import SGDClassifier pd.options.display.max_columns = 50 pd.options.display.max_colwidth = 200 pd.options.display.max_colwidth = 200 pd.set_option('display.max_rows', None) RND_SEED = 45822 random.seed(RND_SEED) np.random.seed(RND_SEED) connection = sqlite3.connect('database.db', timeout=30) with open("schema.sql") as f: connection.executescript(f.read()) def get_db_connection(): conn = sqlite3.connect('database.db', timeout=30) conn.row_factory = sqlite3.Row return conn def populate_texts_table_sql(texts_list, table_name="texts", reset_labels=True): conn = get_db_connection() cur = conn.cursor() cur.execute("DELETE FROM " + table_name + ";") conn.commit() if reset_labels: for text_record in texts_list: cur.execute("INSERT INTO " + table_name + " (id, text, label) VALUES (?, ?, ?)", (text_record["id"], text_record["text"], "-")) else: for text_record in texts_list: cur.execute("INSERT INTO " + table_name + " (id, text, label) VALUES (?, ?, ?)", (text_record["id"], text_record["text"], text_record["label"])) conn.commit() conn.close() return None def get_decimal_value(name): conn = get_db_connection() query = "SELECT name, value FROM decimalValues WHERE name = '%s' ;" % name sql_table = conn.execute(query).fetchall() decimal_value = [dict(row)["value"] for row in sql_table][0] conn.close() return decimal_value def set_decimal_value(name, value): conn = get_db_connection() query = "UPDATE decimalValues SET value = %s WHERE name = '%s' ;" % (value, name) conn.execute(query) conn.commit() conn.close() return None def update_overall_quality_scores(value): current_score = get_decimal_value(name="OVERALL_QUALITY_SCORE_DECIMAL") set_decimal_value(name="OVERALL_QUALITY_SCORE_DECIMAL_PREVIOUS", value=current_score) set_decimal_value(name="OVERALL_QUALITY_SCORE_DECIMAL", value=value) return None def set_pkl(name, pkl_data, reset=False): conn = get_db_connection() cur = conn.cursor() if not reset: test_query = cur.execute('SELECT * FROM pkls WHERE name = ?', (name,)).fetchall() if len(test_query) > 0: cur.execute('DELETE FROM pkls WHERE name = ?', (name,)) query = "INSERT INTO pkls (name, data) VALUES (?, ?)" pkl_data_ = pickle.dumps(pkl_data) cur.execute(query, (name, pkl_data_)) else: cur.execute("DELETE FROM pkls WHERE name = '" + name + "';") conn.commit() conn.close() return None def get_pkl(name): try: conn = get_db_connection() cur = conn.cursor() query = "SELECT * FROM pkls WHERE name = '" + name + "';" pkl_table = cur.execute(query).fetchall() data = [dict(row)["data"] for row in pkl_table] if len(data) > 0: pkl_data = pickle.loads(data[0]) else: pkl_data = None conn.close() return pkl_data except: return None def get_text_list(table_name="texts"): conn = get_db_connection() text_list_sql = conn.execute("SELECT * FROM " + table_name).fetchall() text_list_sql = [dict(row) for row in text_list_sql] conn.close() return text_list_sql def set_text_list(label, table_name="searchResults"): conn = get_db_connection() conn.execute("UPDATE " + table_name + " SET label = '" + label + "'") conn.commit() conn.close() return None def clear_text_list(table_name="searchResults"): conn = get_db_connection() cur = conn.cursor() cur.execute("DELETE FROM " + table_name + ";") conn.commit() conn.close() return None def get_appropriate_text_list_list(text_list_full_sql, total_pages_sql, search_results_length_sql, table_limit_sql): if search_results_length_sql > 0: text_list_full_sql = get_text_list(table_name="searchResults") total_pages_sql = get_variable_value(name="SEARCH_TOTAL_PAGES") text_list_list_sql = create_text_list_list(text_list_full_sql=text_list_full_sql, sub_list_limit=table_limit_sql) return text_list_list_sql, text_list_full_sql, total_pages_sql def get_y_classes(): conn = get_db_connection() y_classes_sql = conn.execute('SELECT className FROM yClasses;').fetchall() y_classes_sql = [dict(row)["className"] for row in y_classes_sql] conn.close() return y_classes_sql def clear_y_classes(): conn = get_db_connection() conn.execute('DELETE FROM yClasses;') conn.commit() conn.close() return [] def add_y_classes(y_classses_list, begin_fresh=True): conn = get_db_connection() cur = conn.cursor() if begin_fresh: cur.execute("DELETE FROM yClasses;") for i, value in enumerate(y_classses_list): cur.execute("INSERT INTO yClasses (classId, className) VALUES (?, ?)", (i, value)) conn.commit() conn.close() return 1 def get_click_log(): conn = get_db_connection() sql_table = \ conn.execute('SELECT click_id, click_location, click_type, click_object, click_date_time FROM clickRecord;').fetchall() click_log_sql = list() for row in sql_table: dict_row = {"click_id": dict(row)["click_id"], "click_location": dict(row)["click_location"], "click_type": dict(row)["click_type"], "click_object": dict(row)["click_object"], "click_date_time" : dict(row)["click_date_time"]} click_log_sql.append(dict_row) conn.close() return click_log_sql def get_value_log(): conn = get_db_connection() sql_table = \ conn.execute('SELECT click_id, value_type, value FROM valueRecord;').fetchall() click_log_sql = list() for row in sql_table: dict_row = {"click_id": dict(row)["click_id"], "value_type": dict(row)["value_type"], "value": dict(row)["value"]} click_log_sql.append(dict_row) conn.close() return click_log_sql def reset_log_click_record_sql(): conn = get_db_connection() conn.execute("DELETE FROM clickRecord") conn.commit() conn.close() return None def reset_log_click_value_sql(): conn = get_db_connection() conn.execute("DELETE FROM valueRecord") conn.commit() conn.close() return None def add_log_click_record_sql(records): conn = get_db_connection() cur = conn.cursor() for record in records: cur.execute("""INSERT INTO clickRecord (click_id, click_location, click_type, click_object, click_date_time) VALUES (?, ?, ?, ?, ?)""", (record["click_id"], record["click_location"], record["click_type"], record["click_object"], record["click_date_time"])) conn.commit() conn.close() return None def add_log_click_value_sql(records): conn = get_db_connection() cur = conn.cursor() for record in records: cur.execute("""INSERT INTO valueRecord (click_id, value_type, value) VALUES (?, ?, ?)""", (record["click_id"], record["value_type"], record["value"])) conn.commit() conn.close() return None def get_panel_flags(): conn = get_db_connection() sql_table = conn.execute('SELECT name, value FROM initializeFlags;').fetchall() panel_flags = {dict(row)["name"]: dict(row)["value"] for row in sql_table} conn.close() return panel_flags def update_panel_flags_sql(update_flag): conn = get_db_connection() cur = conn.cursor() update_query = "UPDATE initializeFlags SET value = ? WHERE name = ?;" for name, value in update_flag.items(): cur.execute(update_query, (value, name)) conn.commit() conn.close() return None def get_texts_group_x(table_name="group1Texts"): conn = get_db_connection() sql_table = conn.execute("SELECT id, text, label FROM " + table_name + ";").fetchall() conn.close() if len(sql_table) > 0: texts_group_2 = [{"id": dict(row)["id"], "text": dict(row)["text"], "label": dict(row)["label"]} for row in sql_table] else: texts_group_2 = [] return texts_group_2 def set_texts_group_x(top_texts, table_name="group1Texts"): conn = get_db_connection() cur = conn.cursor() cur.execute("DELETE FROM " + table_name + ";") if top_texts: for record in top_texts: cur.execute("INSERT INTO " + table_name + " (id, text, label) VALUES (?, ?, ?)", (record["id"], record["text"], record["label"])) conn.commit() conn.close() return None def get_total_summary_sql(): conn = get_db_connection() sql_table = conn.execute('SELECT name, number, percentage FROM totalSummary;').fetchall() total_summary = [{"name": dict(row)["name"], "number": dict(row)["number"], "percentage": dict(row)["percentage"]} for row in sql_table] conn.close() return total_summary def set_total_summary(text_lists): labels = [text_obj["label"] for text_obj in text_lists] label_counter = Counter(labels) total_texts = len(text_lists) number_unlabeled = label_counter["-"] number_labeled = total_texts - number_unlabeled total_texts_percentage = "100.00%" if total_texts > 0: number_unlabeled_percentage = "{:.2%}".format(number_unlabeled / total_texts) number_labeled_percentage = "{:.2%}".format(number_labeled / total_texts) else: number_unlabeled_percentage = "{:.2%}".format(1.0) number_labeled_percentage = "{:.2%}".format(0.0) total_summary = list() total_summary.append({"name": "Total Texts", "number": "{:,}".format(total_texts), "percentage": total_texts_percentage}) total_summary.append({"name": "Total Unlabeled", "number": "{:,}".format(number_unlabeled), "percentage": number_unlabeled_percentage}) total_summary.append({"name": "Total Labeled", "number": "{:,}".format(number_labeled), "percentage": number_labeled_percentage}) conn = get_db_connection() cur = conn.cursor() cur.execute("DELETE FROM totalSummary;") for record in total_summary: cur.execute("INSERT INTO totalSummary (name, number, percentage) VALUES (?, ?, ?)", (record["name"], record["number"], record["percentage"])) conn.commit() conn.close() return None def get_label_summary_sql(): conn = get_db_connection() sql_table = conn.execute('SELECT name, number, percentage FROM labelSummary;').fetchall() label_summary = [{"name": dict(row)["name"], "number": dict(row)["number"], "percentage": dict(row)["percentage"]} for row in sql_table] conn.close() return label_summary def set_label_summary(text_lists): labels = [text_obj["label"] for text_obj in text_lists] label_counter = Counter(labels) total_texts = len(text_lists) label_summary = [] for key, value in label_counter.items(): label_summary.append({"name": key, "number": "{:,}".format(value), "percentage": "{:.2%}".format(value / total_texts)}) conn = get_db_connection() cur = conn.cursor() cur.execute("DELETE FROM labelSummary;") for record in label_summary: cur.execute("INSERT INTO labelSummary (name, number, percentage) VALUES (?, ?, ?)", (record["name"], record["number"], record["percentage"])) conn.commit() conn.close() return None def get_selected_text(selected_text_id, text_list_full_sql): selected_text_test = [text["text"] for text in text_list_full_sql if text["id"] == selected_text_id] if selected_text_id: if len(selected_text_test) == 0: selected_text = "" else: selected_text = selected_text_test[0] else: selected_text = "" return selected_text def create_text_list_list(text_list_full_sql, sub_list_limit): texts_list_list = \ [text_list_full_sql[i:i + sub_list_limit] for i in range(0, len(text_list_full_sql), sub_list_limit)] return texts_list_list def update_texts_list_by_id_sql(update_objs=None, selected_label=None, update_ids=None, sub_list_limit=10, update_in_place=True): conn = get_db_connection() cur = conn.cursor() if selected_label and update_ids and not update_objs: if update_in_place: update_query = "UPDATE texts SET label = ? WHERE id IN (%s)" % ",".join("?"*len(update_ids)) update_values = [selected_label] update_values.extend(update_ids) cur.execute(update_query, update_values) conn.commit() conn.close() else: cur.execute("DROP TABLE IF EXISTS temp_table;") cur.execute(""" CREATE TABLE temp_table ( id TEXT NOT NULL, text TEXT NOT NULL, label TEXT NOT NULL ); """) query = "INSERT INTO temp_table SELECT * FROM texts WHERE id IN (%s)" % ",".join("?" * len(update_ids)) cur.execute(query, update_ids) cur.execute("UPDATE temp_table SET label = ?", (selected_label, )) cur.execute("DELETE FROM texts WHERE id IN (%s)" % ",".join("?" * len(update_ids)), update_ids) cur.execute("INSERT INTO texts SELECT * FROM temp_table;") conn.commit() conn.close() elif update_objs and not selected_label and not update_ids: if update_in_place: labels = set([obj["label"] for obj in update_objs]) for label in labels: update_ids = [obj["id"] for obj in update_objs if obj["label"] == label] update_ids_sql = ", ".join(update_ids) update_query = "UPDATE texts SET label = ? WHERE id IN (%s)" % update_ids_sql conn.execute(update_query, (label, )) conn.commit() conn.close() else: cur.execute("DROP TABLE IF EXISTS temp_table;") cur.execute(""" CREATE TABLE temp_table ( id TEXT NOT NULL, text TEXT NOT NULL, label TEXT NOT NULL ); """) all_update_ids = [obj["id"] for obj in update_objs] query = "INSERT INTO temp_table SELECT * FROM texts WHERE id IN (%s)" % ",".join("?" * len(all_update_ids)) cur.execute(query, all_update_ids) labels = set([obj["label"] for obj in update_objs]) for label in labels: update_ids = [obj["id"] for obj in update_objs if obj["label"] == label] update_ids_sql = ", ".join(update_ids) update_query = "UPDATE temp_table SET label = ? WHERE id IN (%s)" % update_ids_sql conn.execute(update_query, (label,)) delete_query = "DELETE FROM texts WHERE id IN (%s)" % ",".join("?" * len(all_update_ids)) cur.execute(delete_query, all_update_ids) cur.execute("INSERT INTO texts SELECT * FROM temp_table;") conn.commit() conn.close() text_list_full = get_text_list(table_name="texts") texts_list_list = create_text_list_list(text_list_full_sql=text_list_full, sub_list_limit=sub_list_limit) return text_list_full, texts_list_list def label_all_sql(fitted_classifier, sparse_vectorized_corpus, corpus_text_ids, texts_list, label_only_unlabeled=True, sub_list_limit=50, update_in_place=True): texts_list_df = pd.DataFrame(texts_list) if not label_only_unlabeled: predictions = fitted_classifier.predict(sparse_vectorized_corpus) predictions_df = pd.DataFrame(predictions) predictions_df["id"] = corpus_text_ids labeled_text_ids = corpus_text_ids number_to_label = len(labeled_text_ids) else: label_only_these_ids = texts_list_df[texts_list_df["label"] == "-"]["id"].values keep_indices = [corpus_text_ids.index(x) for x in label_only_these_ids] number_to_label = len(keep_indices) if number_to_label > 0: if label_only_unlabeled: sparse_vectorized_corpus_alt = sparse_vectorized_corpus[keep_indices, :] predictions = fitted_classifier.predict(sparse_vectorized_corpus_alt) predictions_df = pd.DataFrame(predictions) predictions_df["id"] = label_only_these_ids labeled_text_ids = label_only_these_ids predictions_df = predictions_df.rename(columns={0: "label"}) predictions_df = predictions_df.merge(texts_list_df[["id", "text"]], left_on="id", right_on="id", how="left") predictions_df = predictions_df[["id", "text", "label"]] update_objects = predictions_df.to_dict("records") text_list_full, texts_list_list = \ update_texts_list_by_id_sql(update_objs=update_objects, selected_label=None, update_ids=None, sub_list_limit=sub_list_limit, update_in_place=update_in_place) else: text_list_full = get_text_list(table_name="texts") texts_list_list = create_text_list_list(text_list_full_sql=text_list_full, sub_list_limit=sub_list_limit) labeled_text_ids = [] return text_list_full, texts_list_list, labeled_text_ids def generate_summary_sql(text_lists): labels = [text_obj["label"] for text_obj in text_lists] label_counter = Counter(labels) total_texts = len(text_lists) number_unlabeled = label_counter["-"] number_labeled = total_texts - number_unlabeled set_total_summary(text_lists=text_lists) set_label_summary(text_lists=text_lists) set_variable(name="NUMBER_UNLABELED_TEXTS", value=number_unlabeled) summary_headline = \ "Total Labeled : {:,} / {:,} {:.1%}".format(number_labeled, total_texts, number_labeled / total_texts) set_variable(name="LABEL_SUMMARY_STRING", value=summary_headline) total_summary_sql = get_total_summary_sql() label_summary_sql = get_label_summary_sql() number_unlabeled_texts_sql = number_unlabeled label_summary_string_sql = summary_headline return total_summary_sql, label_summary_sql, number_unlabeled_texts_sql, label_summary_string_sql def set_variable(name, value): conn = get_db_connection() cur = conn.cursor() test_query = cur.execute('SELECT * FROM variables WHERE name = ?', (name,)).fetchall() if len(test_query) > 0: cur.execute('DELETE FROM variables WHERE name = ?', (name,)) query = """INSERT INTO variables (name, value) VALUES (?, ?) """ else: query = """INSERT INTO variables (name, value) VALUES (?, ?) """ cur.execute(query, (name, value)) conn.commit() conn.close() return 1 def get_variable_value(name): conn = get_db_connection() cur = conn.cursor() query = cur.execute('SELECT value FROM variables WHERE name = ?', (name,)).fetchall() value = [dict(row)["value"] for row in query] value = value[0] if name in ["TOTAL_PAGES", "NUMBER_UNLABELED_TEXTS", "MAX_CONTENT_PATH", "TEXTS_LIMIT", "TABLE_LIMIT", "MAX_FEATURES", "RND_STATE", "PREDICTIONS_NUMBER", "SEARCH_RESULTS_LENGTH", "GROUP_1_KEEP_TOP", "GROUP_3_KEEP_TOP", "CONFIRM_LABEL_ALL_TEXTS_COUNTS", "SEARCH_TOTAL_PAGES", "LABEL_ALL_BATCH_NO", "LABEL_ALL_TOTAL_BATCHES", "NUMBER_AUTO_LABELED", "LABEL_ALL_BATCH_SIZE"]: value = int(value) if name in ["KEEP_ORIGINAL", "GROUP_1_EXCLUDE_ALREADY_LABELED", "GROUP_2_EXCLUDE_ALREADY_LABELED", "PREDICTIONS_VERBOSE", "SIMILAR_TEXT_VERBOSE", "FIT_CLASSIFIER_VERBOSE", "FIRST_LABELING_FLAG", "FULL_FIT_IF_LABELS_GOT_OVERRIDDEN", "FORCE_FULL_FIT_FOR_DIFFICULT_TEXTS", "LABELS_GOT_OVERRIDDEN_FLAG", "UPDATE_TEXTS_IN_PLACE"]: if value == "True": value = True else: value = False if name in ["PREDICTIONS_PROBABILITY"]: value = float(value) conn.commit() conn.close() return value def get_difficult_texts_sql(): try: conn = get_db_connection() select_diff_texts_query = get_variable_value(name="SELECT_DIFF_TEXTS_QUERY") sql_cols_list_y_classes = get_pkl(name="SQL_COLS_LIST_Y_CLASSES") sql_table = conn.execute(select_diff_texts_query).fetchall() total_summary = list() for row in sql_table: temp_row = {col: dict(row)[col] for col in sql_cols_list_y_classes} total_summary.append(temp_row) conn.close() return total_summary except: return [] def reset_difficult_texts_sql(): try: conn = get_db_connection() cur = conn.cursor() cur.execute('DELETE FROM difficultTexts') conn.commit() conn.close() return None except: return None def get_available_datasets(): conn = get_db_connection() cur = conn.cursor() cur.execute("DELETE FROM availableDatasets;") cur.execute("INSERT INTO availableDatasets SELECT * FROM fixedDatasets;") conn.commit() conn.close() dataset_name, dataset_url, date_time, y_classes, total_summary = has_save_data() if dataset_name and date_time and y_classes and total_summary: date_at_end_check = re.findall(r"(.*)\-[0-9]{4}\-[0-9]{2}\-[0-9]{2}\-\-[0-9]{2}\-[0-9]{2}\-[0-9]{2}", dataset_name) if len(date_at_end_check) > 0: dataset_name_alt = date_at_end_check[0] else: dataset_name_alt = dataset_name conn = get_db_connection() cur = conn.cursor() cur.execute("INSERT INTO availableDatasets (name, description, url) VALUES (?, ?, ?)", (dataset_name_alt + "-" + date_time, "A partially labeled dataset having " + total_summary[2]["percentage"] + " of " + total_summary[0]["number"] + " texts labeled.", dataset_url)) conn.commit() conn.close() conn = get_db_connection() available_datasets_sql = conn.execute('SELECT * FROM availableDatasets').fetchall() conn.close() return available_datasets_sql def has_save_data(): try: dataset_name = get_pkl(name="DATASET_NAME") dataset_url = get_pkl(name="DATASET_URL") date_time = get_pkl(name="DATE_TIME") y_classes = get_pkl(name="Y_CLASSES") total_summary = get_pkl(name="TOTAL_SUMMARY") return dataset_name, dataset_url, date_time, y_classes, total_summary except: return None, None, None, None, None def get_all_predictions_sql(fitted_classifier, sparse_vectorized_corpus, corpus_text_ids, texts_list, top=5, y_classes=["earthquake", "fire", "flood", "hurricane"], verbose=False, round_to=2, format_as_percentage=False): predictions = fitted_classifier.predict_proba(sparse_vectorized_corpus) predictions_df = pd.DataFrame(predictions) y_classes = [x.replace(" ", "_") for x in y_classes] predictions_df.columns = y_classes predictions_summary = predictions_df.replace(0.0, np.NaN).mean(axis=0) predictions_df["id"] = corpus_text_ids texts_list_df = pd.DataFrame(texts_list) predictions_df = predictions_df.merge(texts_list_df, left_on="id", right_on="id") keep_cols = ["id", "text"] keep_cols.extend(y_classes) predictions_df = predictions_df[keep_cols] pred_scores = score_predictions(predictions_df[y_classes], use_entropy=True, num_labels=len(y_classes)) overall_quality = np.mean(pred_scores) overall_quality_score_decimal_sql = overall_quality predictions_df["pred_scores"] = pred_scores if round_to and not format_as_percentage: predictions_df[y_classes] = predictions_df[y_classes].round(round_to) predictions_summary = predictions_summary.round(round_to) overall_quality = overall_quality.round(round_to) if format_as_percentage: if verbose: print(">> get_all_predictions > predictions_df.head() :") print(predictions_df.head(top)) predictions_df[y_classes] = predictions_df[y_classes]\ .astype(float)\ .applymap(lambda x: "{0:.0%}".format(x)) overall_quality = (overall_quality.astype(float) * 100).round(1).astype(str) + "%" predictions_df = predictions_df.sort_values(["pred_scores"], ascending=[True]) if verbose: print(">> get_all_predictions > predictions_df.head() :") print(predictions_df.head(top)) print(">> get_all_predictions > predictions_df.tail() :") print(predictions_df.tail(top)) keep_cols = ["id", "text"] keep_cols.extend(y_classes) sql_cols_list = [x + ' TEXT NOT NULL' for x in keep_cols] sql_cols = ", ".join(sql_cols_list) top_texts = predictions_df.head(top)[keep_cols].to_dict("records") sql_query_1 = """ DROP TABLE IF EXISTS difficultTexts; """ sql_query_2 = """ CREATE TABLE difficultTexts ( """ + sql_cols + """ ); """ conn = get_db_connection() cur = conn.cursor() cur.execute(sql_query_1) conn.commit() cur.execute(sql_query_2) conn.commit() parameters = ", ".join(["?"] * len(keep_cols)) query = "INSERT INTO difficultTexts (" + ", ".join(keep_cols) + ") VALUES (%s)" % parameters for record in top_texts: insert_values = [value for key, value in record.items()] cur.execute(query, (insert_values)) conn.commit() conn.close() conn = get_db_connection() select_diff_texts_query = "SELECT " + ", ".join(keep_cols) + " FROM difficultTexts;" set_variable(name="SELECT_DIFF_TEXTS_QUERY", value=select_diff_texts_query) set_pkl(name="SQL_COLS_LIST_Y_CLASSES", pkl_data=keep_cols, reset=None) sql_table = conn.execute(select_diff_texts_query).fetchall() texts_group_3_sql = [] for row in sql_table: texts_group_3_sql.append({key: value for key, value in dict(row).items()}) conn.close() update_overall_quality_scores(value=overall_quality_score_decimal_sql) set_variable(name="OVERALL_QUALITY_SCORE", value=overall_quality) overall_quality_score_sql = overall_quality overall_quality_score_decimal_previous_sql = get_decimal_value(name="OVERALL_QUALITY_SCORE_DECIMAL_PREVIOUS") return texts_group_3_sql, overall_quality_score_sql, \ overall_quality_score_decimal_sql, overall_quality_score_decimal_previous_sql def get_top_predictions_sql(selected_class, fitted_classifier, sparse_vectorized_corpus, corpus_text_ids, texts_list, top=5, cutoff_proba=0.95, y_classes=["earthquake", "fire", "flood", "hurricane"], verbose=False, exclude_already_labeled=True): predictions = fitted_classifier.predict_proba(sparse_vectorized_corpus) predictions_df = pd.DataFrame(predictions) predictions_df.columns = y_classes predictions_df["id"] = corpus_text_ids keep_cols = ["id"] keep_cols.extend([selected_class]) predictions_df = predictions_df[keep_cols] predictions_df = predictions_df[predictions_df[selected_class] > cutoff_proba] predictions_df = predictions_df.sort_values([selected_class], ascending=False) if exclude_already_labeled: texts_list_df = pd.DataFrame.from_dict(texts_list) predictions_df = predictions_df.merge(texts_list_df, left_on="id", right_on="id", how="left") predictions_df = predictions_df[predictions_df["label"].isin(["-"])] if verbose: print(">> get_top_predictions > predictions_df :") print(predictions_df.head(top)) filter_list = predictions_df.head(top)["id"].values top_texts = filter_all_texts(texts_list, filter_list, exclude_already_labeled=False) set_texts_group_x(top_texts=top_texts, table_name="group2Texts") texts_group_3_sql = get_texts_group_x(table_name="group2Texts") return texts_group_3_sql def fit_classifier_sql(sparse_vectorized_corpus, corpus_text_ids, texts_list, texts_list_labeled, y_classes=["earthquake", "fire", "flood", "hurricane"], verbose=False, random_state=2584, n_jobs=-1, labels_got_overridden_flag=False, full_fit_if_labels_got_overridden=False): texts_list_labeled_df = pd.DataFrame.from_dict(texts_list_labeled) if verbose: print("texts_list_labeled_df :") print(texts_list_labeled_df.head()) ids = texts_list_labeled_df["id"].values y_train = texts_list_labeled_df["label"].values indices = [corpus_text_ids.index(x) for x in ids] X_train = sparse_vectorized_corpus[indices, :] classifier_sql = get_pkl(name="CLASSIFIER") if classifier_sql: clf = classifier_sql else: clf = SGDClassifier(loss="modified_huber", max_iter=1000, tol=1e-3, random_state=random_state, n_jobs=n_jobs) if labels_got_overridden_flag: if full_fit_if_labels_got_overridden: all_texts_list_labeled_df = pd.DataFrame.from_dict(texts_list) all_texts_list_labeled_df = all_texts_list_labeled_df[~all_texts_list_labeled_df["label"].isin(["-"])] y_classes_labeled = list(set(all_texts_list_labeled_df["label"].values)) all_classes_present = all(label in y_classes_labeled for label in y_classes) clf = SGDClassifier(loss="modified_huber", max_iter=1000, tol=1e-3, random_state=random_state, n_jobs=n_jobs) ids_all = all_texts_list_labeled_df["id"].values y_train_all = all_texts_list_labeled_df["label"].values indices_all = [corpus_text_ids.index(x) for x in ids_all] X_train_all = sparse_vectorized_corpus[indices_all, :] if all_classes_present: clf.fit(X_train_all, y_train_all) else: clf.partial_fit(X_train_all, y_train_all, classes=y_classes) else: clf.partial_fit(X_train, y_train, classes=y_classes) else: clf.partial_fit(X_train, y_train, classes=y_classes) set_pkl(name="CLASSIFIER", pkl_data=clf, reset=False) return clf def load_new_data_sql(source_file, text_id_col, text_value_col, source_folder="./output/upload/", shuffle_by="kmeans", table_limit=50, texts_limit=1000, max_features=100, y_classes=["Label 1", "Label 2", "Label 3", "Label 4"], rnd_state=258): data_df = get_new_data(source_file=source_file, source_folder=source_folder, number_samples=None, random_state=rnd_state) corpus_text_ids = [str(x) for x in data_df[text_id_col].values] vectorizer = TfidfVectorizer(ngram_range=(1, 2), stop_words="english", max_features=max_features) vectorized_corpus = vectorizer.fit_transform(data_df[text_value_col].values) if shuffle_by == "kmeans": kmeans = KMeans(n_clusters=len(y_classes), random_state=rnd_state).fit(vectorized_corpus) kmeans_labels = kmeans.labels_ texts_list, adj_text_ids = convert_new_data_into_list_json(data_df, limit=texts_limit, shuffle_list=kmeans_labels, random_shuffle=False, random_state=rnd_state, id_col=text_id_col, text_col=text_value_col, label_col="label") else: texts_list, adj_text_ids = convert_new_data_into_list_json(data_df, limit=texts_limit, shuffle_list=[], random_shuffle=True, random_state=rnd_state, id_col=text_id_col, text_col=text_value_col, label_col="label") populate_texts_table_sql(texts_list=texts_list, table_name="texts") set_pkl(name="DATASET_NAME", pkl_data=None, reset=True) set_pkl(name="DATASET_NAME", pkl_data=source_file, reset=False) set_pkl(name="DATASET_URL", pkl_data=None, reset=True) set_pkl(name="DATASET_URL", pkl_data="-", reset=False) set_pkl(name="CORPUS_TEXT_IDS", pkl_data=None, reset=True) set_pkl(name="CORPUS_TEXT_IDS", pkl_data=adj_text_ids, reset=False) texts_list_list = [texts_list[i:i + table_limit] for i in range(0, len(texts_list), table_limit)] total_pages = len(texts_list_list) set_variable(name="TOTAL_PAGES", value=total_pages) set_pkl(name="TEXTS_LIST_LIST", pkl_data=None, reset=True) set_pkl(name="TEXTS_LIST_LIST", pkl_data=texts_list_list, reset=False) set_pkl(name="VECTORIZED_CORPUS", pkl_data=None, reset=True) set_pkl(name="VECTORIZED_CORPUS", pkl_data=vectorized_corpus, reset=False) set_pkl(name="VECTORIZER", pkl_data=None, reset=True) set_pkl(name="VECTORIZER", pkl_data=vectorizer, reset=False) return texts_list, texts_list_list, adj_text_ids, total_pages, vectorized_corpus, vectorizer, corpus_text_ids def load_demo_data_sql(dataset_name="Disaster Tweets Dataset", shuffle_by="kmeans", table_limit=50, texts_limit=1000, max_features=100, y_classes=["Earthquake", "Fire", "Flood", "Hurricane"], rnd_state=258): if dataset_name == "Disaster Tweets Dataset": consolidated_disaster_tweet_data_df = get_disaster_tweet_demo_data(number_samples=None, filter_data_types=["train"], random_state=rnd_state) corpus_text_ids = [str(x) for x in consolidated_disaster_tweet_data_df["tweet_id"].values] set_pkl(name="CORPUS_TEXT_IDS", pkl_data=corpus_text_ids, reset=False) vectorizer = TfidfVectorizer(ngram_range=(1, 2), stop_words="english", max_features=max_features) vectorized_corpus = \ vectorizer.fit_transform(consolidated_disaster_tweet_data_df["tweet_text"].values) set_pkl(name="VECTORIZER", pkl_data=vectorizer, reset=False) set_pkl(name="VECTORIZED_CORPUS", pkl_data=vectorized_corpus, reset=False) if shuffle_by == "kmeans": kmeans = KMeans(n_clusters=len(y_classes), random_state=rnd_state).fit(vectorized_corpus) kmeans_labels = kmeans.labels_ texts_list, adj_text_ids = convert_demo_data_into_list_json(consolidated_disaster_tweet_data_df, limit=texts_limit, keep_labels=False, shuffle_list=kmeans_labels, random_shuffle=False, random_state=rnd_state) else: texts_list, adj_text_ids = convert_demo_data_into_list_json(consolidated_disaster_tweet_data_df, limit=texts_limit, keep_labels=False, shuffle_list=[], random_shuffle=True, random_state=rnd_state) texts_list_list = [texts_list[i:i + table_limit] for i in range(0, len(texts_list), table_limit)] total_pages = len(texts_list_list) set_variable(name="TOTAL_PAGES", value=total_pages) return texts_list, texts_list_list, adj_text_ids, total_pages, vectorized_corpus, vectorizer, corpus_text_ids def generate_all_predictions_if_appropriate(n_jobs=-1, labels_got_overridden_flag=True, full_fit_if_labels_got_overridden=True, round_to=1, format_as_percentage=True): classifier_sql = get_pkl(name="CLASSIFIER") try: if classifier_sql: label_summary_sql = get_label_summary_sql() label_summary_df = pd.DataFrame.from_dict(label_summary_sql) y_classes_labeled = label_summary_df["name"].values y_classes_sql = get_y_classes() all_classes_present = all(label in y_classes_labeled for label in y_classes_sql) if all_classes_present: force_full_fit_for_difficult_texts_sql = get_variable_value(name="FORCE_FULL_FIT_FOR_DIFFICULT_TEXTS") random_state_sql = get_variable_value(name="RND_STATE") corpus_text_ids_sql = get_pkl(name="CORPUS_TEXT_IDS") vectorized_corpus_sql = get_pkl(name="VECTORIZED_CORPUS") predictions_verbose_sql = get_variable_value(name="PREDICTIONS_VERBOSE") fit_classifier_verbose_sql = get_variable_value(name="FIT_CLASSIFIER_VERBOSE") text_list_full_sql = get_text_list(table_name="texts") if force_full_fit_for_difficult_texts_sql: fit_classifier_sql(sparse_vectorized_corpus=vectorized_corpus_sql, corpus_text_ids=corpus_text_ids_sql, texts_list=text_list_full_sql, texts_list_labeled=text_list_full_sql, y_classes=y_classes_sql, verbose=fit_classifier_verbose_sql, random_state=random_state_sql, n_jobs=n_jobs, labels_got_overridden_flag=labels_got_overridden_flag, full_fit_if_labels_got_overridden=full_fit_if_labels_got_overridden) top_sql = get_variable_value(name="GROUP_3_KEEP_TOP") texts_group_3_sql, overall_quality_score_sql, \ overall_quality_score_decimal_sql, overall_quality_score_decimal_previous_sql = \ get_all_predictions_sql(fitted_classifier=classifier_sql, sparse_vectorized_corpus=vectorized_corpus_sql, corpus_text_ids=corpus_text_ids_sql, texts_list=text_list_full_sql, top=top_sql, y_classes=y_classes_sql, verbose=predictions_verbose_sql, round_to=round_to, format_as_percentage=format_as_percentage) return 1, "The difficult texts list has been generated.", \ texts_group_3_sql, overall_quality_score_sql, \ overall_quality_score_decimal_sql, overall_quality_score_decimal_previous_sql else: return 0, """Examples of all labels are not present. Label more texts then try generating the difficult text list.""", [], "-", 0.0, 0.0 else: return 0, "Label more texts then try generating the difficult text list.", [], "-", 0.0, 0.0 except: return -1, "An error occurred when trying to generate the difficult texts.", [], "-", 0.0, 0.0 def get_top_similar_texts_sql(all_texts_json, similarities_series, top=5, exclude_already_labeled=False, verbose=True): if exclude_already_labeled: all_texts_df = pd.DataFrame.from_dict(all_texts_json) similarities_df = pd.DataFrame(similarities_series).reset_index().rename(columns={0: "proba", "index": "id"}) if verbose: print(">> get_top_similar_texts > similarities_df :") print(similarities_df.head()) print(">> all_texts_df > all_texts_df :") print(all_texts_df.head()) similarities_df = similarities_df.merge(all_texts_df, left_on="id", right_on="id") similarities_df = similarities_df[similarities_df["label"].isin(["-"])] filter_list = similarities_df.head(top)["id"].values else: filter_list = similarities_series.head(top).index.values top_texts = filter_all_texts(all_texts_json, filter_list, exclude_already_labeled=False) if verbose: print(">> all_texts_df > len(top_texts) :", len(top_texts)) set_texts_group_x(top_texts=top_texts, table_name="group1Texts") return top_texts def read_new_dataset(source_file_name, text_id_col, text_value_col, source_dir="./output/upload"): try: dataset_df = pd.read_csv(os.path.join(source_dir, source_file_name)) dataset_df = dataset_df[[text_id_col, text_value_col]] dataset_df.rename(columns={text_id_col: "id", text_value_col: "text"}, inplace=True) dataset_df["label"] = "-" return 1, dataset_df except: return 0, None def load_save_state_sql(): try: save_state_json = get_pkl(name="SAVE_STATE") set_variable(name="TOTAL_PAGES", value=save_state_json["TOTAL_PAGES"]) add_y_classes(y_classses_list=save_state_json["Y_CLASSES"], begin_fresh=True) set_variable(name="SHUFFLE_BY", value=save_state_json["SHUFFLE_BY"]) set_variable(name="HTML_CONFIG_TEMPLATE", value=save_state_json["HTML_CONFIG_TEMPLATE"]) set_variable(name="DATASET_NAME", value=save_state_json["DATASET_NAME"]) set_variable(name="LABEL_ALL_BATCH_NO", value=-99) set_variable(name="LABEL_ALL_TOTAL_BATCHES", value=0) set_variable(name="NUMBER_AUTO_LABELED", value=0) set_variable(name="SEARCH_MESSAGE", value=save_state_json["SEARCH_MESSAGE"]) set_variable(name="NUMBER_UNLABELED_TEXTS", value=save_state_json["NUMBER_UNLABELED_TEXTS"]) set_variable(name="LABEL_SUMMARY_STRING", value=save_state_json["LABEL_SUMMARY_STRING"]) set_variable(name="OVERALL_QUALITY_SCORE", value=save_state_json["OVERALL_QUALITY_SCORE"]) set_variable(name="OVERALL_QUALITY_SCORE_DECIMAL", value=save_state_json["OVERALL_QUALITY_SCORE_DECIMAL"]) set_variable(name="OVERALL_QUALITY_SCORE_DECIMAL_PREVIOUS", value=save_state_json["OVERALL_QUALITY_SCORE_DECIMAL_PREVIOUS"]) set_variable(name="ALLOW_SEARCH_TO_OVERRIDE_EXISTING_LABELS", value=save_state_json["ALLOW_SEARCH_TO_OVERRIDE_EXISTING_LABELS"]) texts_list_sql = get_pkl(name="TEXTS_LIST") populate_texts_table_sql(texts_list=texts_list_sql, table_name="texts", reset_labels=False) generate_summary_sql(text_lists=texts_list_sql) return 1 except: return 0 def get_disaster_tweet_demo_data(number_samples=None, filter_data_types=None, random_state=1144, source_file="./data/consolidated_disaster_tweet_data.tsv", retry_count=5): data_df = pd.read_csv(source_file, sep="\t") for count in range(0, retry_count): if len(data_df) == 0: data_df = pd.read_csv(source_file, sep="\t") else: print("len(data_df) :", len(data_df)) break if filter_data_types: data_df = data_df[data_df["data_type"].isin(filter_data_types)] if number_samples: data_df = data_df.sample(number_samples, random_state=random_state) if filter_data_types or number_samples: data_df = data_df.reset_index(drop=True) return data_df def get_new_data(source_file, source_folder="./output/upload/", number_samples=None, random_state=1144): full_source_file_name = os.path.join(source_folder, source_file) data_df = pd.read_csv(full_source_file_name, sep=",") if number_samples: data_df = data_df.sample(number_samples, random_state=random_state) data_df = data_df.reset_index(drop=True) return data_df def convert_demo_data_into_list_json(data_df, limit=50, keep_labels=False, shuffle_list=[], random_shuffle=False, random_state=21524, new_label_col_name="assigned_label", old_label_col_name="event_type", id_col="tweet_id", text_col="tweet_text", label_col="assigned_label"): if keep_labels: data_df[new_label_col_name] = data_df[old_label_col_name] else: data_df[new_label_col_name] = "-" data_df[id_col] = data_df[id_col].values.astype(str) if len(shuffle_list) > 0: sort_index = data_df.index.values group_dict = {} for group in set(shuffle_list): group_dict[group] = [] for (group, index) in zip(shuffle_list, sort_index): group_dict[group].append(index) dictionaries = list(group_dict.values()) sort_indices = [] for sort_indices_tuple in itertools.zip_longest(*dictionaries): temp_list = [x for x in [*sort_indices_tuple] if x is not None] sort_indices.extend(temp_list) data_df = data_df.iloc[sort_indices, :] if len(shuffle_list) == 0 and random_shuffle: data_df = data_df.sample(frac=1, random_state=random_state).reset_index(drop=True) all_texts = data_df[[id_col, text_col, label_col]].values.tolist() max_length = len(all_texts) if limit < max_length: all_texts_adj = random.sample(all_texts, limit) else: all_texts_adj = all_texts all_texts_json = [{"id": text[0], "text": text[1], "label": text[2]} for text in all_texts_adj] adj_text_ids = [text[0] for text in all_texts_adj] return all_texts_json, adj_text_ids def convert_new_data_into_list_json(data_df, limit=50, shuffle_list=[], random_shuffle=False, random_state=21524, id_col="id", text_col="text", label_col="label"): data_df[id_col] = data_df[id_col].values.astype(str) data_df[label_col] = "-" if len(shuffle_list) > 0: sort_index = data_df.index.values group_dict = {} for group in set(shuffle_list): group_dict[group] = [] for (group, index) in zip(shuffle_list, sort_index): group_dict[group].append(index) dictionaries = list(group_dict.values()) sort_indices = [] for sort_indices_tuple in itertools.zip_longest(*dictionaries): temp_list = [x for x in [*sort_indices_tuple] if x is not None] sort_indices.extend(temp_list) data_df = data_df.iloc[sort_indices, :] if len(shuffle_list) == 0 and random_shuffle: data_df = data_df.sample(frac=1, random_state=random_state).reset_index(drop=True) all_texts = data_df[[id_col, text_col, label_col]].values.tolist() max_length = len(all_texts) if limit < max_length: all_texts_adj = random.sample(all_texts, limit) else: all_texts_adj = all_texts all_texts_json = [{"id": text[0], "text": text[1], "label": text[2]} for text in all_texts_adj] adj_text_ids = [text[0] for text in all_texts_adj] return all_texts_json, adj_text_ids def update_all_texts(all_texts, text_id, label): all_texts_df = pd.DataFrame(all_texts, columns=["tweet_id", "tweet_text", "assigned_label"]) all_texts_df.loc[all_texts_df["tweet_id"] == str(text_id), "assigned_label"] = label all_texts_updated = all_texts_df.values return all_texts_updated def filter_all_texts(all_text, filter_list, exclude_already_labeled=False): filtered_all_text = [] all_text_df = pd.DataFrame(all_text) filtered_all_text_df = all_text_df[all_text_df["id"].isin(filter_list)] if exclude_already_labeled: filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["label"].isin(["-"])] filtered_all_text = filtered_all_text_df.to_dict("records") return filtered_all_text def search_all_texts_sql(all_text, include_search_term, exclude_search_term, allow_search_to_override_existing_labels="No", include_behavior="conjunction", exclude_behavior="disjunction", all_upper=True): all_text_df = pd.DataFrame(all_text) if allow_search_to_override_existing_labels == "No": filtered_all_text_df = all_text_df[all_text_df["label"].isin(["-"])] else: filtered_all_text_df = all_text_df if include_search_term and len(include_search_term) > 0: include_search_terms = include_search_term.split() if all_upper: if include_behavior == "disjunction": filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).str.upper().apply( lambda text: any(word.upper() in text for word in include_search_terms))] else: filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).str.upper().apply( lambda text: all(word.upper() in text for word in include_search_terms))] else: if include_behavior == "disjunction": filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).apply( lambda text: any(word in text for word in include_search_terms))] else: filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).apply( lambda text: all(word in text for word in include_search_terms))] if exclude_search_term and len(exclude_search_term) > 0: exclude_search_terms = exclude_search_term.split() if all_upper: if exclude_behavior == "disjunction": filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).str.upper().apply( lambda text: any(word.upper() not in text for word in exclude_search_terms))] else: filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).str.upper().apply( lambda text: all(word.upper() not in text for word in exclude_search_terms))] else: if exclude_behavior == "disjunction": filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).apply( lambda text: any(word not in text for word in exclude_search_terms))] else: filtered_all_text_df = filtered_all_text_df[filtered_all_text_df["text"].astype(str).apply( lambda text: all(word not in text for word in exclude_search_terms))] filtered_all_text = filtered_all_text_df.to_dict("records") search_results_sql = filtered_all_text search_results_length_sql = len(filtered_all_text) populate_texts_table_sql(filtered_all_text, table_name="searchResults") set_variable(name="SEARCH_RESULT_LENGTH", value=search_results_length_sql) return search_results_sql, search_results_length_sql def update_texts_list(texts_list, sub_list_limit, old_obj_lst=[], new_obj_lst=[], texts_list_list=[]): updated_texts_list = texts_list if len(old_obj_lst) > 0 or len(new_obj_lst) > 0: if len(old_obj_lst) > 0: for old_obj in old_obj_lst: updated_texts_list.remove(old_obj) if len(new_obj_lst) > 0: for new_obj in new_obj_lst: updated_texts_list.append(new_obj) texts_list_list.clear() updated_texts_list_list = \ [updated_texts_list[i:i + sub_list_limit] for i in range(0, len(updated_texts_list), sub_list_limit)] texts_list_list.extend(updated_texts_list_list) return updated_texts_list, updated_texts_list_list def cosine_similarities(mat): col_normed_mat = pp.normalize(mat.tocsc(), axis=1) return col_normed_mat * col_normed_mat.T def get_all_similarities(sparse_vectorized_corpus, corpus_text_ids): similarities = cosine_similarities(sparse_vectorized_corpus) similarities_df = pd.DataFrame.sparse.from_spmatrix(similarities, columns=corpus_text_ids) similarities_df["id"] = corpus_text_ids similarities_df = similarities_df.set_index(["id"]) return similarities_df def get_all_similarities_one_at_a_time(sparse_vectorized_corpus, corpus_text_ids, text_id, keep_original=False): text_id_index = corpus_text_ids.index(text_id) single_vectorized_record = sparse_vectorized_corpus[text_id_index, :] similarities = np.dot(single_vectorized_record, sparse_vectorized_corpus.T).toarray().ravel() similarities_series = pd.Series(similarities, index=corpus_text_ids) corpus_text_ids_adj = corpus_text_ids.copy() corpus_text_ids_adj.remove(text_id) similarities_series = similarities_series.filter(corpus_text_ids_adj) similarities_series.index.name = "id" similarities_series = similarities_series.sort_values(ascending=False) if keep_original: similarities_series = pd.concat([pd.Series(99.0, index=[text_id]), similarities_series]) return similarities_series def score_predictions(predictions_df, use_entropy=True, num_labels=5): prediction_values = predictions_df.values if use_entropy: all_score_combined = [] for prediction in prediction_values: qk = [1/num_labels] * num_labels all_score_combined.append(entropy(prediction, base=num_labels, qk=qk)) else: all_scores_num_non_zero = [] all_scores_std = [] for prediction in prediction_values: score_std = np.std(prediction) all_scores_std.append(score_std) score_num_non_zero = len([x for x in prediction if x > 0.0]) all_scores_num_non_zero.append(score_num_non_zero) all_score_combined = np.array(all_scores_std) / np.array(all_scores_num_non_zero) return all_score_combined def get_similarities_single_record(similarities_df, corpus_text_id): keep_indices = [x for x in similarities_df.index.values if x not in [corpus_text_id]] similarities = similarities_df[corpus_text_id] similarities = similarities.filter(keep_indices) similarities = similarities.sort_values(ascending=False) return similarities def generate_click_record(click_location, click_type, click_object, guid=None): time_stamp = datetime.now() if not guid: guid = uuid.uuid4() click_record = {"click_id": str(guid), "click_location": click_location, "click_type": click_type, "click_object": click_object, "click_date_time": time_stamp} return click_record, guid def generate_value_record(guid, value_type, value): value_record = {"click_id": str(guid), "value_type": value_type, "value": value} return value_record def add_log_record(record, log=[]): log.extend(record) return None def get_alert_message(label_summary_sql, overall_quality_score_decimal_sql, overall_quality_score_decimal_previous_sql, texts_group_3_sql): if not overall_quality_score_decimal_previous_sql and not overall_quality_score_decimal_sql: alert_message = "" elif not overall_quality_score_decimal_previous_sql and overall_quality_score_decimal_sql: if overall_quality_score_decimal_sql < 0.60: alert_message = "More labels are required to improve the overall quality score." elif overall_quality_score_decimal_sql < 0.80: alert_message = "This is a fairly good start. Keep labeling to try to get the quality score close to 100%" else: alert_message = "This is a reasonable quality score. Click on the score above to go to the difficult text section." elif overall_quality_score_decimal_previous_sql < overall_quality_score_decimal_sql: alert_message = "The quality score is improving. Keep labeling." elif overall_quality_score_decimal_previous_sql > overall_quality_score_decimal_sql: alert_message = "The quality score has dropped. Examine the texts more carefully before assigning a label." else: alert_message = "" return alert_message if __name__ == "__main__": start_time = datetime.now() print(">> Start time :", start_time.strftime("%m/%d/%Y %H:%M:%S"), "*"*100) end_time = datetime.now() duration = end_time - start_time print(">> End time :", end_time.strftime("%m/%d/%Y @ %H:%M:%S"), "*"*100) print(">> Duration :", duration, "*"*100)
true
true
1c3c0ce4b4e2c6a7db5c9927674ea4fad1b17918
2,271
py
Python
Chapter2/dna_search.py
trenton3983/ClassicComputerScienceProblemsInPython
f20edef60a072ab43bda98c5a5cb659ddd385b7f
[ "Apache-2.0" ]
792
2018-07-10T18:44:04.000Z
2022-03-25T19:19:22.000Z
Chapter2/dna_search.py
trenton3983/ClassicComputerScienceProblemsInPython
f20edef60a072ab43bda98c5a5cb659ddd385b7f
[ "Apache-2.0" ]
17
2019-01-29T04:07:58.000Z
2021-04-27T08:28:23.000Z
Chapter2/dna_search.py
trenton3983/ClassicComputerScienceProblemsInPython
f20edef60a072ab43bda98c5a5cb659ddd385b7f
[ "Apache-2.0" ]
340
2018-07-26T22:23:55.000Z
2022-03-30T03:44:02.000Z
# dna_search.py # From Classic Computer Science Problems in Python Chapter 2 # Copyright 2018 David Kopec # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from enum import IntEnum from typing import Tuple, List Nucleotide: IntEnum = IntEnum('Nucleotide', ('A', 'C', 'G', 'T')) Codon = Tuple[Nucleotide, Nucleotide, Nucleotide] # type alias for codons Gene = List[Codon] # type alias for genes gene_str: str = "ACGTGGCTCTCTAACGTACGTACGTACGGGGTTTATATATACCCTAGGACTCCCTTT" def string_to_gene(s: str) -> Gene: gene: Gene = [] for i in range(0, len(s), 3): if (i + 2) >= len(s): # don't run off end! return gene # initialize codon out of three nucleotides codon: Codon = (Nucleotide[s[i]], Nucleotide[s[i + 1]], Nucleotide[s[i + 2]]) gene.append(codon) # add codon to gene return gene my_gene: Gene = string_to_gene(gene_str) def linear_contains(gene: Gene, key_codon: Codon) -> bool: for codon in gene: if codon == key_codon: return True return False acg: Codon = (Nucleotide.A, Nucleotide.C, Nucleotide.G) gat: Codon = (Nucleotide.G, Nucleotide.A, Nucleotide.T) print(linear_contains(my_gene, acg)) # True print(linear_contains(my_gene, gat)) # False def binary_contains(gene: Gene, key_codon: Codon) -> bool: low: int = 0 high: int = len(gene) - 1 while low <= high: # while there is still a search space mid: int = (low + high) // 2 if gene[mid] < key_codon: low = mid + 1 elif gene[mid] > key_codon: high = mid - 1 else: return True return False my_sorted_gene: Gene = sorted(my_gene) print(binary_contains(my_sorted_gene, acg)) # True print(binary_contains(my_sorted_gene, gat)) # False
32.913043
85
0.676794
from enum import IntEnum from typing import Tuple, List Nucleotide: IntEnum = IntEnum('Nucleotide', ('A', 'C', 'G', 'T')) Codon = Tuple[Nucleotide, Nucleotide, Nucleotide] Gene = List[Codon] gene_str: str = "ACGTGGCTCTCTAACGTACGTACGTACGGGGTTTATATATACCCTAGGACTCCCTTT" def string_to_gene(s: str) -> Gene: gene: Gene = [] for i in range(0, len(s), 3): if (i + 2) >= len(s): return gene # initialize codon out of three nucleotides codon: Codon = (Nucleotide[s[i]], Nucleotide[s[i + 1]], Nucleotide[s[i + 2]]) gene.append(codon) # add codon to gene return gene my_gene: Gene = string_to_gene(gene_str) def linear_contains(gene: Gene, key_codon: Codon) -> bool: for codon in gene: if codon == key_codon: return True return False acg: Codon = (Nucleotide.A, Nucleotide.C, Nucleotide.G) gat: Codon = (Nucleotide.G, Nucleotide.A, Nucleotide.T) print(linear_contains(my_gene, acg)) # True print(linear_contains(my_gene, gat)) # False def binary_contains(gene: Gene, key_codon: Codon) -> bool: low: int = 0 high: int = len(gene) - 1 while low <= high: # while there is still a search space mid: int = (low + high) // 2 if gene[mid] < key_codon: low = mid + 1 elif gene[mid] > key_codon: high = mid - 1 else: return True return False my_sorted_gene: Gene = sorted(my_gene) print(binary_contains(my_sorted_gene, acg)) # True print(binary_contains(my_sorted_gene, gat)) # False
true
true
1c3c0d69435d264693a977b63370557d2de9213f
43,850
py
Python
lib/galaxy/objectstore/__init__.py
npinter/galaxy
a18a6b9938bae282f9228891e72442bf8ab51476
[ "CC-BY-3.0" ]
null
null
null
lib/galaxy/objectstore/__init__.py
npinter/galaxy
a18a6b9938bae282f9228891e72442bf8ab51476
[ "CC-BY-3.0" ]
null
null
null
lib/galaxy/objectstore/__init__.py
npinter/galaxy
a18a6b9938bae282f9228891e72442bf8ab51476
[ "CC-BY-3.0" ]
null
null
null
""" objectstore package, abstraction for storing blobs of data for use in Galaxy. all providers ensure that data can be accessed on the filesystem for running tools """ import abc import logging import os import random import shutil import threading import time from collections import OrderedDict import yaml from galaxy.exceptions import ObjectInvalid, ObjectNotFound from galaxy.util import ( directory_hash_id, force_symlink, parse_xml, umask_fix_perms, ) from galaxy.util.bunch import Bunch from galaxy.util.path import ( safe_makedirs, safe_relpath, ) from galaxy.util.sleeper import Sleeper NO_SESSION_ERROR_MESSAGE = "Attempted to 'create' object store entity in configuration with no database session present." log = logging.getLogger(__name__) class ObjectStore(metaclass=abc.ABCMeta): """ObjectStore interface. FIELD DESCRIPTIONS (these apply to all the methods in this class): :type obj: StorableObject :param obj: A Galaxy object with an assigned database ID accessible via the .id attribute. :type base_dir: string :param base_dir: A key in `self.extra_dirs` corresponding to the base directory in which this object should be created, or `None` to specify the default directory. :type dir_only: boolean :param dir_only: If `True`, check only the path where the file identified by `obj` should be located, not the dataset itself. This option applies to `extra_dir` argument as well. :type extra_dir: string :param extra_dir: Append `extra_dir` to the directory structure where the dataset identified by `obj` should be located. (e.g., 000/extra_dir/obj.id). Valid values include 'job_work' (defaulting to config.jobs_directory = '$GALAXY_ROOT/database/jobs_directory'); 'temp' (defaulting to config.new_file_path = '$GALAXY_ROOT/database/tmp'). :type extra_dir_at_root: boolean :param extra_dir_at_root: Applicable only if `extra_dir` is set. If True, the `extra_dir` argument is placed at root of the created directory structure rather than at the end (e.g., extra_dir/000/obj.id vs. 000/extra_dir/obj.id) :type alt_name: string :param alt_name: Use this name as the alternative name for the created dataset rather than the default. :type obj_dir: boolean :param obj_dir: Append a subdirectory named with the object's ID (e.g. 000/obj.id) """ @abc.abstractmethod def exists(self, obj, base_dir=None, dir_only=False, extra_dir=None, extra_dir_at_root=False, alt_name=None): """Return True if the object identified by `obj` exists, False otherwise.""" raise NotImplementedError() @abc.abstractmethod def create(self, obj, base_dir=None, dir_only=False, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): """ Mark the object (`obj`) as existing in the store, but with no content. This method will create a proper directory structure for the file if the directory does not already exist. """ raise NotImplementedError() @abc.abstractmethod def empty(self, obj, base_dir=None, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): """ Test if the object identified by `obj` has content. If the object does not exist raises `ObjectNotFound`. """ raise NotImplementedError() @abc.abstractmethod def size(self, obj, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): """ Return size of the object identified by `obj`. If the object does not exist, return 0. """ raise NotImplementedError() @abc.abstractmethod def delete(self, obj, entire_dir=False, base_dir=None, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): """ Delete the object identified by `obj`. :type entire_dir: boolean :param entire_dir: If True, delete the entire directory pointed to by extra_dir. For safety reasons, this option applies only for and in conjunction with the extra_dir or obj_dir options. """ raise NotImplementedError() @abc.abstractmethod def get_data(self, obj, start=0, count=-1, base_dir=None, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): """ Fetch `count` bytes of data offset by `start` bytes using `obj.id`. If the object does not exist raises `ObjectNotFound`. :type start: int :param start: Set the position to start reading the dataset file :type count: int :param count: Read at most `count` bytes from the dataset """ raise NotImplementedError() @abc.abstractmethod def get_filename(self, obj, base_dir=None, dir_only=False, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): """ Get the expected filename with absolute path for object with id `obj.id`. This can be used to access the contents of the object. """ raise NotImplementedError() @abc.abstractmethod def update_from_file(self, obj, base_dir=None, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False, file_name=None, create=False): """ Inform the store that the file associated with `obj.id` has been updated. If `file_name` is provided, update from that file instead of the default. If the object does not exist raises `ObjectNotFound`. :type file_name: string :param file_name: Use file pointed to by `file_name` as the source for updating the dataset identified by `obj` :type create: boolean :param create: If True and the default dataset does not exist, create it first. """ raise NotImplementedError() @abc.abstractmethod def get_object_url(self, obj, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): """ Return the URL for direct acces if supported, otherwise return None. Note: need to be careful to not bypass dataset security with this. """ raise NotImplementedError() @abc.abstractmethod def get_store_usage_percent(self): """Return the percentage indicating how full the store is.""" raise NotImplementedError() @abc.abstractmethod def get_store_by(self, obj): """Return how object is stored (by 'uuid', 'id', or None if not yet saved). Certain Galaxy remote data features aren't available if objects are stored by 'id'. """ raise NotImplementedError() class BaseObjectStore(ObjectStore): def __init__(self, config, config_dict=None, **kwargs): """ :type config: object :param config: An object, most likely populated from `galaxy/config.ini`, having the following attributes: * object_store_check_old_style (only used by the :class:`DiskObjectStore` subclass) * jobs_directory -- Each job is given a unique empty directory as its current working directory. This option defines in what parent directory those directories will be created. * new_file_path -- Used to set the 'temp' extra_dir. """ if config_dict is None: config_dict = {} self.running = True self.config = config self.check_old_style = config.object_store_check_old_style extra_dirs = {} extra_dirs['job_work'] = config.jobs_directory extra_dirs['temp'] = config.new_file_path extra_dirs.update({ e['type']: e['path'] for e in config_dict.get('extra_dirs', [])}) self.extra_dirs = extra_dirs def shutdown(self): """Close any connections for this ObjectStore.""" self.running = False def file_ready(self, obj, base_dir=None, dir_only=False, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): """ Check if a file corresponding to a dataset is ready to be used. Return True if so, False otherwise """ return True @classmethod def parse_xml(clazz, config_xml): """Parse an XML description of a configuration for this object store. Return a configuration dictionary (such as would correspond to the YAML configuration) for the object store. """ raise NotImplementedError() @classmethod def from_xml(clazz, config, config_xml, **kwd): config_dict = clazz.parse_xml(config_xml) return clazz(config, config_dict, **kwd) def to_dict(self): extra_dirs = [] for extra_dir_type, extra_dir_path in self.extra_dirs.items(): extra_dirs.append({"type": extra_dir_type, "path": extra_dir_path}) return { 'config': config_to_dict(self.config), 'extra_dirs': extra_dirs, 'type': self.store_type, } def _get_object_id(self, obj): if hasattr(obj, self.store_by): return getattr(obj, self.store_by) else: # job's don't have uuids, so always use ID in this case when creating # job working directories. return obj.id def _invoke(self, delegate, obj=None, **kwargs): return self.__getattribute__("_" + delegate)(obj=obj, **kwargs) def exists(self, obj, **kwargs): return self._invoke('exists', obj, **kwargs) def create(self, obj, **kwargs): return self._invoke('create', obj, **kwargs) def empty(self, obj, **kwargs): return self._invoke('empty', obj, **kwargs) def size(self, obj, **kwargs): return self._invoke('size', obj, **kwargs) def delete(self, obj, **kwargs): return self._invoke('delete', obj, **kwargs) def get_data(self, obj, **kwargs): return self._invoke('get_data', obj, **kwargs) def get_filename(self, obj, **kwargs): return self._invoke('get_filename', obj, **kwargs) def update_from_file(self, obj, **kwargs): return self._invoke('update_from_file', obj, **kwargs) def get_object_url(self, obj, **kwargs): return self._invoke('get_object_url', obj, **kwargs) def get_store_usage_percent(self): return self._invoke('get_store_usage_percent') def get_store_by(self, obj, **kwargs): return self._invoke('get_store_by', obj, **kwargs) class ConcreteObjectStore(BaseObjectStore): """Subclass of ObjectStore for stores that don't delegate (non-nested). Currently only adds store_by functionality. Which doesn't make sense for the delegating object stores. """ def __init__(self, config, config_dict=None, **kwargs): """ :type config: object :param config: An object, most likely populated from `galaxy/config.ini`, having the following attributes: * object_store_check_old_style (only used by the :class:`DiskObjectStore` subclass) * jobs_directory -- Each job is given a unique empty directory as its current working directory. This option defines in what parent directory those directories will be created. * new_file_path -- Used to set the 'temp' extra_dir. """ if config_dict is None: config_dict = {} super().__init__(config=config, config_dict=config_dict, **kwargs) self.store_by = config_dict.get("store_by", None) or getattr(config, "object_store_store_by", "id") def to_dict(self): rval = super().to_dict() rval["store_by"] = self.store_by return rval def _get_store_by(self, obj): return self.store_by class DiskObjectStore(ConcreteObjectStore): """ Standard Galaxy object store. Stores objects in files under a specific directory on disk. >>> from galaxy.util.bunch import Bunch >>> import tempfile >>> file_path=tempfile.mkdtemp() >>> obj = Bunch(id=1) >>> s = DiskObjectStore(Bunch(umask=0o077, jobs_directory=file_path, new_file_path=file_path, object_store_check_old_style=False), dict(files_dir=file_path)) >>> s.create(obj) >>> s.exists(obj) True >>> assert s.get_filename(obj) == file_path + '/000/dataset_1.dat' """ store_type = 'disk' def __init__(self, config, config_dict): """ :type config: object :param config: An object, most likely populated from `galaxy/config.ini`, having the same attributes needed by :class:`ObjectStore` plus: * file_path -- Default directory to store objects to disk in. * umask -- the permission bits for newly created files. :type file_path: str :param file_path: Override for the `config.file_path` value. :type extra_dirs: dict :param extra_dirs: Keys are string, values are directory paths. """ super().__init__(config, config_dict) self.file_path = os.path.abspath(config_dict.get("files_dir") or config.file_path) @classmethod def parse_xml(clazz, config_xml): extra_dirs = [] config_dict = {} if config_xml is not None: store_by = config_xml.attrib.get('store_by', None) if store_by is not None: config_dict['store_by'] = store_by for e in config_xml: if e.tag == 'files_dir': config_dict["files_dir"] = e.get('path') else: extra_dirs.append({"type": e.get('type'), "path": e.get('path')}) config_dict["extra_dirs"] = extra_dirs return config_dict def to_dict(self): as_dict = super().to_dict() as_dict["files_dir"] = self.file_path return as_dict def __get_filename(self, obj, base_dir=None, dir_only=False, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): """ Return the absolute path for the file corresponding to the `obj.id`. This is regardless of whether or not the file exists. """ path = self._construct_path(obj, base_dir=base_dir, dir_only=dir_only, extra_dir=extra_dir, extra_dir_at_root=extra_dir_at_root, alt_name=alt_name, obj_dir=False, old_style=True) # For backward compatibility: check the old style root path first; # otherwise construct hashed path. if not os.path.exists(path): return self._construct_path(obj, base_dir=base_dir, dir_only=dir_only, extra_dir=extra_dir, extra_dir_at_root=extra_dir_at_root, alt_name=alt_name) # TODO: rename to _disk_path or something like that to avoid conflicts with # children that'll use the local_extra_dirs decorator, e.g. S3 def _construct_path(self, obj, old_style=False, base_dir=None, dir_only=False, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False, **kwargs): """ Construct the absolute path for accessing the object identified by `obj.id`. :type base_dir: string :param base_dir: A key in self.extra_dirs corresponding to the base directory in which this object should be created, or None to specify the default directory. :type dir_only: boolean :param dir_only: If True, check only the path where the file identified by `obj` should be located, not the dataset itself. This option applies to `extra_dir` argument as well. :type extra_dir: string :param extra_dir: Append the value of this parameter to the expected path used to access the object identified by `obj` (e.g., /files/000/<extra_dir>/dataset_10.dat). :type alt_name: string :param alt_name: Use this name as the alternative name for the returned dataset rather than the default. :type old_style: boolean param old_style: This option is used for backward compatibility. If `True` then the composed directory structure does not include a hash id (e.g., /files/dataset_10.dat (old) vs. /files/000/dataset_10.dat (new)) """ base = os.path.abspath(self.extra_dirs.get(base_dir, self.file_path)) # extra_dir should never be constructed from provided data but just # make sure there are no shenannigans afoot if extra_dir and extra_dir != os.path.normpath(extra_dir): log.warning('extra_dir is not normalized: %s', extra_dir) raise ObjectInvalid("The requested object is invalid") # ensure that any parent directory references in alt_name would not # result in a path not contained in the directory path constructed here if alt_name and not safe_relpath(alt_name): log.warning('alt_name would locate path outside dir: %s', alt_name) raise ObjectInvalid("The requested object is invalid") obj_id = self._get_object_id(obj) if old_style: if extra_dir is not None: path = os.path.join(base, extra_dir) else: path = base else: # Construct hashed path rel_path = os.path.join(*directory_hash_id(obj_id)) # Create a subdirectory for the object ID if obj_dir: rel_path = os.path.join(rel_path, str(obj_id)) # Optionally append extra_dir if extra_dir is not None: if extra_dir_at_root: rel_path = os.path.join(extra_dir, rel_path) else: rel_path = os.path.join(rel_path, extra_dir) path = os.path.join(base, rel_path) if not dir_only: assert obj_id is not None, "The effective dataset identifier consumed by object store [%s] must be set before a path can be constructed." % (self.store_by) path = os.path.join(path, alt_name if alt_name else "dataset_%s.dat" % obj_id) return os.path.abspath(path) def _exists(self, obj, **kwargs): """Override `ObjectStore`'s stub and check on disk.""" if self.check_old_style: path = self._construct_path(obj, old_style=True, **kwargs) # For backward compatibility: check root path first; otherwise # construct and check hashed path. if os.path.exists(path): return True return os.path.exists(self._construct_path(obj, **kwargs)) def _create(self, obj, **kwargs): """Override `ObjectStore`'s stub by creating any files and folders on disk.""" if not self._exists(obj, **kwargs): path = self._construct_path(obj, **kwargs) dir_only = kwargs.get('dir_only', False) # Create directory if it does not exist dir = path if dir_only else os.path.dirname(path) safe_makedirs(dir) # Create the file if it does not exist if not dir_only: open(path, 'w').close() # Should be rb? umask_fix_perms(path, self.config.umask, 0o666) def _empty(self, obj, **kwargs): """Override `ObjectStore`'s stub by checking file size on disk.""" return self.size(obj, **kwargs) == 0 def _size(self, obj, **kwargs): """Override `ObjectStore`'s stub by return file size on disk. Returns 0 if the object doesn't exist yet or other error. """ if self._exists(obj, **kwargs): try: filepath = self._get_filename(obj, **kwargs) for _ in range(0, 2): size = os.path.getsize(filepath) if size != 0: break # May be legitimately 0, or there may be an issue with the FS / kernel, so we try again time.sleep(0.01) return size except OSError: return 0 else: return 0 def _delete(self, obj, entire_dir=False, **kwargs): """Override `ObjectStore`'s stub; delete the file or folder on disk.""" path = self._get_filename(obj, **kwargs) extra_dir = kwargs.get('extra_dir', None) obj_dir = kwargs.get('obj_dir', False) try: if entire_dir and (extra_dir or obj_dir): shutil.rmtree(path) return True if self._exists(obj, **kwargs): os.remove(path) return True except OSError as ex: log.critical('{} delete error {}'.format(self.__get_filename(obj, **kwargs), ex)) return False def _get_data(self, obj, start=0, count=-1, **kwargs): """Override `ObjectStore`'s stub; retrieve data directly from disk.""" data_file = open(self._get_filename(obj, **kwargs)) # Should be rb? data_file.seek(start) content = data_file.read(count) data_file.close() return content def _get_filename(self, obj, **kwargs): """ Override `ObjectStore`'s stub. If `object_store_check_old_style` is set to `True` in config then the root path is checked first. """ if self.check_old_style: path = self._construct_path(obj, old_style=True, **kwargs) # For backward compatibility, check root path first; otherwise, # construct and return hashed path if os.path.exists(path): return path path = self._construct_path(obj, **kwargs) if not os.path.exists(path): raise ObjectNotFound return path def _update_from_file(self, obj, file_name=None, create=False, **kwargs): """`create` parameter is not used in this implementation.""" preserve_symlinks = kwargs.pop('preserve_symlinks', False) # FIXME: symlinks and the object store model may not play well together # these should be handled better, e.g. registering the symlink'd file # as an object if create: self._create(obj, **kwargs) if file_name and self._exists(obj, **kwargs): try: if preserve_symlinks and os.path.islink(file_name): force_symlink(os.readlink(file_name), self._get_filename(obj, **kwargs)) else: path = self._get_filename(obj, **kwargs) shutil.copy(file_name, path) umask_fix_perms(path, self.config.umask, 0o666) except OSError as ex: log.critical('Error copying {} to {}: {}'.format(file_name, self.__get_filename(obj, **kwargs), ex)) raise ex def _get_object_url(self, obj, **kwargs): """ Override `ObjectStore`'s stub. Returns `None`, we have no URLs. """ return None def _get_store_usage_percent(self, **kwargs): """Override `ObjectStore`'s stub by return percent storage used.""" st = os.statvfs(self.file_path) return (float(st.f_blocks - st.f_bavail) / st.f_blocks) * 100 class NestedObjectStore(BaseObjectStore): """ Base for ObjectStores that use other ObjectStores. Example: DistributedObjectStore, HierarchicalObjectStore """ def __init__(self, config, config_xml=None): """Extend `ObjectStore`'s constructor.""" super().__init__(config) self.backends = {} def shutdown(self): """For each backend, shuts them down.""" for store in self.backends.values(): store.shutdown() super().shutdown() def _exists(self, obj, **kwargs): """Determine if the `obj` exists in any of the backends.""" return self._call_method('_exists', obj, False, False, **kwargs) def file_ready(self, obj, **kwargs): """Determine if the file for `obj` is ready to be used by any of the backends.""" return self._call_method('file_ready', obj, False, False, **kwargs) def _create(self, obj, **kwargs): """Create a backing file in a random backend.""" random.choice(list(self.backends.values())).create(obj, **kwargs) def _empty(self, obj, **kwargs): """For the first backend that has this `obj`, determine if it is empty.""" return self._call_method('_empty', obj, True, False, **kwargs) def _size(self, obj, **kwargs): """For the first backend that has this `obj`, return its size.""" return self._call_method('_size', obj, 0, False, **kwargs) def _delete(self, obj, **kwargs): """For the first backend that has this `obj`, delete it.""" return self._call_method('_delete', obj, False, False, **kwargs) def _get_data(self, obj, **kwargs): """For the first backend that has this `obj`, get data from it.""" return self._call_method('_get_data', obj, ObjectNotFound, True, **kwargs) def _get_filename(self, obj, **kwargs): """For the first backend that has this `obj`, get its filename.""" return self._call_method('_get_filename', obj, ObjectNotFound, True, **kwargs) def _update_from_file(self, obj, **kwargs): """For the first backend that has this `obj`, update it from the given file.""" if kwargs.get('create', False): self._create(obj, **kwargs) kwargs['create'] = False return self._call_method('_update_from_file', obj, ObjectNotFound, True, **kwargs) def _get_object_url(self, obj, **kwargs): """For the first backend that has this `obj`, get its URL.""" return self._call_method('_get_object_url', obj, None, False, **kwargs) def _get_store_by(self, obj): return self._call_method('_get_store_by', obj, None, False) def _repr_object_for_exception(self, obj): try: # there are a few objects in python that don't have __class__ obj_id = self._get_object_id(obj) return '{}({}={})'.format(obj.__class__.__name__, self.store_by, obj_id) except AttributeError: return str(obj) def _call_method(self, method, obj, default, default_is_exception, **kwargs): """Check all children object stores for the first one with the dataset.""" for store in self.backends.values(): if store.exists(obj, **kwargs): return store.__getattribute__(method)(obj, **kwargs) if default_is_exception: raise default('objectstore, _call_method failed: %s on %s, kwargs: %s' % (method, self._repr_object_for_exception(obj), str(kwargs))) else: return default class DistributedObjectStore(NestedObjectStore): """ ObjectStore that defers to a list of backends. When getting objects the first store where the object exists is used. When creating objects they are created in a store selected randomly, but with weighting. """ store_type = 'distributed' def __init__(self, config, config_dict, fsmon=False): """ :type config: object :param config: An object, most likely populated from `galaxy/config.ini`, having the same attributes needed by :class:`NestedObjectStore` plus: * distributed_object_store_config_file :type config_xml: ElementTree :type fsmon: bool :param fsmon: If True, monitor the file system for free space, removing backends when they get too full. """ super().__init__(config, config_dict) self.backends = {} self.weighted_backend_ids = [] self.original_weighted_backend_ids = [] self.max_percent_full = {} self.global_max_percent_full = config_dict.get("global_max_percent_full", 0) random.seed() for backend_def in config_dict["backends"]: backened_id = backend_def["id"] maxpctfull = backend_def.get("max_percent_full", 0) weight = backend_def["weight"] backend = build_object_store_from_config(config, config_dict=backend_def, fsmon=fsmon) self.backends[backened_id] = backend self.max_percent_full[backened_id] = maxpctfull for _ in range(0, weight): # The simplest way to do weighting: add backend ids to a # sequence the number of times equalling weight, then randomly # choose a backend from that sequence at creation self.weighted_backend_ids.append(backened_id) self.original_weighted_backend_ids = self.weighted_backend_ids self.sleeper = None if fsmon and (self.global_max_percent_full or [_ for _ in self.max_percent_full.values() if _ != 0.0]): self.sleeper = Sleeper() self.filesystem_monitor_thread = threading.Thread(target=self.__filesystem_monitor) self.filesystem_monitor_thread.setDaemon(True) self.filesystem_monitor_thread.start() log.info("Filesystem space monitor started") @classmethod def parse_xml(clazz, config_xml, legacy=False): if legacy: backends_root = config_xml else: backends_root = config_xml.find('backends') backends = [] config_dict = { 'global_max_percent_full': float(backends_root.get('maxpctfull', 0)), 'backends': backends, } for b in [e for e in backends_root if e.tag == 'backend']: store_id = b.get("id") store_weight = int(b.get("weight", 1)) store_maxpctfull = float(b.get('maxpctfull', 0)) store_type = b.get("type", "disk") store_by = b.get('store_by', None) objectstore_class, _ = type_to_object_store_class(store_type) backend_config_dict = objectstore_class.parse_xml(b) backend_config_dict["id"] = store_id backend_config_dict["weight"] = store_weight backend_config_dict["max_percent_full"] = store_maxpctfull backend_config_dict["type"] = store_type if store_by is not None: backend_config_dict["store_by"] = store_by backends.append(backend_config_dict) return config_dict @classmethod def from_xml(clazz, config, config_xml, fsmon=False): legacy = False if config_xml is None: distributed_config = config.distributed_object_store_config_file assert distributed_config is not None, \ "distributed object store ('object_store = distributed') " \ "requires a config file, please set one in " \ "'distributed_object_store_config_file')" log.debug('Loading backends for distributed object store from %s', distributed_config) config_xml = parse_xml(distributed_config).getroot() legacy = True else: log.debug('Loading backends for distributed object store from %s', config_xml.get('id')) config_dict = clazz.parse_xml(config_xml, legacy=legacy) return clazz(config, config_dict, fsmon=fsmon) def to_dict(self): as_dict = super().to_dict() as_dict["global_max_percent_full"] = self.global_max_percent_full backends = [] for backend_id, backend in self.backends.items(): backend_as_dict = backend.to_dict() backend_as_dict["id"] = backend_id backend_as_dict["max_percent_full"] = self.max_percent_full[backend_id] backend_as_dict["weight"] = len([i for i in self.original_weighted_backend_ids if i == backend_id]) backends.append(backend_as_dict) as_dict["backends"] = backends return as_dict def shutdown(self): """Shut down. Kill the free space monitor if there is one.""" super().shutdown() if self.sleeper is not None: self.sleeper.wake() def __filesystem_monitor(self): while self.running: new_weighted_backend_ids = self.original_weighted_backend_ids for id, backend in self.backends.items(): maxpct = self.max_percent_full[id] or self.global_max_percent_full pct = backend.get_store_usage_percent() if pct > maxpct: new_weighted_backend_ids = [_ for _ in new_weighted_backend_ids if _ != id] self.weighted_backend_ids = new_weighted_backend_ids self.sleeper.sleep(120) # Test free space every 2 minutes def _create(self, obj, **kwargs): """The only method in which obj.object_store_id may be None.""" if obj.object_store_id is None or not self._exists(obj, **kwargs): if obj.object_store_id is None or obj.object_store_id not in self.backends: try: obj.object_store_id = random.choice(self.weighted_backend_ids) except IndexError: raise ObjectInvalid('objectstore.create, could not generate ' 'obj.object_store_id: %s, kwargs: %s' % (str(obj), str(kwargs))) log.debug("Selected backend '%s' for creation of %s %s" % (obj.object_store_id, obj.__class__.__name__, obj.id)) else: log.debug("Using preferred backend '%s' for creation of %s %s" % (obj.object_store_id, obj.__class__.__name__, obj.id)) self.backends[obj.object_store_id].create(obj, **kwargs) def _call_method(self, method, obj, default, default_is_exception, **kwargs): object_store_id = self.__get_store_id_for(obj, **kwargs) if object_store_id is not None: return self.backends[object_store_id].__getattribute__(method)(obj, **kwargs) if default_is_exception: raise default('objectstore, _call_method failed: %s on %s, kwargs: %s' % (method, self._repr_object_for_exception(obj), str(kwargs))) else: return default def __get_store_id_for(self, obj, **kwargs): if obj.object_store_id is not None: if obj.object_store_id in self.backends: return obj.object_store_id else: log.warning('The backend object store ID (%s) for %s object with ID %s is invalid' % (obj.object_store_id, obj.__class__.__name__, obj.id)) # if this instance has been switched from a non-distributed to a # distributed object store, or if the object's store id is invalid, # try to locate the object for id, store in self.backends.items(): if store.exists(obj, **kwargs): log.warning('%s object with ID %s found in backend object store with ID %s' % (obj.__class__.__name__, obj.id, id)) obj.object_store_id = id return id return None class HierarchicalObjectStore(NestedObjectStore): """ ObjectStore that defers to a list of backends. When getting objects the first store where the object exists is used. When creating objects only the first store is used. """ store_type = 'hierarchical' def __init__(self, config, config_dict, fsmon=False): """The default contructor. Extends `NestedObjectStore`.""" super().__init__(config, config_dict) backends = OrderedDict() for order, backend_def in enumerate(config_dict["backends"]): backends[order] = build_object_store_from_config(config, config_dict=backend_def, fsmon=fsmon) self.backends = backends @classmethod def parse_xml(clazz, config_xml): backends_list = [] for b in sorted(config_xml.find('backends'), key=lambda b: int(b.get('order'))): store_type = b.get("type") objectstore_class, _ = type_to_object_store_class(store_type) backend_config_dict = objectstore_class.parse_xml(b) backend_config_dict["type"] = store_type backends_list.append(backend_config_dict) return {"backends": backends_list} def to_dict(self): as_dict = super().to_dict() backends = [] for backend in self.backends.values(): backend_as_dict = backend.to_dict() backends.append(backend_as_dict) as_dict["backends"] = backends return as_dict def _exists(self, obj, **kwargs): """Check all child object stores.""" for store in self.backends.values(): if store.exists(obj, **kwargs): return True return False def _create(self, obj, **kwargs): """Call the primary object store.""" self.backends[0].create(obj, **kwargs) def type_to_object_store_class(store, fsmon=False): objectstore_class = None objectstore_constructor_kwds = {} if store == 'disk': objectstore_class = DiskObjectStore elif store == 's3': from .s3 import S3ObjectStore objectstore_class = S3ObjectStore elif store == 'cloud': from .cloud import Cloud objectstore_class = Cloud elif store == 'swift': from .s3 import SwiftObjectStore objectstore_class = SwiftObjectStore elif store == 'distributed': objectstore_class = DistributedObjectStore objectstore_constructor_kwds["fsmon"] = fsmon elif store == 'hierarchical': objectstore_class = HierarchicalObjectStore objectstore_constructor_kwds["fsmon"] = fsmon elif store == 'irods': from .irods import IRODSObjectStore objectstore_class = IRODSObjectStore elif store == 'azure_blob': from .azure_blob import AzureBlobObjectStore objectstore_class = AzureBlobObjectStore elif store == 'pithos': from .pithos import PithosObjectStore objectstore_class = PithosObjectStore # Disable the Pulsar object store for now until it receives some attention # elif store == 'pulsar': # from .pulsar import PulsarObjectStore # return PulsarObjectStore(config=config, config_xml=config_xml) return objectstore_class, objectstore_constructor_kwds def build_object_store_from_config(config, fsmon=False, config_xml=None, config_dict=None): """ Invoke the appropriate object store. Will use the `object_store_config_file` attribute of the `config` object to configure a new object store from the specified XML file. Or you can specify the object store type in the `object_store` attribute of the `config` object. Currently 'disk', 's3', 'swift', 'distributed', 'hierarchical', 'irods', and 'pulsar' are supported values. """ from_object = 'xml' if config is None and config_dict is not None and 'config' in config_dict: # Build a config object from to_dict of an ObjectStore. config = Bunch(**config_dict["config"]) elif config is None: raise Exception("build_object_store_from_config sent None as config parameter and one cannot be recovered from config_dict") if config_xml is None and config_dict is None: config_file = config.object_store_config_file if os.path.exists(config_file): if config_file.endswith(".xml") or config_file.endswith(".xml.sample"): # This is a top level invocation of build_object_store_from_config, and # we have an object_store_conf.xml -- read the .xml and build # accordingly config_xml = parse_xml(config.object_store_config_file).getroot() store = config_xml.get('type') else: with open(config_file) as f: config_dict = yaml.safe_load(f) from_object = 'dict' store = config_dict.get('type') else: store = config.object_store elif config_xml is not None: store = config_xml.get('type') elif config_dict is not None: from_object = 'dict' store = config_dict.get('type') objectstore_class, objectstore_constructor_kwds = type_to_object_store_class(store, fsmon=fsmon) if objectstore_class is None: log.error("Unrecognized object store definition: {}".format(store)) if from_object == 'xml': return objectstore_class.from_xml(config=config, config_xml=config_xml, **objectstore_constructor_kwds) else: return objectstore_class(config=config, config_dict=config_dict, **objectstore_constructor_kwds) def local_extra_dirs(func): """Non-local plugin decorator using local directories for the extra_dirs (job_work and temp).""" def wraps(self, *args, **kwargs): if kwargs.get('base_dir', None) is None: return func(self, *args, **kwargs) else: for c in self.__class__.__mro__: if c.__name__ == 'DiskObjectStore': return getattr(c, func.__name__)(self, *args, **kwargs) raise Exception("Could not call DiskObjectStore's %s method, does your " "Object Store plugin inherit from DiskObjectStore?" % func.__name__) return wraps def convert_bytes(bytes): """A helper function used for pretty printing disk usage.""" if bytes is None: bytes = 0 bytes = float(bytes) if bytes >= 1099511627776: terabytes = bytes / 1099511627776 size = '%.2fTB' % terabytes elif bytes >= 1073741824: gigabytes = bytes / 1073741824 size = '%.2fGB' % gigabytes elif bytes >= 1048576: megabytes = bytes / 1048576 size = '%.2fMB' % megabytes elif bytes >= 1024: kilobytes = bytes / 1024 size = '%.2fKB' % kilobytes else: size = '%.2fb' % bytes return size def config_to_dict(config): """Dict-ify the portion of a config object consumed by the ObjectStore class and its subclasses. """ return { 'object_store_check_old_style': config.object_store_check_old_style, 'file_path': config.file_path, 'umask': config.umask, 'jobs_directory': config.jobs_directory, 'new_file_path': config.new_file_path, 'object_store_cache_path': config.object_store_cache_path, 'gid': config.gid, } class ObjectStorePopulator: """ Small helper for interacting with the object store and making sure all datasets from a job end up with the same object_store_id. """ def __init__(self, app): self.object_store = app.object_store self.object_store_id = None def set_object_store_id(self, data): # Create an empty file immediately. The first dataset will be # created in the "default" store, all others will be created in # the same store as the first. data.dataset.object_store_id = self.object_store_id try: self.object_store.create(data.dataset) except ObjectInvalid: raise Exception('Unable to create output dataset: object store is full') self.object_store_id = data.dataset.object_store_id # these will be the same thing after the first output
40.340386
167
0.630627
import abc import logging import os import random import shutil import threading import time from collections import OrderedDict import yaml from galaxy.exceptions import ObjectInvalid, ObjectNotFound from galaxy.util import ( directory_hash_id, force_symlink, parse_xml, umask_fix_perms, ) from galaxy.util.bunch import Bunch from galaxy.util.path import ( safe_makedirs, safe_relpath, ) from galaxy.util.sleeper import Sleeper NO_SESSION_ERROR_MESSAGE = "Attempted to 'create' object store entity in configuration with no database session present." log = logging.getLogger(__name__) class ObjectStore(metaclass=abc.ABCMeta): @abc.abstractmethod def exists(self, obj, base_dir=None, dir_only=False, extra_dir=None, extra_dir_at_root=False, alt_name=None): raise NotImplementedError() @abc.abstractmethod def create(self, obj, base_dir=None, dir_only=False, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): raise NotImplementedError() @abc.abstractmethod def empty(self, obj, base_dir=None, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): raise NotImplementedError() @abc.abstractmethod def size(self, obj, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): raise NotImplementedError() @abc.abstractmethod def delete(self, obj, entire_dir=False, base_dir=None, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): raise NotImplementedError() @abc.abstractmethod def get_data(self, obj, start=0, count=-1, base_dir=None, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): raise NotImplementedError() @abc.abstractmethod def get_filename(self, obj, base_dir=None, dir_only=False, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): raise NotImplementedError() @abc.abstractmethod def update_from_file(self, obj, base_dir=None, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False, file_name=None, create=False): raise NotImplementedError() @abc.abstractmethod def get_object_url(self, obj, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): raise NotImplementedError() @abc.abstractmethod def get_store_usage_percent(self): raise NotImplementedError() @abc.abstractmethod def get_store_by(self, obj): raise NotImplementedError() class BaseObjectStore(ObjectStore): def __init__(self, config, config_dict=None, **kwargs): if config_dict is None: config_dict = {} self.running = True self.config = config self.check_old_style = config.object_store_check_old_style extra_dirs = {} extra_dirs['job_work'] = config.jobs_directory extra_dirs['temp'] = config.new_file_path extra_dirs.update({ e['type']: e['path'] for e in config_dict.get('extra_dirs', [])}) self.extra_dirs = extra_dirs def shutdown(self): self.running = False def file_ready(self, obj, base_dir=None, dir_only=False, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): return True @classmethod def parse_xml(clazz, config_xml): raise NotImplementedError() @classmethod def from_xml(clazz, config, config_xml, **kwd): config_dict = clazz.parse_xml(config_xml) return clazz(config, config_dict, **kwd) def to_dict(self): extra_dirs = [] for extra_dir_type, extra_dir_path in self.extra_dirs.items(): extra_dirs.append({"type": extra_dir_type, "path": extra_dir_path}) return { 'config': config_to_dict(self.config), 'extra_dirs': extra_dirs, 'type': self.store_type, } def _get_object_id(self, obj): if hasattr(obj, self.store_by): return getattr(obj, self.store_by) else: return obj.id def _invoke(self, delegate, obj=None, **kwargs): return self.__getattribute__("_" + delegate)(obj=obj, **kwargs) def exists(self, obj, **kwargs): return self._invoke('exists', obj, **kwargs) def create(self, obj, **kwargs): return self._invoke('create', obj, **kwargs) def empty(self, obj, **kwargs): return self._invoke('empty', obj, **kwargs) def size(self, obj, **kwargs): return self._invoke('size', obj, **kwargs) def delete(self, obj, **kwargs): return self._invoke('delete', obj, **kwargs) def get_data(self, obj, **kwargs): return self._invoke('get_data', obj, **kwargs) def get_filename(self, obj, **kwargs): return self._invoke('get_filename', obj, **kwargs) def update_from_file(self, obj, **kwargs): return self._invoke('update_from_file', obj, **kwargs) def get_object_url(self, obj, **kwargs): return self._invoke('get_object_url', obj, **kwargs) def get_store_usage_percent(self): return self._invoke('get_store_usage_percent') def get_store_by(self, obj, **kwargs): return self._invoke('get_store_by', obj, **kwargs) class ConcreteObjectStore(BaseObjectStore): def __init__(self, config, config_dict=None, **kwargs): if config_dict is None: config_dict = {} super().__init__(config=config, config_dict=config_dict, **kwargs) self.store_by = config_dict.get("store_by", None) or getattr(config, "object_store_store_by", "id") def to_dict(self): rval = super().to_dict() rval["store_by"] = self.store_by return rval def _get_store_by(self, obj): return self.store_by class DiskObjectStore(ConcreteObjectStore): store_type = 'disk' def __init__(self, config, config_dict): super().__init__(config, config_dict) self.file_path = os.path.abspath(config_dict.get("files_dir") or config.file_path) @classmethod def parse_xml(clazz, config_xml): extra_dirs = [] config_dict = {} if config_xml is not None: store_by = config_xml.attrib.get('store_by', None) if store_by is not None: config_dict['store_by'] = store_by for e in config_xml: if e.tag == 'files_dir': config_dict["files_dir"] = e.get('path') else: extra_dirs.append({"type": e.get('type'), "path": e.get('path')}) config_dict["extra_dirs"] = extra_dirs return config_dict def to_dict(self): as_dict = super().to_dict() as_dict["files_dir"] = self.file_path return as_dict def __get_filename(self, obj, base_dir=None, dir_only=False, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False): path = self._construct_path(obj, base_dir=base_dir, dir_only=dir_only, extra_dir=extra_dir, extra_dir_at_root=extra_dir_at_root, alt_name=alt_name, obj_dir=False, old_style=True) if not os.path.exists(path): return self._construct_path(obj, base_dir=base_dir, dir_only=dir_only, extra_dir=extra_dir, extra_dir_at_root=extra_dir_at_root, alt_name=alt_name) def _construct_path(self, obj, old_style=False, base_dir=None, dir_only=False, extra_dir=None, extra_dir_at_root=False, alt_name=None, obj_dir=False, **kwargs): base = os.path.abspath(self.extra_dirs.get(base_dir, self.file_path)) # extra_dir should never be constructed from provided data but just # make sure there are no shenannigans afoot if extra_dir and extra_dir != os.path.normpath(extra_dir): log.warning('extra_dir is not normalized: %s', extra_dir) raise ObjectInvalid("The requested object is invalid") # ensure that any parent directory references in alt_name would not # result in a path not contained in the directory path constructed here if alt_name and not safe_relpath(alt_name): log.warning('alt_name would locate path outside dir: %s', alt_name) raise ObjectInvalid("The requested object is invalid") obj_id = self._get_object_id(obj) if old_style: if extra_dir is not None: path = os.path.join(base, extra_dir) else: path = base else: # Construct hashed path rel_path = os.path.join(*directory_hash_id(obj_id)) # Create a subdirectory for the object ID if obj_dir: rel_path = os.path.join(rel_path, str(obj_id)) # Optionally append extra_dir if extra_dir is not None: if extra_dir_at_root: rel_path = os.path.join(extra_dir, rel_path) else: rel_path = os.path.join(rel_path, extra_dir) path = os.path.join(base, rel_path) if not dir_only: assert obj_id is not None, "The effective dataset identifier consumed by object store [%s] must be set before a path can be constructed." % (self.store_by) path = os.path.join(path, alt_name if alt_name else "dataset_%s.dat" % obj_id) return os.path.abspath(path) def _exists(self, obj, **kwargs): if self.check_old_style: path = self._construct_path(obj, old_style=True, **kwargs) # For backward compatibility: check root path first; otherwise # construct and check hashed path. if os.path.exists(path): return True return os.path.exists(self._construct_path(obj, **kwargs)) def _create(self, obj, **kwargs): if not self._exists(obj, **kwargs): path = self._construct_path(obj, **kwargs) dir_only = kwargs.get('dir_only', False) # Create directory if it does not exist dir = path if dir_only else os.path.dirname(path) safe_makedirs(dir) # Create the file if it does not exist if not dir_only: open(path, 'w').close() # Should be rb? umask_fix_perms(path, self.config.umask, 0o666) def _empty(self, obj, **kwargs): return self.size(obj, **kwargs) == 0 def _size(self, obj, **kwargs): if self._exists(obj, **kwargs): try: filepath = self._get_filename(obj, **kwargs) for _ in range(0, 2): size = os.path.getsize(filepath) if size != 0: break # May be legitimately 0, or there may be an issue with the FS / kernel, so we try again time.sleep(0.01) return size except OSError: return 0 else: return 0 def _delete(self, obj, entire_dir=False, **kwargs): path = self._get_filename(obj, **kwargs) extra_dir = kwargs.get('extra_dir', None) obj_dir = kwargs.get('obj_dir', False) try: if entire_dir and (extra_dir or obj_dir): shutil.rmtree(path) return True if self._exists(obj, **kwargs): os.remove(path) return True except OSError as ex: log.critical('{} delete error {}'.format(self.__get_filename(obj, **kwargs), ex)) return False def _get_data(self, obj, start=0, count=-1, **kwargs): data_file = open(self._get_filename(obj, **kwargs)) # Should be rb? data_file.seek(start) content = data_file.read(count) data_file.close() return content def _get_filename(self, obj, **kwargs): if self.check_old_style: path = self._construct_path(obj, old_style=True, **kwargs) # For backward compatibility, check root path first; otherwise, # construct and return hashed path if os.path.exists(path): return path path = self._construct_path(obj, **kwargs) if not os.path.exists(path): raise ObjectNotFound return path def _update_from_file(self, obj, file_name=None, create=False, **kwargs): preserve_symlinks = kwargs.pop('preserve_symlinks', False) # FIXME: symlinks and the object store model may not play well together # these should be handled better, e.g. registering the symlink'd file if create: self._create(obj, **kwargs) if file_name and self._exists(obj, **kwargs): try: if preserve_symlinks and os.path.islink(file_name): force_symlink(os.readlink(file_name), self._get_filename(obj, **kwargs)) else: path = self._get_filename(obj, **kwargs) shutil.copy(file_name, path) umask_fix_perms(path, self.config.umask, 0o666) except OSError as ex: log.critical('Error copying {} to {}: {}'.format(file_name, self.__get_filename(obj, **kwargs), ex)) raise ex def _get_object_url(self, obj, **kwargs): return None def _get_store_usage_percent(self, **kwargs): st = os.statvfs(self.file_path) return (float(st.f_blocks - st.f_bavail) / st.f_blocks) * 100 class NestedObjectStore(BaseObjectStore): def __init__(self, config, config_xml=None): super().__init__(config) self.backends = {} def shutdown(self): for store in self.backends.values(): store.shutdown() super().shutdown() def _exists(self, obj, **kwargs): return self._call_method('_exists', obj, False, False, **kwargs) def file_ready(self, obj, **kwargs): return self._call_method('file_ready', obj, False, False, **kwargs) def _create(self, obj, **kwargs): random.choice(list(self.backends.values())).create(obj, **kwargs) def _empty(self, obj, **kwargs): return self._call_method('_empty', obj, True, False, **kwargs) def _size(self, obj, **kwargs): return self._call_method('_size', obj, 0, False, **kwargs) def _delete(self, obj, **kwargs): return self._call_method('_delete', obj, False, False, **kwargs) def _get_data(self, obj, **kwargs): return self._call_method('_get_data', obj, ObjectNotFound, True, **kwargs) def _get_filename(self, obj, **kwargs): return self._call_method('_get_filename', obj, ObjectNotFound, True, **kwargs) def _update_from_file(self, obj, **kwargs): if kwargs.get('create', False): self._create(obj, **kwargs) kwargs['create'] = False return self._call_method('_update_from_file', obj, ObjectNotFound, True, **kwargs) def _get_object_url(self, obj, **kwargs): return self._call_method('_get_object_url', obj, None, False, **kwargs) def _get_store_by(self, obj): return self._call_method('_get_store_by', obj, None, False) def _repr_object_for_exception(self, obj): try: obj_id = self._get_object_id(obj) return '{}({}={})'.format(obj.__class__.__name__, self.store_by, obj_id) except AttributeError: return str(obj) def _call_method(self, method, obj, default, default_is_exception, **kwargs): for store in self.backends.values(): if store.exists(obj, **kwargs): return store.__getattribute__(method)(obj, **kwargs) if default_is_exception: raise default('objectstore, _call_method failed: %s on %s, kwargs: %s' % (method, self._repr_object_for_exception(obj), str(kwargs))) else: return default class DistributedObjectStore(NestedObjectStore): store_type = 'distributed' def __init__(self, config, config_dict, fsmon=False): super().__init__(config, config_dict) self.backends = {} self.weighted_backend_ids = [] self.original_weighted_backend_ids = [] self.max_percent_full = {} self.global_max_percent_full = config_dict.get("global_max_percent_full", 0) random.seed() for backend_def in config_dict["backends"]: backened_id = backend_def["id"] maxpctfull = backend_def.get("max_percent_full", 0) weight = backend_def["weight"] backend = build_object_store_from_config(config, config_dict=backend_def, fsmon=fsmon) self.backends[backened_id] = backend self.max_percent_full[backened_id] = maxpctfull for _ in range(0, weight): # The simplest way to do weighting: add backend ids to a # sequence the number of times equalling weight, then randomly # choose a backend from that sequence at creation self.weighted_backend_ids.append(backened_id) self.original_weighted_backend_ids = self.weighted_backend_ids self.sleeper = None if fsmon and (self.global_max_percent_full or [_ for _ in self.max_percent_full.values() if _ != 0.0]): self.sleeper = Sleeper() self.filesystem_monitor_thread = threading.Thread(target=self.__filesystem_monitor) self.filesystem_monitor_thread.setDaemon(True) self.filesystem_monitor_thread.start() log.info("Filesystem space monitor started") @classmethod def parse_xml(clazz, config_xml, legacy=False): if legacy: backends_root = config_xml else: backends_root = config_xml.find('backends') backends = [] config_dict = { 'global_max_percent_full': float(backends_root.get('maxpctfull', 0)), 'backends': backends, } for b in [e for e in backends_root if e.tag == 'backend']: store_id = b.get("id") store_weight = int(b.get("weight", 1)) store_maxpctfull = float(b.get('maxpctfull', 0)) store_type = b.get("type", "disk") store_by = b.get('store_by', None) objectstore_class, _ = type_to_object_store_class(store_type) backend_config_dict = objectstore_class.parse_xml(b) backend_config_dict["id"] = store_id backend_config_dict["weight"] = store_weight backend_config_dict["max_percent_full"] = store_maxpctfull backend_config_dict["type"] = store_type if store_by is not None: backend_config_dict["store_by"] = store_by backends.append(backend_config_dict) return config_dict @classmethod def from_xml(clazz, config, config_xml, fsmon=False): legacy = False if config_xml is None: distributed_config = config.distributed_object_store_config_file assert distributed_config is not None, \ "distributed object store ('object_store = distributed') " \ "requires a config file, please set one in " \ "'distributed_object_store_config_file')" log.debug('Loading backends for distributed object store from %s', distributed_config) config_xml = parse_xml(distributed_config).getroot() legacy = True else: log.debug('Loading backends for distributed object store from %s', config_xml.get('id')) config_dict = clazz.parse_xml(config_xml, legacy=legacy) return clazz(config, config_dict, fsmon=fsmon) def to_dict(self): as_dict = super().to_dict() as_dict["global_max_percent_full"] = self.global_max_percent_full backends = [] for backend_id, backend in self.backends.items(): backend_as_dict = backend.to_dict() backend_as_dict["id"] = backend_id backend_as_dict["max_percent_full"] = self.max_percent_full[backend_id] backend_as_dict["weight"] = len([i for i in self.original_weighted_backend_ids if i == backend_id]) backends.append(backend_as_dict) as_dict["backends"] = backends return as_dict def shutdown(self): super().shutdown() if self.sleeper is not None: self.sleeper.wake() def __filesystem_monitor(self): while self.running: new_weighted_backend_ids = self.original_weighted_backend_ids for id, backend in self.backends.items(): maxpct = self.max_percent_full[id] or self.global_max_percent_full pct = backend.get_store_usage_percent() if pct > maxpct: new_weighted_backend_ids = [_ for _ in new_weighted_backend_ids if _ != id] self.weighted_backend_ids = new_weighted_backend_ids self.sleeper.sleep(120) # Test free space every 2 minutes def _create(self, obj, **kwargs): if obj.object_store_id is None or not self._exists(obj, **kwargs): if obj.object_store_id is None or obj.object_store_id not in self.backends: try: obj.object_store_id = random.choice(self.weighted_backend_ids) except IndexError: raise ObjectInvalid('objectstore.create, could not generate ' 'obj.object_store_id: %s, kwargs: %s' % (str(obj), str(kwargs))) log.debug("Selected backend '%s' for creation of %s %s" % (obj.object_store_id, obj.__class__.__name__, obj.id)) else: log.debug("Using preferred backend '%s' for creation of %s %s" % (obj.object_store_id, obj.__class__.__name__, obj.id)) self.backends[obj.object_store_id].create(obj, **kwargs) def _call_method(self, method, obj, default, default_is_exception, **kwargs): object_store_id = self.__get_store_id_for(obj, **kwargs) if object_store_id is not None: return self.backends[object_store_id].__getattribute__(method)(obj, **kwargs) if default_is_exception: raise default('objectstore, _call_method failed: %s on %s, kwargs: %s' % (method, self._repr_object_for_exception(obj), str(kwargs))) else: return default def __get_store_id_for(self, obj, **kwargs): if obj.object_store_id is not None: if obj.object_store_id in self.backends: return obj.object_store_id else: log.warning('The backend object store ID (%s) for %s object with ID %s is invalid' % (obj.object_store_id, obj.__class__.__name__, obj.id)) # if this instance has been switched from a non-distributed to a # distributed object store, or if the object's store id is invalid, for id, store in self.backends.items(): if store.exists(obj, **kwargs): log.warning('%s object with ID %s found in backend object store with ID %s' % (obj.__class__.__name__, obj.id, id)) obj.object_store_id = id return id return None class HierarchicalObjectStore(NestedObjectStore): store_type = 'hierarchical' def __init__(self, config, config_dict, fsmon=False): super().__init__(config, config_dict) backends = OrderedDict() for order, backend_def in enumerate(config_dict["backends"]): backends[order] = build_object_store_from_config(config, config_dict=backend_def, fsmon=fsmon) self.backends = backends @classmethod def parse_xml(clazz, config_xml): backends_list = [] for b in sorted(config_xml.find('backends'), key=lambda b: int(b.get('order'))): store_type = b.get("type") objectstore_class, _ = type_to_object_store_class(store_type) backend_config_dict = objectstore_class.parse_xml(b) backend_config_dict["type"] = store_type backends_list.append(backend_config_dict) return {"backends": backends_list} def to_dict(self): as_dict = super().to_dict() backends = [] for backend in self.backends.values(): backend_as_dict = backend.to_dict() backends.append(backend_as_dict) as_dict["backends"] = backends return as_dict def _exists(self, obj, **kwargs): for store in self.backends.values(): if store.exists(obj, **kwargs): return True return False def _create(self, obj, **kwargs): self.backends[0].create(obj, **kwargs) def type_to_object_store_class(store, fsmon=False): objectstore_class = None objectstore_constructor_kwds = {} if store == 'disk': objectstore_class = DiskObjectStore elif store == 's3': from .s3 import S3ObjectStore objectstore_class = S3ObjectStore elif store == 'cloud': from .cloud import Cloud objectstore_class = Cloud elif store == 'swift': from .s3 import SwiftObjectStore objectstore_class = SwiftObjectStore elif store == 'distributed': objectstore_class = DistributedObjectStore objectstore_constructor_kwds["fsmon"] = fsmon elif store == 'hierarchical': objectstore_class = HierarchicalObjectStore objectstore_constructor_kwds["fsmon"] = fsmon elif store == 'irods': from .irods import IRODSObjectStore objectstore_class = IRODSObjectStore elif store == 'azure_blob': from .azure_blob import AzureBlobObjectStore objectstore_class = AzureBlobObjectStore elif store == 'pithos': from .pithos import PithosObjectStore objectstore_class = PithosObjectStore return objectstore_class, objectstore_constructor_kwds def build_object_store_from_config(config, fsmon=False, config_xml=None, config_dict=None): from_object = 'xml' if config is None and config_dict is not None and 'config' in config_dict: config = Bunch(**config_dict["config"]) elif config is None: raise Exception("build_object_store_from_config sent None as config parameter and one cannot be recovered from config_dict") if config_xml is None and config_dict is None: config_file = config.object_store_config_file if os.path.exists(config_file): if config_file.endswith(".xml") or config_file.endswith(".xml.sample"): config_xml = parse_xml(config.object_store_config_file).getroot() store = config_xml.get('type') else: with open(config_file) as f: config_dict = yaml.safe_load(f) from_object = 'dict' store = config_dict.get('type') else: store = config.object_store elif config_xml is not None: store = config_xml.get('type') elif config_dict is not None: from_object = 'dict' store = config_dict.get('type') objectstore_class, objectstore_constructor_kwds = type_to_object_store_class(store, fsmon=fsmon) if objectstore_class is None: log.error("Unrecognized object store definition: {}".format(store)) if from_object == 'xml': return objectstore_class.from_xml(config=config, config_xml=config_xml, **objectstore_constructor_kwds) else: return objectstore_class(config=config, config_dict=config_dict, **objectstore_constructor_kwds) def local_extra_dirs(func): def wraps(self, *args, **kwargs): if kwargs.get('base_dir', None) is None: return func(self, *args, **kwargs) else: for c in self.__class__.__mro__: if c.__name__ == 'DiskObjectStore': return getattr(c, func.__name__)(self, *args, **kwargs) raise Exception("Could not call DiskObjectStore's %s method, does your " "Object Store plugin inherit from DiskObjectStore?" % func.__name__) return wraps def convert_bytes(bytes): if bytes is None: bytes = 0 bytes = float(bytes) if bytes >= 1099511627776: terabytes = bytes / 1099511627776 size = '%.2fTB' % terabytes elif bytes >= 1073741824: gigabytes = bytes / 1073741824 size = '%.2fGB' % gigabytes elif bytes >= 1048576: megabytes = bytes / 1048576 size = '%.2fMB' % megabytes elif bytes >= 1024: kilobytes = bytes / 1024 size = '%.2fKB' % kilobytes else: size = '%.2fb' % bytes return size def config_to_dict(config): return { 'object_store_check_old_style': config.object_store_check_old_style, 'file_path': config.file_path, 'umask': config.umask, 'jobs_directory': config.jobs_directory, 'new_file_path': config.new_file_path, 'object_store_cache_path': config.object_store_cache_path, 'gid': config.gid, } class ObjectStorePopulator: def __init__(self, app): self.object_store = app.object_store self.object_store_id = None def set_object_store_id(self, data): # Create an empty file immediately. The first dataset will be # created in the "default" store, all others will be created in # the same store as the first. data.dataset.object_store_id = self.object_store_id try: self.object_store.create(data.dataset) except ObjectInvalid: raise Exception('Unable to create output dataset: object store is full') self.object_store_id = data.dataset.object_store_id # these will be the same thing after the first output
true
true
1c3c0db35e5980f991c1935641bf247688c58588
3,092
py
Python
src/third_party/wiredtiger/test/suite/test_bug011.py
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
4
2018-02-06T01:53:12.000Z
2018-02-20T01:47:36.000Z
src/third_party/wiredtiger/test/suite/test_bug011.py
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
null
null
null
src/third_party/wiredtiger/test/suite/test_bug011.py
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
3
2018-02-06T01:53:18.000Z
2021-07-28T09:48:15.000Z
#!usr/bin/env python # # Public Domain 2014-2016 MongoDB, Inc. # Public Domain 2008-2014 WiredTiger, Inc. # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and to the detriment of our heirs and # successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # # 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 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 random, wiredtiger, wttest from wtdataset import SimpleDataSet # test_bug011.py # Eviction working on more trees than the eviction server can walk # simultaneously. There is a builtin limit of 1000 trees, we open double # that, which makes this a long-running test. class test_bug011(wttest.WiredTigerTestCase): """ Test having eviction working on more files than the number of allocated hazard pointers. """ table_name = 'test_bug011' ntables = 2000 nrows = 10000 nops = 10000 # Add connection configuration for this test. def conn_config(self): return 'cache_size=1GB' @wttest.longtest("Eviction copes with lots of files") def test_eviction(self): cursors = [] datasets = [] for i in range(0, self.ntables): this_uri = 'table:%s-%05d' % (self.table_name, i) ds = SimpleDataSet(self, this_uri, self.nrows, config='allocation_size=1KB,leaf_page_max=1KB') ds.populate() datasets.append(ds) # Switch over to on-disk trees with multiple leaf pages self.reopen_conn() # Make sure we have a cursor for every table so it stays in cache. for i in range(0, self.ntables): this_uri = 'table:%s-%05d' % (self.table_name, i) cursors.append(self.session.open_cursor(this_uri, None)) # Make use of the cache. for i in range(0, self.nops): for i in range(0, self.ntables): cursors[i].set_key(ds.key(random.randint(0, self.nrows - 1))) cursors[i].search() cursors[i].reset() if __name__ == '__main__': wttest.run()
40.155844
79
0.667206
import random, wiredtiger, wttest from wtdataset import SimpleDataSet class test_bug011(wttest.WiredTigerTestCase): table_name = 'test_bug011' ntables = 2000 nrows = 10000 nops = 10000 def conn_config(self): return 'cache_size=1GB' @wttest.longtest("Eviction copes with lots of files") def test_eviction(self): cursors = [] datasets = [] for i in range(0, self.ntables): this_uri = 'table:%s-%05d' % (self.table_name, i) ds = SimpleDataSet(self, this_uri, self.nrows, config='allocation_size=1KB,leaf_page_max=1KB') ds.populate() datasets.append(ds) self.reopen_conn() for i in range(0, self.ntables): this_uri = 'table:%s-%05d' % (self.table_name, i) cursors.append(self.session.open_cursor(this_uri, None)) for i in range(0, self.nops): for i in range(0, self.ntables): cursors[i].set_key(ds.key(random.randint(0, self.nrows - 1))) cursors[i].search() cursors[i].reset() if __name__ == '__main__': wttest.run()
true
true
1c3c0e1a20ec82d2c18e9e846b46216ed165c356
1,075
py
Python
web/polls/migrations/0001_initial.py
yhmun/portfolio
fd06acb779dd1da227a1db265246165f6975ee58
[ "Unlicense" ]
null
null
null
web/polls/migrations/0001_initial.py
yhmun/portfolio
fd06acb779dd1da227a1db265246165f6975ee58
[ "Unlicense" ]
5
2021-06-04T23:19:31.000Z
2021-09-22T19:08:08.000Z
web/polls/migrations/0001_initial.py
yhmun/portfolio
fd06acb779dd1da227a1db265246165f6975ee58
[ "Unlicense" ]
null
null
null
# Generated by Django 3.0.6 on 2020-05-31 21:26 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Question', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('question_text', models.CharField(max_length=200)), ('pub_date', models.DateTimeField(verbose_name='date published')), ], ), migrations.CreateModel( name='Choice', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('choice_text', models.CharField(max_length=200)), ('votes', models.IntegerField(default=0)), ('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question')), ], ), ]
32.575758
114
0.586047
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Question', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('question_text', models.CharField(max_length=200)), ('pub_date', models.DateTimeField(verbose_name='date published')), ], ), migrations.CreateModel( name='Choice', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('choice_text', models.CharField(max_length=200)), ('votes', models.IntegerField(default=0)), ('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question')), ], ), ]
true
true
1c3c0f273d3aedaf69b93c9b0765066b82b32c34
7,255
py
Python
selfdrive/controls/lib/pathplanner.py
TiffanyInAPot/openpilot
ca9cad56a3b11760ae3a2c3ed0ac0dbe852ab18a
[ "MIT" ]
1
2019-06-06T03:10:46.000Z
2019-06-06T03:10:46.000Z
selfdrive/controls/lib/pathplanner.py
TiffanyInAPot/openpilot
ca9cad56a3b11760ae3a2c3ed0ac0dbe852ab18a
[ "MIT" ]
null
null
null
selfdrive/controls/lib/pathplanner.py
TiffanyInAPot/openpilot
ca9cad56a3b11760ae3a2c3ed0ac0dbe852ab18a
[ "MIT" ]
null
null
null
import os import math import numpy as np from common.numpy_fast import clip from common.realtime import sec_since_boot from selfdrive.services import service_list from selfdrive.swaglog import cloudlog from selfdrive.controls.lib.lateral_mpc import libmpc_py from selfdrive.controls.lib.drive_helpers import MPC_COST_LAT from selfdrive.controls.lib.model_parser import ModelParser import selfdrive.messaging as messaging LOG_MPC = os.environ.get('LOG_MPC', False) MAX_STEER_ACCEL = 10.5 def calc_states_after_delay(states, v_ego, steer_angle, curvature_factor, steer_ratio, delay): states[0].x = v_ego * delay states[0].psi = v_ego * curvature_factor * math.radians(steer_angle) / steer_ratio * delay return states class PathPlanner(object): def __init__(self, CP): self.MP = ModelParser() self.l_poly = libmpc_py.ffi.new("double[4]") self.r_poly = libmpc_py.ffi.new("double[4]") self.p_poly = libmpc_py.ffi.new("double[4]") self.last_cloudlog_t = 0 self.plan = messaging.pub_sock(service_list['pathPlan'].port) self.livempc = messaging.pub_sock(service_list['liveMpc'].port) self.setup_mpc(CP.steerRateCost) self.solution_invalid_cnt = 0 def setup_mpc(self, steer_rate_cost): self.libmpc = libmpc_py.libmpc #self.libmpc.init(MPC_COST_LAT.PATH, MPC_COST_LAT.LANE, MPC_COST_LAT.HEADING, steer_rate_cost) self.libmpc.init(MPC_COST_LAT.PATH * 0.1, MPC_COST_LAT.LANE, MPC_COST_LAT.HEADING, steer_rate_cost) self.mpc_solution = libmpc_py.ffi.new("log_t *") self.cur_state = libmpc_py.ffi.new("state_t *") self.cur_state[0].x = 0.0 self.cur_state[0].y = 0.0 self.cur_state[0].psi = 0.0 self.cur_state[0].delta = 0.0 self.mpc_angles = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] self.mpc_rates = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] self.mpc_times = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] self.angle_steers_des = 0.0 self.angle_steers_des_mpc = 0.0 self.angle_steers_des_prev = 0.0 self.angle_steers_des_time = 0.0 self.rate_des_prev = 0.0 self.angle_offset = 0.0 def update(self, sm, CP, VM): v_ego = sm['carState'].vEgo angle_steers = sm['carState'].steeringAngle cur_time = sec_since_boot() angle_offset_average = sm['liveParameters'].angleOffsetAverage max_offset_change = 0.001 / (abs(self.angle_offset) + 0.0001) self.angle_offset = clip(angle_offset_average + sm['controlsState'].lateralControlState.pidState.angleBias, self.angle_offset - max_offset_change, self.angle_offset + max_offset_change) self.MP.update(v_ego, sm['model']) # Run MPC self.angle_steers_des_prev = self.angle_steers_des_mpc VM.update_params(sm['liveParameters'].stiffnessFactor, sm['liveParameters'].steerRatio) curvature_factor = VM.curvature_factor(v_ego) self.l_poly = list(self.MP.l_poly) self.r_poly = list(self.MP.r_poly) self.p_poly = list(self.MP.p_poly) # prevent over-inflation of desired angle actual_delta = math.radians(angle_steers - self.angle_offset) / VM.sR delta_limit = abs(actual_delta) + abs(3.0 * self.mpc_solution[0].rate[0]) self.cur_state[0].delta = clip(self.cur_state[0].delta, -delta_limit, delta_limit) # account for actuation delay self.cur_state = calc_states_after_delay(self.cur_state, v_ego, angle_steers - self.angle_offset, curvature_factor, VM.sR, CP.steerActuatorDelay) v_ego_mpc = max(v_ego, 5.0) # avoid mpc roughness due to low speed self.libmpc.run_mpc(self.cur_state, self.mpc_solution, self.l_poly, self.r_poly, self.p_poly, self.MP.l_prob, self.MP.r_prob, self.MP.p_prob, curvature_factor, v_ego_mpc, self.MP.lane_width) # Check for infeasable MPC solution mpc_nans = np.any(np.isnan(list(self.mpc_solution[0].delta))) if not mpc_nans: if (self.rate_des_prev < 0) != (self.mpc_solution[0].rate[0] < 0): delta_adjust = self.cur_state[0].delta - actual_delta self.cur_state[0].delta = actual_delta self.mpc_solution[0].delta[0] -= delta_adjust self.mpc_angles[0] = float(math.degrees(self.cur_state[0].delta * VM.sR) + angle_offset_average) self.mpc_times[0] = sm.logMonoTime['model'] * 1e-9 for i in range(1,6): self.mpc_times[i] = self.mpc_times[i-1] + 0.05 self.mpc_rates[i-1] = float(math.degrees(self.mpc_solution[0].rate[i-1] * VM.sR)) self.mpc_angles[i] = (0.05 * self.mpc_rates[i-1] + self.mpc_angles[i-1]) self.cur_state[0].delta = self.mpc_solution[0].delta[1] rate_desired = math.degrees(self.mpc_solution[0].rate[0] * VM.sR) self.angle_steers_des_mpc = float(math.degrees(self.mpc_solution[0].delta[1] * VM.sR) + angle_offset_average) else: self.libmpc.init(MPC_COST_LAT.PATH * 0.1, MPC_COST_LAT.LANE, MPC_COST_LAT.HEADING, CP.steerRateCost) rate_desired = 0.0 if cur_time > self.last_cloudlog_t + 5.0: self.last_cloudlog_t = cur_time cloudlog.warning("Lateral mpc - nan: True") self.rate_des_prev = rate_desired if self.mpc_solution[0].cost > 20000. or mpc_nans: # TODO: find a better way to detect when MPC did not converge self.solution_invalid_cnt += 1 else: self.solution_invalid_cnt = 0 plan_solution_valid = self.solution_invalid_cnt < 2 plan_send = messaging.new_message() plan_send.init('pathPlan') plan_send.valid = sm.all_alive_and_valid(service_list=['carState', 'controlsState', 'liveParameters', 'model']) plan_send.pathPlan.laneWidth = float(self.MP.lane_width) plan_send.pathPlan.pPoly = [float(x) for x in self.MP.p_poly] plan_send.pathPlan.pProb = float(self.MP.p_prob) plan_send.pathPlan.dPoly = [float(x) for x in self.MP.d_poly] plan_send.pathPlan.cPoly = [float(x) for x in self.MP.c_poly] plan_send.pathPlan.cProb = float(self.MP.c_prob) plan_send.pathPlan.lPoly = [float(x) for x in self.l_poly] plan_send.pathPlan.lProb = float(self.MP.l_prob) plan_send.pathPlan.rPoly = [float(x) for x in self.r_poly] plan_send.pathPlan.rProb = float(self.MP.r_prob) plan_send.pathPlan.angleSteers = float(self.angle_steers_des_mpc) plan_send.pathPlan.rateSteers = float(rate_desired) plan_send.pathPlan.angleBias = float(self.angle_offset - angle_offset_average) plan_send.pathPlan.angleOffset = float(angle_offset_average) plan_send.pathPlan.mpcAngles = [float(x) for x in self.mpc_angles] plan_send.pathPlan.mpcTimes = [float(x) for x in self.mpc_times] plan_send.pathPlan.mpcRates = [float(x) for x in self.mpc_rates] plan_send.pathPlan.mpcSolutionValid = bool(plan_solution_valid) plan_send.pathPlan.paramsValid = bool(sm['liveParameters'].valid) plan_send.pathPlan.sensorValid = bool(sm['liveParameters'].sensorValid) plan_send.pathPlan.posenetValid = bool(sm['liveParameters'].posenetValid) self.plan.send(plan_send.to_bytes()) dat = messaging.new_message() dat.init('liveMpc') dat.liveMpc.x = list(self.mpc_solution[0].x) dat.liveMpc.y = list(self.mpc_solution[0].y) dat.liveMpc.psi = list(self.mpc_solution[0].psi) dat.liveMpc.delta = list(self.mpc_solution[0].delta) dat.liveMpc.cost = self.mpc_solution[0].cost self.livempc.send(dat.to_bytes())
45.062112
189
0.715507
import os import math import numpy as np from common.numpy_fast import clip from common.realtime import sec_since_boot from selfdrive.services import service_list from selfdrive.swaglog import cloudlog from selfdrive.controls.lib.lateral_mpc import libmpc_py from selfdrive.controls.lib.drive_helpers import MPC_COST_LAT from selfdrive.controls.lib.model_parser import ModelParser import selfdrive.messaging as messaging LOG_MPC = os.environ.get('LOG_MPC', False) MAX_STEER_ACCEL = 10.5 def calc_states_after_delay(states, v_ego, steer_angle, curvature_factor, steer_ratio, delay): states[0].x = v_ego * delay states[0].psi = v_ego * curvature_factor * math.radians(steer_angle) / steer_ratio * delay return states class PathPlanner(object): def __init__(self, CP): self.MP = ModelParser() self.l_poly = libmpc_py.ffi.new("double[4]") self.r_poly = libmpc_py.ffi.new("double[4]") self.p_poly = libmpc_py.ffi.new("double[4]") self.last_cloudlog_t = 0 self.plan = messaging.pub_sock(service_list['pathPlan'].port) self.livempc = messaging.pub_sock(service_list['liveMpc'].port) self.setup_mpc(CP.steerRateCost) self.solution_invalid_cnt = 0 def setup_mpc(self, steer_rate_cost): self.libmpc = libmpc_py.libmpc self.libmpc.init(MPC_COST_LAT.PATH * 0.1, MPC_COST_LAT.LANE, MPC_COST_LAT.HEADING, steer_rate_cost) self.mpc_solution = libmpc_py.ffi.new("log_t *") self.cur_state = libmpc_py.ffi.new("state_t *") self.cur_state[0].x = 0.0 self.cur_state[0].y = 0.0 self.cur_state[0].psi = 0.0 self.cur_state[0].delta = 0.0 self.mpc_angles = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] self.mpc_rates = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] self.mpc_times = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] self.angle_steers_des = 0.0 self.angle_steers_des_mpc = 0.0 self.angle_steers_des_prev = 0.0 self.angle_steers_des_time = 0.0 self.rate_des_prev = 0.0 self.angle_offset = 0.0 def update(self, sm, CP, VM): v_ego = sm['carState'].vEgo angle_steers = sm['carState'].steeringAngle cur_time = sec_since_boot() angle_offset_average = sm['liveParameters'].angleOffsetAverage max_offset_change = 0.001 / (abs(self.angle_offset) + 0.0001) self.angle_offset = clip(angle_offset_average + sm['controlsState'].lateralControlState.pidState.angleBias, self.angle_offset - max_offset_change, self.angle_offset + max_offset_change) self.MP.update(v_ego, sm['model']) self.angle_steers_des_prev = self.angle_steers_des_mpc VM.update_params(sm['liveParameters'].stiffnessFactor, sm['liveParameters'].steerRatio) curvature_factor = VM.curvature_factor(v_ego) self.l_poly = list(self.MP.l_poly) self.r_poly = list(self.MP.r_poly) self.p_poly = list(self.MP.p_poly) actual_delta = math.radians(angle_steers - self.angle_offset) / VM.sR delta_limit = abs(actual_delta) + abs(3.0 * self.mpc_solution[0].rate[0]) self.cur_state[0].delta = clip(self.cur_state[0].delta, -delta_limit, delta_limit) self.cur_state = calc_states_after_delay(self.cur_state, v_ego, angle_steers - self.angle_offset, curvature_factor, VM.sR, CP.steerActuatorDelay) v_ego_mpc = max(v_ego, 5.0) self.libmpc.run_mpc(self.cur_state, self.mpc_solution, self.l_poly, self.r_poly, self.p_poly, self.MP.l_prob, self.MP.r_prob, self.MP.p_prob, curvature_factor, v_ego_mpc, self.MP.lane_width) mpc_nans = np.any(np.isnan(list(self.mpc_solution[0].delta))) if not mpc_nans: if (self.rate_des_prev < 0) != (self.mpc_solution[0].rate[0] < 0): delta_adjust = self.cur_state[0].delta - actual_delta self.cur_state[0].delta = actual_delta self.mpc_solution[0].delta[0] -= delta_adjust self.mpc_angles[0] = float(math.degrees(self.cur_state[0].delta * VM.sR) + angle_offset_average) self.mpc_times[0] = sm.logMonoTime['model'] * 1e-9 for i in range(1,6): self.mpc_times[i] = self.mpc_times[i-1] + 0.05 self.mpc_rates[i-1] = float(math.degrees(self.mpc_solution[0].rate[i-1] * VM.sR)) self.mpc_angles[i] = (0.05 * self.mpc_rates[i-1] + self.mpc_angles[i-1]) self.cur_state[0].delta = self.mpc_solution[0].delta[1] rate_desired = math.degrees(self.mpc_solution[0].rate[0] * VM.sR) self.angle_steers_des_mpc = float(math.degrees(self.mpc_solution[0].delta[1] * VM.sR) + angle_offset_average) else: self.libmpc.init(MPC_COST_LAT.PATH * 0.1, MPC_COST_LAT.LANE, MPC_COST_LAT.HEADING, CP.steerRateCost) rate_desired = 0.0 if cur_time > self.last_cloudlog_t + 5.0: self.last_cloudlog_t = cur_time cloudlog.warning("Lateral mpc - nan: True") self.rate_des_prev = rate_desired if self.mpc_solution[0].cost > 20000. or mpc_nans: self.solution_invalid_cnt += 1 else: self.solution_invalid_cnt = 0 plan_solution_valid = self.solution_invalid_cnt < 2 plan_send = messaging.new_message() plan_send.init('pathPlan') plan_send.valid = sm.all_alive_and_valid(service_list=['carState', 'controlsState', 'liveParameters', 'model']) plan_send.pathPlan.laneWidth = float(self.MP.lane_width) plan_send.pathPlan.pPoly = [float(x) for x in self.MP.p_poly] plan_send.pathPlan.pProb = float(self.MP.p_prob) plan_send.pathPlan.dPoly = [float(x) for x in self.MP.d_poly] plan_send.pathPlan.cPoly = [float(x) for x in self.MP.c_poly] plan_send.pathPlan.cProb = float(self.MP.c_prob) plan_send.pathPlan.lPoly = [float(x) for x in self.l_poly] plan_send.pathPlan.lProb = float(self.MP.l_prob) plan_send.pathPlan.rPoly = [float(x) for x in self.r_poly] plan_send.pathPlan.rProb = float(self.MP.r_prob) plan_send.pathPlan.angleSteers = float(self.angle_steers_des_mpc) plan_send.pathPlan.rateSteers = float(rate_desired) plan_send.pathPlan.angleBias = float(self.angle_offset - angle_offset_average) plan_send.pathPlan.angleOffset = float(angle_offset_average) plan_send.pathPlan.mpcAngles = [float(x) for x in self.mpc_angles] plan_send.pathPlan.mpcTimes = [float(x) for x in self.mpc_times] plan_send.pathPlan.mpcRates = [float(x) for x in self.mpc_rates] plan_send.pathPlan.mpcSolutionValid = bool(plan_solution_valid) plan_send.pathPlan.paramsValid = bool(sm['liveParameters'].valid) plan_send.pathPlan.sensorValid = bool(sm['liveParameters'].sensorValid) plan_send.pathPlan.posenetValid = bool(sm['liveParameters'].posenetValid) self.plan.send(plan_send.to_bytes()) dat = messaging.new_message() dat.init('liveMpc') dat.liveMpc.x = list(self.mpc_solution[0].x) dat.liveMpc.y = list(self.mpc_solution[0].y) dat.liveMpc.psi = list(self.mpc_solution[0].psi) dat.liveMpc.delta = list(self.mpc_solution[0].delta) dat.liveMpc.cost = self.mpc_solution[0].cost self.livempc.send(dat.to_bytes())
true
true
1c3c10767b90990f4219390186db711aa2387ba1
1,949
py
Python
sparv/util/install.py
heatherleaf/sparv-pipeline
0fe5f27d0d82548ecc6cb21a69289668aac54cf1
[ "MIT" ]
null
null
null
sparv/util/install.py
heatherleaf/sparv-pipeline
0fe5f27d0d82548ecc6cb21a69289668aac54cf1
[ "MIT" ]
null
null
null
sparv/util/install.py
heatherleaf/sparv-pipeline
0fe5f27d0d82548ecc6cb21a69289668aac54cf1
[ "MIT" ]
null
null
null
"""Util functions for installations on remote servers.""" import logging import os import subprocess from glob import glob from sparv.util import system log = logging.getLogger(__name__) def install_file(host, local_file, remote_file): """Rsync a file to a target host.""" system.rsync(local_file, host, remote_file) def install_directory(host, directory): """Rsync every file from local directory to target host. Target path is extracted from filenames by replacing "#" with "/". """ for local in glob(os.path.join(directory, '*')): remote = os.path.basename(local).replace("#", "/") system.rsync(local, host, remote) def install_mysql(host, db_name, sqlfile): """Insert tables and data from local SQL-file to remote MySQL database. sqlfile may be a whitespace separated list of SQL files. """ if not host: raise(Exception("No host provided! Installations aborted.")) sqlfiles = sqlfile.split() file_count = 0 file_total = len(sqlfiles) for sqlf in sqlfiles: file_count += 1 if not os.path.exists(sqlf): log.error("Missing SQL file: %s", sqlf) elif os.path.getsize(sqlf) < 10: log.info("Skipping empty file: %s (%d/%d)", sqlf, file_count, file_total) else: log.info("Installing MySQL database: %s, source: %s (%d/%d)", db_name, sqlf, file_count, file_total) subprocess.check_call('cat %s | ssh %s "mysql %s"' % (sqlf, host, db_name), shell=True) def install_mysql_dump(host, db_name, tables): """Copy selected tables (including data) from local to remote MySQL database.""" if isinstance(tables, str): tables = tables.split() log.info("Copying MySQL database: %s, tables: %s", db_name, ", ".join(tables)) subprocess.check_call('mysqldump %s %s | ssh %s "mysql %s"' % (db_name, " ".join(tables), host, db_name), shell=True)
33.603448
112
0.647512
import logging import os import subprocess from glob import glob from sparv.util import system log = logging.getLogger(__name__) def install_file(host, local_file, remote_file): system.rsync(local_file, host, remote_file) def install_directory(host, directory): for local in glob(os.path.join(directory, '*')): remote = os.path.basename(local).replace("#", "/") system.rsync(local, host, remote) def install_mysql(host, db_name, sqlfile): if not host: raise(Exception("No host provided! Installations aborted.")) sqlfiles = sqlfile.split() file_count = 0 file_total = len(sqlfiles) for sqlf in sqlfiles: file_count += 1 if not os.path.exists(sqlf): log.error("Missing SQL file: %s", sqlf) elif os.path.getsize(sqlf) < 10: log.info("Skipping empty file: %s (%d/%d)", sqlf, file_count, file_total) else: log.info("Installing MySQL database: %s, source: %s (%d/%d)", db_name, sqlf, file_count, file_total) subprocess.check_call('cat %s | ssh %s "mysql %s"' % (sqlf, host, db_name), shell=True) def install_mysql_dump(host, db_name, tables): if isinstance(tables, str): tables = tables.split() log.info("Copying MySQL database: %s, tables: %s", db_name, ", ".join(tables)) subprocess.check_call('mysqldump %s %s | ssh %s "mysql %s"' % (db_name, " ".join(tables), host, db_name), shell=True)
true
true
1c3c10a8ec1e11f5539e1b0e56b8babde0787984
1,857
py
Python
Game/python/pyserial_comm_test.py
TimothyThompkins/InteractiveGame
06042a217ede1239b4a3dd8e5adaa5e28ef7095f
[ "MIT" ]
null
null
null
Game/python/pyserial_comm_test.py
TimothyThompkins/InteractiveGame
06042a217ede1239b4a3dd8e5adaa5e28ef7095f
[ "MIT" ]
null
null
null
Game/python/pyserial_comm_test.py
TimothyThompkins/InteractiveGame
06042a217ede1239b4a3dd8e5adaa5e28ef7095f
[ "MIT" ]
null
null
null
import serial import time #ser = serial.Serial('/dev/tty.usbmodem1431') # open first serial port ser = serial.Serial( # port = '/dev/tty.usbmodem1431', # For Macbook pro running OSX port = '/dev/ttyACM0', # For Ubuntu 14.04. Middle right port baudrate = 9600, parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS, timeout = 5 ) #ser.open() try: ser.isOpen() print ('Connected.') except: print ('Connection Failure') #input=1 while 1 : # get keyboard input #input = raw_input(">> ") # Python 3 users print ('Enter your commands below. Insert "exit" to close the application.') data = input() #sread(size=1) if data == 'exit': ser.close() exit() else: # send the character to the device # (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device) #ser.write(input + '\r\n') ser.write(bytes(data, 'UTF-8')) buffer = '' # let's wait one second before reading output (let's give device time to answer) # time.sleep(1) # x = ser.read() # read one byte # s = ser.read(10) # read up to ten bytes (timeout) # line = ser.readline() # read a '\n' terminated line} # rcv_data = 0; # while rcv_data == 0: # # out += ser.readline() # # # out = ser.readline() # buffer = '' # while ser.inWaiting() > 0: # buffer += ser.readline().decode('UTF-8') # print (buffer) # # if buffer != '': # rcv_data = 1; # print (">>" + buffer) while True: bytesToRead = ser.inWaiting() ser.read(bytesToRead) print (bytesToRead)
27.716418
119
0.541195
import serial import time baudrate = 9600, parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS, timeout = 5 ) try: ser.isOpen() print ('Connected.') except: print ('Connection Failure') while 1 : print ('Enter your commands below. Insert "exit" to close the application.') data = input() if data == 'exit': ser.close() exit() else: ser.write(bytes(data, 'UTF-8')) buffer = '' while True: bytesToRead = ser.inWaiting() ser.read(bytesToRead) print (bytesToRead)
true
true
1c3c129d1d95b2a6ed8bea144df8ec679147077c
1,942
py
Python
services/web/apps/pm/ddash/views.py
prorevizor/noc
37e44b8afc64318b10699c06a1138eee9e7d6a4e
[ "BSD-3-Clause" ]
null
null
null
services/web/apps/pm/ddash/views.py
prorevizor/noc
37e44b8afc64318b10699c06a1138eee9e7d6a4e
[ "BSD-3-Clause" ]
null
null
null
services/web/apps/pm/ddash/views.py
prorevizor/noc
37e44b8afc64318b10699c06a1138eee9e7d6a4e
[ "BSD-3-Clause" ]
null
null
null
# --------------------------------------------------------------------- # pm.ddash application # --------------------------------------------------------------------- # Copyright (C) 2007-2021 The NOC Project # See LICENSE for details # --------------------------------------------------------------------- # NOC modules from noc.lib.app.extapplication import ExtApplication, view from noc.sa.models.managedobject import ManagedObject from .dashboards.loader import loader from .dashboards.base import BaseDashboard from noc.core.translation import ugettext as _ class DynamicDashboardApplication(ExtApplication): """ MetricType application """ title = _("Dynamic Dashboard") @view(url=r"^$", method="GET", access="launch", api=True) def api_dashboard(self, request): dash_name = request.GET.get("dashboard") try: # ddash by cals oid = request.GET.get("id") mo = ManagedObject.get_by_id(oid) if mo.get_caps().get("Sensor | Controller"): dash_name = "sensor_controller" if mo.get_caps().get("Network | DVBC"): dash_name = "modvbc" except Exception: pass try: dt = loader[dash_name] except Exception: self.logger.error("Exception when loading dashboard: %s", request.GET.get("dashboard")) return self.response_not_found("Dashboard not found") if not dt: return self.response_not_found("Dashboard not found") extra_vars = {} for v in request.GET: if v.startswith("var_"): extra_vars[v] = request.GET[v] extra_template = request.GET.get("extra_template") try: dashboard = dt(oid, extra_template, extra_vars) except BaseDashboard.NotFound: return self.response_not_found("Object not found") return dashboard.render()
35.962963
99
0.556128
from noc.lib.app.extapplication import ExtApplication, view from noc.sa.models.managedobject import ManagedObject from .dashboards.loader import loader from .dashboards.base import BaseDashboard from noc.core.translation import ugettext as _ class DynamicDashboardApplication(ExtApplication): title = _("Dynamic Dashboard") @view(url=r"^$", method="GET", access="launch", api=True) def api_dashboard(self, request): dash_name = request.GET.get("dashboard") try: oid = request.GET.get("id") mo = ManagedObject.get_by_id(oid) if mo.get_caps().get("Sensor | Controller"): dash_name = "sensor_controller" if mo.get_caps().get("Network | DVBC"): dash_name = "modvbc" except Exception: pass try: dt = loader[dash_name] except Exception: self.logger.error("Exception when loading dashboard: %s", request.GET.get("dashboard")) return self.response_not_found("Dashboard not found") if not dt: return self.response_not_found("Dashboard not found") extra_vars = {} for v in request.GET: if v.startswith("var_"): extra_vars[v] = request.GET[v] extra_template = request.GET.get("extra_template") try: dashboard = dt(oid, extra_template, extra_vars) except BaseDashboard.NotFound: return self.response_not_found("Object not found") return dashboard.render()
true
true
1c3c13112b99f811fee28d8c227ef456a6878bf9
3,243
py
Python
fastargs/validation.py
lengstrom/fastargs
bf2e0ac826bfb81f7559cd44e956c6a4aad982f1
[ "MIT" ]
20
2021-04-02T06:43:37.000Z
2022-02-16T18:33:10.000Z
fastargs/validation.py
lengstrom/fastargs
bf2e0ac826bfb81f7559cd44e956c6a4aad982f1
[ "MIT" ]
16
2021-04-02T05:27:26.000Z
2022-03-07T18:11:11.000Z
fastargs/validation.py
lengstrom/fastargs
bf2e0ac826bfb81f7559cd44e956c6a4aad982f1
[ "MIT" ]
1
2021-11-11T03:31:10.000Z
2021-11-11T03:31:10.000Z
import importlib from abc import ABC, abstractmethod class Checker(ABC): @abstractmethod def check(self, value): raise NotImplementedError @abstractmethod def help(self) -> str: raise NotImplementedError def get_checker(checker): if checker in DEFAULT_CHECKERS: return DEFAULT_CHECKERS[checker] if not isinstance(checker, Checker): raise TypeError("Invalid checker") return checker class Int(Checker): def check(self, value): return int(value) def help(self): return "an int" class Bool(Checker): def check(self, value): return bool(value) def help(self): return "a boolean" class Float(Checker): def check(self, value): return float(value) def help(self): return "a float" class Str(Checker): def check(self, value): if isinstance(value, str): return value raise TypeError() def help(self): return "a string" class Anything(Checker): def check(self, value): return value def help(self): return "anything" class Or(Checker): def __init__(self, *checkers): self.checkers = [get_checker(x) for x in checkers] def check(self, value): for checker in self.checkers: try: return checker.check(value) except Exception as e: pass raise ValueError("None of the condition are valid") def help(self): return ' or '.join([x.help() for x in self.checkers]) class And(Checker): def __init__(self, *checkers): self.checkers = [get_checker(x) for x in checkers] def check(self, value): result = value for checker in self.checkers: result = checker.check(result) return result def help(self): return ' and '.join([x.help() for x in self.checkers]) class InRange(Checker): def __init__(self, min=float('-inf'), max=float('+inf')): self.low = min self.high = max def check(self, value): if value < self.low or value > self.high: raise ValueError() return value def help(self): return f"between {self.low} and {self.high}" class OneOf(Checker): def __init__(self, possible_values): self.possible_values = set(possible_values) def check(self, value): if value not in self.possible_values: raise ValueError() return value def help(self): return f"One of [{', '.join([str(x) for x in self.possible_values])}]" class Module(Checker): def __init__(self): pass def check(self, value): return importlib.import_module(value) def help(self): return "path to python module" class ImportedObject(Checker): def __init__(self): pass def check(self, value): path = value.split('.') module = '.'.join(path[:-1]) imported = importlib.import_module(module) return getattr(imported, path[-1]) def help(self): return "path to python module and an object within" DEFAULT_CHECKERS = { int: Int(), float: Float(), str: Str(), bool: Bool() }
20.922581
78
0.599137
import importlib from abc import ABC, abstractmethod class Checker(ABC): @abstractmethod def check(self, value): raise NotImplementedError @abstractmethod def help(self) -> str: raise NotImplementedError def get_checker(checker): if checker in DEFAULT_CHECKERS: return DEFAULT_CHECKERS[checker] if not isinstance(checker, Checker): raise TypeError("Invalid checker") return checker class Int(Checker): def check(self, value): return int(value) def help(self): return "an int" class Bool(Checker): def check(self, value): return bool(value) def help(self): return "a boolean" class Float(Checker): def check(self, value): return float(value) def help(self): return "a float" class Str(Checker): def check(self, value): if isinstance(value, str): return value raise TypeError() def help(self): return "a string" class Anything(Checker): def check(self, value): return value def help(self): return "anything" class Or(Checker): def __init__(self, *checkers): self.checkers = [get_checker(x) for x in checkers] def check(self, value): for checker in self.checkers: try: return checker.check(value) except Exception as e: pass raise ValueError("None of the condition are valid") def help(self): return ' or '.join([x.help() for x in self.checkers]) class And(Checker): def __init__(self, *checkers): self.checkers = [get_checker(x) for x in checkers] def check(self, value): result = value for checker in self.checkers: result = checker.check(result) return result def help(self): return ' and '.join([x.help() for x in self.checkers]) class InRange(Checker): def __init__(self, min=float('-inf'), max=float('+inf')): self.low = min self.high = max def check(self, value): if value < self.low or value > self.high: raise ValueError() return value def help(self): return f"between {self.low} and {self.high}" class OneOf(Checker): def __init__(self, possible_values): self.possible_values = set(possible_values) def check(self, value): if value not in self.possible_values: raise ValueError() return value def help(self): return f"One of [{', '.join([str(x) for x in self.possible_values])}]" class Module(Checker): def __init__(self): pass def check(self, value): return importlib.import_module(value) def help(self): return "path to python module" class ImportedObject(Checker): def __init__(self): pass def check(self, value): path = value.split('.') module = '.'.join(path[:-1]) imported = importlib.import_module(module) return getattr(imported, path[-1]) def help(self): return "path to python module and an object within" DEFAULT_CHECKERS = { int: Int(), float: Float(), str: Str(), bool: Bool() }
true
true
1c3c13c36821751f07bc687e0f64ade992b00094
4,137
py
Python
scrape_mars.py
bbruzos/Web-scraping-challenge
1c432b80cb368b7c233927b46542f87fe8933f2d
[ "ADSL" ]
null
null
null
scrape_mars.py
bbruzos/Web-scraping-challenge
1c432b80cb368b7c233927b46542f87fe8933f2d
[ "ADSL" ]
null
null
null
scrape_mars.py
bbruzos/Web-scraping-challenge
1c432b80cb368b7c233927b46542f87fe8933f2d
[ "ADSL" ]
null
null
null
from bs4 import BeautifulSoup as bs import requests import pandas as pd from splinter import Browser from webdriver_manager.chrome import ChromeDriverManager def init_browser(): # @NOTE: Replace the path with your actual path to the chromedriver executable_path = {'executable_path': ChromeDriverManager().install()} return Browser("chrome", **executable_path, headless=False) def scrape(): # apply code from mission_to_mars.ipynb browser = init_browser() # Scraping preparation and store data in dictionary get_mars_data = {} url = 'https://mars.nasa.gov/news/' browser.visit(url) response= requests.get(url) soup = bs(response.text, 'html.parser') #Retrieve the latest subject and content from the Mars website news_title = soup.find('div', class_="content_title").find('a').text news_paragraph = soup.find('div', class_="rollover_description_inner").text print('Most Recent Nasa News Article...') print(f'Title: {news_title}') print(f'Substance: {news_paragraph}') # Push values to Mars dictionary get_mars_data['recent_news'] = news_title get_mars_data['recent_news_substance'] = news_paragraph # ## JPL Mars Space Images - Featured Image # Visit the url for JPL Featured Space Image here. # Use splinter to navigate the site and find the image url for the current Featured Mars Image and assign the url string to a variable called featured_image_url. # Url we will be scraping images from url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars' base_url = 'https://www.jpl.nasa.gov' response = requests.get(url) soup = bs(response.text, 'html.parser') splint_url = base_url + soup.find('a', class_="button fancybox")["data-fancybox-href"] print(f"URL to Featured Nasa Image: {splint_url}") # ## Mars Facts # *Visit the Mars Facts webpage here and use Pandas to scrape the table containing facts about the planet including Diameter, Mass, etc. # *Use Pandas to convert the data to a HTML table string. url = 'https://space-facts.com/mars/' # Read table data from url facts_table = pd.read_html(url) # Convert to dataframe mars_facts_df = facts_table[0] mars_facts_df.columns = ['Type', 'Measurement'] mars_facts_df # create HTML table html_table = mars_facts_df.to_html(border=3) #Remove enter characters get_mars_data['mars_facts_html'] = html_table.replace('\n', '') print(get_mars_data['mars_facts_html']) # ## Mars Hemispheres # *Visit the Mars Facts webpage here and use Pandas to scrape the table containing facts about the planet including Diameter, Mass, etc. # *Use Pandas to convert the data to a HTML table string. url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars' base_url = "https://astrogeology.usgs.gov" # Obtain the webpage response = requests.get(url) soup = bs(response.text, 'html.parser') # Grab all image urls and append to list results = soup.find_all('a', class_="itemLink product-item") full_res_img_url = [] for result in results: # Combine link and base url full_res_img_url.append(base_url + result['href']) print(full_res_img_url) #create a empty list for diction hem_img_urls = [] base_url = 'https://astrogeology.usgs.gov' for url in full_res_img_url: # Obtain webpage from diff website response = requests.get(url) soup = bs(response.text, 'html.parser') #Retrieve url to full resolution image image_url = soup.find('div', class_="downloads").find('ul').find('li').find('a')['href'] #Retrieve the subject title = soup.find('h2', class_="title").text #initial diction and put into list res_dict = { "title":title,"img_url": image_url } hem_img_urls.append(res_dict) print(title) print(image_url) print(hem_img_urls) get_mars_data['hemisphere_image_urls'] = hem_img_urls #print all data from diction print(get_mars_data)
35.973913
165
0.688663
from bs4 import BeautifulSoup as bs import requests import pandas as pd from splinter import Browser from webdriver_manager.chrome import ChromeDriverManager def init_browser(): executable_path = {'executable_path': ChromeDriverManager().install()} return Browser("chrome", **executable_path, headless=False) def scrape(): browser = init_browser() get_mars_data = {} url = 'https://mars.nasa.gov/news/' browser.visit(url) response= requests.get(url) soup = bs(response.text, 'html.parser') news_title = soup.find('div', class_="content_title").find('a').text news_paragraph = soup.find('div', class_="rollover_description_inner").text print('Most Recent Nasa News Article...') print(f'Title: {news_title}') print(f'Substance: {news_paragraph}') get_mars_data['recent_news'] = news_title get_mars_data['recent_news_substance'] = news_paragraph y=Mars' base_url = 'https://www.jpl.nasa.gov' response = requests.get(url) soup = bs(response.text, 'html.parser') splint_url = base_url + soup.find('a', class_="button fancybox")["data-fancybox-href"] print(f"URL to Featured Nasa Image: {splint_url}") tps://space-facts.com/mars/' facts_table = pd.read_html(url) mars_facts_df = facts_table[0] mars_facts_df.columns = ['Type', 'Measurement'] mars_facts_df html_table = mars_facts_df.to_html(border=3) get_mars_data['mars_facts_html'] = html_table.replace('\n', '') print(get_mars_data['mars_facts_html']) eology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars' base_url = "https://astrogeology.usgs.gov" response = requests.get(url) soup = bs(response.text, 'html.parser') results = soup.find_all('a', class_="itemLink product-item") full_res_img_url = [] for result in results: full_res_img_url.append(base_url + result['href']) print(full_res_img_url) hem_img_urls = [] base_url = 'https://astrogeology.usgs.gov' for url in full_res_img_url: response = requests.get(url) soup = bs(response.text, 'html.parser') image_url = soup.find('div', class_="downloads").find('ul').find('li').find('a')['href'] title = soup.find('h2', class_="title").text res_dict = { "title":title,"img_url": image_url } hem_img_urls.append(res_dict) print(title) print(image_url) print(hem_img_urls) get_mars_data['hemisphere_image_urls'] = hem_img_urls print(get_mars_data)
true
true
1c3c14bdfc28c2e1a20a60aea74599200803b67b
9,123
py
Python
pgmpy/estimators/EM.py
dg46/pgmpy
caea6ef7c914464736818fb185a1d395937ed52f
[ "MIT" ]
2,144
2015-01-05T21:25:04.000Z
2022-03-31T08:24:15.000Z
pgmpy/estimators/EM.py
dg46/pgmpy
caea6ef7c914464736818fb185a1d395937ed52f
[ "MIT" ]
1,181
2015-01-04T18:19:44.000Z
2022-03-30T17:21:19.000Z
pgmpy/estimators/EM.py
dg46/pgmpy
caea6ef7c914464736818fb185a1d395937ed52f
[ "MIT" ]
777
2015-01-01T11:13:27.000Z
2022-03-28T12:31:57.000Z
import warnings from itertools import product, chain import numpy as np import pandas as pd from tqdm.auto import tqdm from pgmpy.estimators import ParameterEstimator, MaximumLikelihoodEstimator from pgmpy.models import BayesianNetwork from pgmpy.factors.discrete import TabularCPD from pgmpy.global_vars import SHOW_PROGRESS class ExpectationMaximization(ParameterEstimator): def __init__(self, model, data, **kwargs): """ Class used to compute parameters for a model using Expectation Maximization (EM). EM is an iterative algorithm commonly used for estimation in the case when there are latent variables in the model. The algorithm iteratively improves the parameter estimates maximizing the likelihood of the given data. Parameters ---------- model: A pgmpy.models.BayesianNetwork instance data: pandas DataFrame object DataFrame object with column names identical to the variable names of the network. (If some values in the data are missing the data cells should be set to `numpy.NaN`. Note that pandas converts each column containing `numpy.NaN`s to dtype `float`.) state_names: dict (optional) A dict indicating, for each variable, the discrete set of states that the variable can take. If unspecified, the observed values in the data set are taken to be the only possible states. complete_samples_only: bool (optional, default `True`) Specifies how to deal with missing data, if present. If set to `True` all rows that contain `np.NaN` somewhere are ignored. If `False` then, for each variable, every row where neither the variable nor its parents are `np.NaN` is used. Examples -------- >>> import numpy as np >>> import pandas as pd >>> from pgmpy.models import BayesianNetwork >>> from pgmpy.estimators import ExpectationMaximization >>> data = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 5)), ... columns=['A', 'B', 'C', 'D', 'E']) >>> model = BayesianNetwork([('A', 'B'), ('C', 'B'), ('C', 'D'), ('B', 'E')]) >>> estimator = ExpectationMaximization(model, data) """ if not isinstance(model, BayesianNetwork): raise NotImplementedError( "Expectation Maximization is only implemented for BayesianNetwork" ) super(ExpectationMaximization, self).__init__(model, data, **kwargs) self.model_copy = self.model.copy() def _get_likelihood(self, datapoint): """ Computes the likelihood of a given datapoint. Goes through each CPD matching the combination of states to get the value and multiplies them together. """ likelihood = 1 with warnings.catch_warnings(): warnings.simplefilter("ignore") for cpd in self.model_copy.cpds: scope = set(cpd.scope()) likelihood *= cpd.get_value( **{key: value for key, value in datapoint.items() if key in scope} ) return likelihood def _compute_weights(self, latent_card): """ For each data point, creates extra data points for each possible combination of states of latent variables and assigns weights to each of them. """ cache = [] data_unique = self.data.drop_duplicates() n_counts = self.data.groupby(list(self.data.columns)).size().to_dict() for i in range(data_unique.shape[0]): v = list(product(*[range(card) for card in latent_card.values()])) latent_combinations = np.array(v, dtype=int) df = data_unique.iloc[[i] * latent_combinations.shape[0]].reset_index( drop=True ) for index, latent_var in enumerate(latent_card.keys()): df[latent_var] = latent_combinations[:, index] weights = df.apply(lambda t: self._get_likelihood(dict(t)), axis=1) df["_weight"] = (weights / weights.sum()) * n_counts[ tuple(data_unique.iloc[i]) ] cache.append(df) return pd.concat(cache, copy=False) def _is_converged(self, new_cpds, atol=1e-08): """ Checks if the values of `new_cpds` is within tolerance limits of current model cpds. """ for cpd in new_cpds: if not cpd.__eq__(self.model_copy.get_cpds(node=cpd.scope()[0]), atol=atol): return False return True def get_parameters( self, latent_card=None, max_iter=100, atol=1e-08, n_jobs=-1, seed=None, show_progress=True, ): """ Method to estimate all model parameters (CPDs) using Expecation Maximization. Parameters ---------- latent_card: dict (default: None) A dictionary of the form {latent_var: cardinality} specifying the cardinality (number of states) of each latent variable. If None, assumes `2` states for each latent variable. max_iter: int (default: 100) The maximum number of iterations the algorithm is allowed to run for. If max_iter is reached, return the last value of parameters. atol: int (default: 1e-08) The absolute accepted tolerance for checking convergence. If the parameters change is less than atol in an iteration, the algorithm will exit. n_jobs: int (default: -1) Number of jobs to run in parallel. Default: -1 uses all the processors. seed: int The random seed to use for generating the intial values. show_progress: boolean (default: True) Whether to show a progress bar for iterations. Returns ------- list: A list of estimated CPDs for the model. Examples -------- >>> import numpy as np >>> import pandas as pd >>> from pgmpy.models import BayesianNetwork >>> from pgmpy.estimators import ExpectationMaximization as EM >>> data = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 3)), ... columns=['A', 'C', 'D']) >>> model = BayesianNetwork([('A', 'B'), ('C', 'B'), ('C', 'D')], latents={'B'}) >>> estimator = EM(model, data) >>> estimator.get_parameters(latent_card={'B': 3}) [<TabularCPD representing P(C:2) at 0x7f7b534251d0>, <TabularCPD representing P(B:3 | C:2, A:2) at 0x7f7b4dfd4da0>, <TabularCPD representing P(A:2) at 0x7f7b4dfd4fd0>, <TabularCPD representing P(D:2 | C:2) at 0x7f7b4df822b0>] """ # Step 1: Parameter checks if latent_card is None: latent_card = {var: 2 for var in self.model_copy.latents} # Step 2: Create structures/variables to be used later. n_states_dict = {key: len(value) for key, value in self.state_names.items()} n_states_dict.update(latent_card) for var in self.model_copy.latents: self.state_names[var] = list(range(n_states_dict[var])) # Step 3: Initialize random CPDs if starting values aren't provided. if seed is not None: np.random.seed(seed) cpds = [] for node in self.model_copy.nodes(): parents = list(self.model_copy.predecessors(node)) cpds.append( TabularCPD.get_random( variable=node, evidence=parents, cardinality={ var: n_states_dict[var] for var in chain([node], parents) }, state_names={ var: self.state_names[var] for var in chain([node], parents) }, ) ) self.model_copy.add_cpds(*cpds) if show_progress and SHOW_PROGRESS: pbar = tqdm(total=max_iter) # Step 4: Run the EM algorithm. for _ in range(max_iter): # Step 4.1: E-step: Expands the dataset and computes the likelihood of each # possible state of latent variables. weighted_data = self._compute_weights(latent_card) # Step 4.2: M-step: Uses the weights of the dataset to do a weighted MLE. new_cpds = MaximumLikelihoodEstimator( self.model_copy, weighted_data ).get_parameters(n_jobs=n_jobs, weighted=True) # Step 4.3: Check of convergence and max_iter if self._is_converged(new_cpds, atol=atol): if show_progress and SHOW_PROGRESS: pbar.close() return new_cpds else: self.model_copy.cpds = new_cpds if show_progress and SHOW_PROGRESS: pbar.update(1) return cpds
39.493506
88
0.59213
import warnings from itertools import product, chain import numpy as np import pandas as pd from tqdm.auto import tqdm from pgmpy.estimators import ParameterEstimator, MaximumLikelihoodEstimator from pgmpy.models import BayesianNetwork from pgmpy.factors.discrete import TabularCPD from pgmpy.global_vars import SHOW_PROGRESS class ExpectationMaximization(ParameterEstimator): def __init__(self, model, data, **kwargs): if not isinstance(model, BayesianNetwork): raise NotImplementedError( "Expectation Maximization is only implemented for BayesianNetwork" ) super(ExpectationMaximization, self).__init__(model, data, **kwargs) self.model_copy = self.model.copy() def _get_likelihood(self, datapoint): likelihood = 1 with warnings.catch_warnings(): warnings.simplefilter("ignore") for cpd in self.model_copy.cpds: scope = set(cpd.scope()) likelihood *= cpd.get_value( **{key: value for key, value in datapoint.items() if key in scope} ) return likelihood def _compute_weights(self, latent_card): cache = [] data_unique = self.data.drop_duplicates() n_counts = self.data.groupby(list(self.data.columns)).size().to_dict() for i in range(data_unique.shape[0]): v = list(product(*[range(card) for card in latent_card.values()])) latent_combinations = np.array(v, dtype=int) df = data_unique.iloc[[i] * latent_combinations.shape[0]].reset_index( drop=True ) for index, latent_var in enumerate(latent_card.keys()): df[latent_var] = latent_combinations[:, index] weights = df.apply(lambda t: self._get_likelihood(dict(t)), axis=1) df["_weight"] = (weights / weights.sum()) * n_counts[ tuple(data_unique.iloc[i]) ] cache.append(df) return pd.concat(cache, copy=False) def _is_converged(self, new_cpds, atol=1e-08): for cpd in new_cpds: if not cpd.__eq__(self.model_copy.get_cpds(node=cpd.scope()[0]), atol=atol): return False return True def get_parameters( self, latent_card=None, max_iter=100, atol=1e-08, n_jobs=-1, seed=None, show_progress=True, ): if latent_card is None: latent_card = {var: 2 for var in self.model_copy.latents} n_states_dict = {key: len(value) for key, value in self.state_names.items()} n_states_dict.update(latent_card) for var in self.model_copy.latents: self.state_names[var] = list(range(n_states_dict[var])) if seed is not None: np.random.seed(seed) cpds = [] for node in self.model_copy.nodes(): parents = list(self.model_copy.predecessors(node)) cpds.append( TabularCPD.get_random( variable=node, evidence=parents, cardinality={ var: n_states_dict[var] for var in chain([node], parents) }, state_names={ var: self.state_names[var] for var in chain([node], parents) }, ) ) self.model_copy.add_cpds(*cpds) if show_progress and SHOW_PROGRESS: pbar = tqdm(total=max_iter) # Step 4: Run the EM algorithm. for _ in range(max_iter): # Step 4.1: E-step: Expands the dataset and computes the likelihood of each # possible state of latent variables. weighted_data = self._compute_weights(latent_card) # Step 4.2: M-step: Uses the weights of the dataset to do a weighted MLE. new_cpds = MaximumLikelihoodEstimator( self.model_copy, weighted_data ).get_parameters(n_jobs=n_jobs, weighted=True) # Step 4.3: Check of convergence and max_iter if self._is_converged(new_cpds, atol=atol): if show_progress and SHOW_PROGRESS: pbar.close() return new_cpds else: self.model_copy.cpds = new_cpds if show_progress and SHOW_PROGRESS: pbar.update(1) return cpds
true
true
1c3c16f2f9c12a308f80775d111741f371af1209
1,044
py
Python
python/bitcoin_101/bitcoin_client.py
fcracker79/python_bitcoin_101
3af1b1e1b817d9676981f3c6c87d93064ac8febe
[ "MIT" ]
1
2018-09-26T18:10:36.000Z
2018-09-26T18:10:36.000Z
python/bitcoin_101/bitcoin_client.py
fcracker79/python_bitcoin_101
3af1b1e1b817d9676981f3c6c87d93064ac8febe
[ "MIT" ]
null
null
null
python/bitcoin_101/bitcoin_client.py
fcracker79/python_bitcoin_101
3af1b1e1b817d9676981f3c6c87d93064ac8febe
[ "MIT" ]
null
null
null
import base64 from bitcoin_101 import bitjson_dumps, bitjson_loads import requests class BitcoinClient: def __init__(self): btcd_auth_header = b'Basic ' + base64.b64encode(b'bitcoin:qwertyuiop') self.btcd_headers = {'content-type': 'application/json', 'Authorization': btcd_auth_header} def __getattr__(self, item): if item == '_call': return self._call return lambda *a, **kw: self._call(item, *a, **kw) def _call(self, method: str, *params, expect_json: bool=True): payload = bitjson_dumps({ 'method': method, 'params': params, 'jsonrpc': '2.0', 'id': 0, }) resp = requests.post('http://localhost:18332', data=payload, headers=self.btcd_headers) content = resp.text if expect_json: content = bitjson_loads(content) if content['error']: raise ValueError('Error: {}'.format(content['error'])) return content['result'] return content
30.705882
99
0.59387
import base64 from bitcoin_101 import bitjson_dumps, bitjson_loads import requests class BitcoinClient: def __init__(self): btcd_auth_header = b'Basic ' + base64.b64encode(b'bitcoin:qwertyuiop') self.btcd_headers = {'content-type': 'application/json', 'Authorization': btcd_auth_header} def __getattr__(self, item): if item == '_call': return self._call return lambda *a, **kw: self._call(item, *a, **kw) def _call(self, method: str, *params, expect_json: bool=True): payload = bitjson_dumps({ 'method': method, 'params': params, 'jsonrpc': '2.0', 'id': 0, }) resp = requests.post('http://localhost:18332', data=payload, headers=self.btcd_headers) content = resp.text if expect_json: content = bitjson_loads(content) if content['error']: raise ValueError('Error: {}'.format(content['error'])) return content['result'] return content
true
true
1c3c1726f5d0b409cb8cfc71d00d47de1723023a
3,345
py
Python
rlpyt/ul/envs/atari.py
traffic-lights/rlpyt
ec4689cddd55d98c037194685cfd6ca8e6785014
[ "MIT" ]
2,122
2019-07-02T13:19:10.000Z
2022-03-22T09:59:42.000Z
rlpyt/ul/envs/atari.py
traffic-lights/rlpyt
ec4689cddd55d98c037194685cfd6ca8e6785014
[ "MIT" ]
206
2019-07-02T14:19:42.000Z
2022-02-15T02:34:28.000Z
rlpyt/ul/envs/atari.py
traffic-lights/rlpyt
ec4689cddd55d98c037194685cfd6ca8e6785014
[ "MIT" ]
369
2019-07-02T13:38:28.000Z
2022-03-28T11:16:39.000Z
import numpy as np import cv2 import atari_py import os from rlpyt.spaces.int_box import IntBox from rlpyt.envs.atari.atari_env import AtariEnv from rlpyt.utils.quick_args import save__init__args class AtariEnv84(AtariEnv): """ Same as built-in AtariEnv except returns standard 84x84 frames. Actually, can resize the image to whatever square size you want. """ def __init__(self, game="pong", frame_skip=4, num_img_obs=4, clip_reward=True, episodic_lives=False, # ! max_start_noops=30, repeat_action_probability=0.25, # ! horizon=27000, obs_size=84, # square resize fire_on_reset=True, ): save__init__args(locals(), underscore=True) # ALE game_path = atari_py.get_game_path(game) if not os.path.exists(game_path): raise IOError("You asked for game {} but path {} does not " " exist".format(game, game_path)) self.ale = atari_py.ALEInterface() self.ale.setFloat(b'repeat_action_probability', repeat_action_probability) self.ale.loadROM(game_path) # Spaces self._obs_size = obs_size self._action_set = self.ale.getMinimalActionSet() self._action_space = IntBox(low=0, high=len(self._action_set)) obs_shape = (num_img_obs, self._obs_size, self._obs_size) self._observation_space = IntBox(low=0, high=256, shape=obs_shape, dtype="uint8") self._max_frame = self.ale.getScreenGrayscale() self._raw_frame_1 = self._max_frame.copy() self._raw_frame_2 = self._max_frame.copy() self._obs = np.zeros(shape=obs_shape, dtype="uint8") # Settings self._has_fire = "FIRE" in self.get_action_meanings() self._has_up = "UP" in self.get_action_meanings() self._horizon = int(horizon) self.reset() def reset(self): """Performs hard reset of ALE game.""" self.ale.reset_game() self._reset_obs() self._life_reset() for _ in range(np.random.randint(0, self._max_start_noops + 1)): self.ale.act(0) if self._fire_on_reset: self.fire_and_up() self._update_obs() # (don't bother to populate any frame history) self._step_counter = 0 return self.get_obs() def _update_obs(self): """Max of last two frames; resize to standard 84x84.""" self._get_screen(2) np.maximum(self._raw_frame_1, self._raw_frame_2, self._max_frame) img = cv2.resize(self._max_frame, (self._obs_size, self._obs_size), cv2.INTER_AREA) # NOTE: order OLDEST to NEWEST should match use in frame-wise buffer. self._obs = np.concatenate([self._obs[1:], img[np.newaxis]]) def _life_reset(self): self.ale.act(0) # (advance from lost life state) self._lives = self.ale.lives() def fire_and_up(self): if self._has_fire: # TODO: for sticky actions, make sure fire is actually pressed self.ale.act(1) # (e.g. needed in Breakout, not sure what others) if self._has_up: self.ale.act(2) # (not sure if this is necessary, saw it somewhere)
37.166667
91
0.615546
import numpy as np import cv2 import atari_py import os from rlpyt.spaces.int_box import IntBox from rlpyt.envs.atari.atari_env import AtariEnv from rlpyt.utils.quick_args import save__init__args class AtariEnv84(AtariEnv): def __init__(self, game="pong", frame_skip=4, num_img_obs=4, clip_reward=True, episodic_lives=False, max_start_noops=30, repeat_action_probability=0.25, horizon=27000, obs_size=84, fire_on_reset=True, ): save__init__args(locals(), underscore=True) game_path = atari_py.get_game_path(game) if not os.path.exists(game_path): raise IOError("You asked for game {} but path {} does not " " exist".format(game, game_path)) self.ale = atari_py.ALEInterface() self.ale.setFloat(b'repeat_action_probability', repeat_action_probability) self.ale.loadROM(game_path) self._obs_size = obs_size self._action_set = self.ale.getMinimalActionSet() self._action_space = IntBox(low=0, high=len(self._action_set)) obs_shape = (num_img_obs, self._obs_size, self._obs_size) self._observation_space = IntBox(low=0, high=256, shape=obs_shape, dtype="uint8") self._max_frame = self.ale.getScreenGrayscale() self._raw_frame_1 = self._max_frame.copy() self._raw_frame_2 = self._max_frame.copy() self._obs = np.zeros(shape=obs_shape, dtype="uint8") self._has_fire = "FIRE" in self.get_action_meanings() self._has_up = "UP" in self.get_action_meanings() self._horizon = int(horizon) self.reset() def reset(self): self.ale.reset_game() self._reset_obs() self._life_reset() for _ in range(np.random.randint(0, self._max_start_noops + 1)): self.ale.act(0) if self._fire_on_reset: self.fire_and_up() self._update_obs() self._step_counter = 0 return self.get_obs() def _update_obs(self): self._get_screen(2) np.maximum(self._raw_frame_1, self._raw_frame_2, self._max_frame) img = cv2.resize(self._max_frame, (self._obs_size, self._obs_size), cv2.INTER_AREA) # NOTE: order OLDEST to NEWEST should match use in frame-wise buffer. self._obs = np.concatenate([self._obs[1:], img[np.newaxis]]) def _life_reset(self): self.ale.act(0) # (advance from lost life state) self._lives = self.ale.lives() def fire_and_up(self): if self._has_fire: # TODO: for sticky actions, make sure fire is actually pressed self.ale.act(1) # (e.g. needed in Breakout, not sure what others) if self._has_up: self.ale.act(2) # (not sure if this is necessary, saw it somewhere)
true
true
1c3c17813cd1d03fcc24ee310d43a134760247e8
4,011
py
Python
cliboa/adapter/sftp.py
bp-gen-aihara/cliboa
978b5b484a988083768e0ebb021ff5480180e9cc
[ "MIT" ]
27
2019-11-11T11:09:47.000Z
2022-03-01T14:27:59.000Z
cliboa/adapter/sftp.py
bp-gen-aihara/cliboa
978b5b484a988083768e0ebb021ff5480180e9cc
[ "MIT" ]
228
2019-11-11T11:04:26.000Z
2022-03-29T02:16:05.000Z
cliboa/adapter/sftp.py
bp-gen-aihara/cliboa
978b5b484a988083768e0ebb021ff5480180e9cc
[ "MIT" ]
11
2019-11-12T03:15:52.000Z
2022-01-11T05:46:02.000Z
# # Copyright BrainPad Inc. All Rights Reserved. # # 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. # import logging from time import sleep from paramiko import AutoAddPolicy, SSHClient class SftpAdapter(object): """ Sftp Adaptor """ TIMEOUT_SEC = 30 def __init__( self, host, user, password=None, key=None, passphrase=None, timeout=TIMEOUT_SEC, retryTimes=3, port=22, ): """ Must set whether password or key Args: host (str): hostname user (str): username password (str): password key (path): private key path passphrase (str): passphrase timeout=30 (int): timeout seconds retryTimes=3 (int): retry count port=22 (int): port number Raises: ValueError: both password and private key are empty, or both specified. """ logging.getLogger("paramiko").setLevel(logging.CRITICAL) if (not password and not key) or (password and key): raise ValueError("Illegal paramters are given.") self._host = host self._user = user self._password = password self._key = key self._passphrase = passphrase self._timeout = timeout self._retryTimes = retryTimes self._port = 22 if port is None else port self._logger = logging.getLogger(__name__) def execute(self, obj): """ Execute sftp process. Pass a result of cliboa.util.sftp.Sftp.{{ function }} for the arguments. Args: obj (tuple): obj[0]: A function to be executed. obj[1]: Arguments when function is executed. """ return self._execute(obj[0], obj[1]) def _execute(self, func, kwargs): if not func: raise ValueError("Function must not be empty.") err = None for _ in range(self._retryTimes): ssh = None sftp = None try: ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy()) if self._password: ssh.connect( hostname=self._host, username=self._user, password=self._password, port=self._port, timeout=self._timeout, ) else: ssh.connect( hostname=self._host, username=self._user, key_filename=self._key, passphrase=self._passphrase, port=self._port, timeout=self._timeout, ) sftp = ssh.open_sftp() # call the argument function ret = func(sftp=sftp, **kwargs) return ret except Exception as e: self._logger.warning(e) self._logger.warning(kwargs) err = e finally: if sftp is not None: sftp.close() if ssh is not None: ssh.close() self._logger.warning("Unexpected error occurred. Retry will start in 10 sec.") sleep(10) raise IOError(err, "SFTP failed.")
29.932836
90
0.537522
import logging from time import sleep from paramiko import AutoAddPolicy, SSHClient class SftpAdapter(object): TIMEOUT_SEC = 30 def __init__( self, host, user, password=None, key=None, passphrase=None, timeout=TIMEOUT_SEC, retryTimes=3, port=22, ): logging.getLogger("paramiko").setLevel(logging.CRITICAL) if (not password and not key) or (password and key): raise ValueError("Illegal paramters are given.") self._host = host self._user = user self._password = password self._key = key self._passphrase = passphrase self._timeout = timeout self._retryTimes = retryTimes self._port = 22 if port is None else port self._logger = logging.getLogger(__name__) def execute(self, obj): return self._execute(obj[0], obj[1]) def _execute(self, func, kwargs): if not func: raise ValueError("Function must not be empty.") err = None for _ in range(self._retryTimes): ssh = None sftp = None try: ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy()) if self._password: ssh.connect( hostname=self._host, username=self._user, password=self._password, port=self._port, timeout=self._timeout, ) else: ssh.connect( hostname=self._host, username=self._user, key_filename=self._key, passphrase=self._passphrase, port=self._port, timeout=self._timeout, ) sftp = ssh.open_sftp() ret = func(sftp=sftp, **kwargs) return ret except Exception as e: self._logger.warning(e) self._logger.warning(kwargs) err = e finally: if sftp is not None: sftp.close() if ssh is not None: ssh.close() self._logger.warning("Unexpected error occurred. Retry will start in 10 sec.") sleep(10) raise IOError(err, "SFTP failed.")
true
true
1c3c1a1f7a8dfa35cd7c76d0f8fb37fa6fc86163
9,929
py
Python
net/gnn_base.py
Steven177/intra_batch
7fa9340ee39f5970f308153931620bcf061d6285
[ "MIT" ]
null
null
null
net/gnn_base.py
Steven177/intra_batch
7fa9340ee39f5970f308153931620bcf061d6285
[ "MIT" ]
null
null
null
net/gnn_base.py
Steven177/intra_batch
7fa9340ee39f5970f308153931620bcf061d6285
[ "MIT" ]
null
null
null
from torch_scatter import scatter_mean, scatter_max, scatter_add import torch from torch import nn import math import torch.nn.functional as F import numpy as np import torch import logging from .utils import * from .attentions import MultiHeadDotProduct import torch.utils.checkpoint as checkpoint logger = logging.getLogger('GNNReID.GNNModule') class MetaLayer(torch.nn.Module): """ Core Message Passing Network Class. Extracted from torch_geometric, with minor modifications. (https://github.com/rusty1s/pytorch_geometric/blob/master/torch_geometric/nn/meta.py) """ def __init__(self, edge_model=None, node_model=None): super(MetaLayer, self).__init__() self.edge_model = edge_model # possible to add edge model self.node_model = node_model self.reset_parameters() def reset_parameters(self): for item in [self.node_model, self.edge_model]: if hasattr(item, 'reset_parameters'): item.reset_parameters() def forward(self, feats, edge_index, edge_attr=None): r, c = edge_index[:, 0], edge_index[:, 1] if self.edge_model is not None: edge_attr = torch.cat([feats[r], feats[c], edge_attr], dim=1) edge_attr = self.edge_model(edge_attr) if self.node_model is not None: feats, edge_index, edge_attr = self.node_model(feats, edge_index, edge_attr) return feats, edge_index, edge_attr def __repr__(self): if self.edge_model: return ('{}(\n' ' edge_model={},\n' ' node_model={},\n' ')').format(self.__class__.__name__, self.edge_model, self.node_model) else: return ('{}(\n' ' node_model={},\n' ')').format(self.__class__.__name__, self.node_model) class GNNReID(nn.Module): def __init__(self, dev, params: dict = None, embed_dim: int = 2048): super(GNNReID, self).__init__() num_classes = params['classifier']['num_classes'] self.dev = dev self.params = params self.gnn_params = params['gnn'] self.dim_red = nn.Linear(embed_dim, int(embed_dim/params['red'])) logger.info("Embed dim old {}, new".format(embed_dim, embed_dim/params['red'])) embed_dim = int(embed_dim/params['red']) logger.info("Embed dim {}".format(embed_dim)) self.gnn_model = self._build_GNN_Net(embed_dim=embed_dim) # classifier self.neck = params['classifier']['neck'] dim = self.gnn_params['num_layers'] * embed_dim if self.params['cat'] else embed_dim every = self.params['every'] if self.neck: layers = [nn.BatchNorm1d(dim) for _ in range(self.gnn_params['num_layers'])] if every else [nn.BatchNorm1d(dim)] self.bottleneck = Sequential(*layers) for layer in self.bottleneck: layer.bias.requires_grad_(False) layer.apply(weights_init_kaiming) layers = [nn.Linear(dim, num_classes, bias=False) for _ in range(self.gnn_params['num_layers'])] if every else [nn.Linear(dim, num_classes, bias=False)] self.fc = Sequential(*layers) for layer in self.fc: layer.apply(weights_init_classifier) else: layers = [nn.Linear(dim, num_classes) for _ in range(self.gnn_params['num_layers'])] if every else [nn.Linear(dim, num_classes)] self.fc = Sequential(*layers) def _build_GNN_Net(self, embed_dim: int = 2048): # init aggregator if self.gnn_params['aggregator'] == "add": self.aggr = lambda out, row, dim, x_size: scatter_add(out, row, dim=dim, dim_size=x_size) if self.gnn_params['aggregator'] == "mean": self.aggr = lambda out, row, dim, x_size: scatter_mean(out, row, dim=dim, dim_size=x_size) if self.gnn_params['aggregator'] == "max": self.aggr = lambda out, row, dim, x_size: scatter_max(out, row, dim=dim, dim_size=x_size) gnn = GNNNetwork(embed_dim, self.aggr, self.dev, self.gnn_params, self.gnn_params['num_layers'] ) return MetaLayer(node_model=gnn) def forward(self, feats, edge_index, edge_attr=None, output_option='norm'): r, c = edge_index[:, 0], edge_index[:, 1] if self.dim_red is not None: feats = self.dim_red(feats) feats, _, _ = self.gnn_model(feats, edge_index, edge_attr) if self.params['cat']: feats = [torch.cat(feats, dim=1).to(self.dev)] elif self.params['every']: feats = feats else: feats = [feats[-1]] if self.neck: features = list() for i, layer in enumerate(self.bottleneck): f = layer(feats[i]) features.append(f) else: features = feats x = list() for i, layer in enumerate(self.fc): f = layer(features[i]) x.append(f) if output_option == 'norm': return x, feats elif output_option == 'plain': return x, [F.normalize(f, p=2, dim=1) for f in feats] elif output_option == 'neck' and self.neck: return x, features elif output_option == 'neck' and not self.neck: print("Output option neck only avaiable if bottleneck (neck) is " "enabeled - giving back x and fc7") return x, feats return x, feats class GNNNetwork(nn.Module): def __init__(self, embed_dim, aggr, dev, gnn_params, num_layers): super(GNNNetwork, self).__init__() layers = [DotAttentionLayer(embed_dim, aggr, dev, gnn_params) for _ in range(num_layers)] self.layers = Sequential(*layers) def forward(self, feats, edge_index, edge_attr): out = list() for layer in self.layers: feats, egde_index, edge_attr = layer(feats, edge_index, edge_attr) out.append(feats) return out, edge_index, edge_attr class DotAttentionLayer(nn.Module): def __init__(self, embed_dim, aggr, dev, params, d_hid=None): super(DotAttentionLayer, self).__init__() num_heads = params['num_heads'] self.res1 = params['res1'] self.res2 = params['res2'] self.prenorm = True if params['prenorm'] else None self.att = MultiHeadDotProduct(embed_dim, num_heads, params['aggregator'], True, mult_attr=params['mult_attr']).to(dev) if params['att'] else None d_hid = 4 * embed_dim if d_hid is None else d_hid self.mlp = params['mlp'] self.linear1 = nn.Linear(embed_dim, d_hid) if params['mlp'] else None self.dropout = nn.Dropout(params['dropout_mlp']) self.linear2 = nn.Linear(d_hid, embed_dim) if params['mlp'] else None self.norm1 = LayerNorm(embed_dim) if params['norm1'] else None self.norm2 = LayerNorm(embed_dim) if params['norm2'] else None self.dropout1 = nn.Dropout(params['dropout_1']) self.dropout2 = nn.Dropout(params['dropout_2']) self.act = F.relu self.dummy_tensor = torch.ones(1, requires_grad=True) def custom(self): def custom_forward(*inputs): feats2 = self.att(inputs[0], inputs[1], inputs[2]) return feats2 return custom_forward def forward(self, feats, egde_index, edge_attr): if self.prenorm: # Layer 1 if self.norm1: feats2 = self.norm1(feats) else: feats2 = feats if self.att: feats2 = self.att(feats2, egde_index, edge_attr) feats2 = self.dropout1(feats2) if self.res1: feats = feats + feats2 else: feats = feats2 # Layer 2 if self.norm2: feats2 = self.norm2(feats) else: feats2 = feats if self.mlp: feats2 = self.linear2(self.dropout(self.act(self.linear1(feats2)))) feats2 = self.dropout2(feats2) if self.res2: feats = feats + feats2 else: feats = feats2 else: # Layer 1 if self.att: feats2 = self.att(feats, egde_index, edge_attr) else: feats2 = feats feats2 = self.dropout1(feats2) if self.res1: feats = feats + feats2 else: feats = feats2 if self.norm1: feats = self.norm1(feats) # Layer 2 if self.mlp: feats2 = self.linear2(self.dropout(self.act(self.linear1(feats)))) else: feats2 = feats feats2 = self.dropout2(feats2) if self.res2: feats = feats + feats2 else: feats = feats2 if self.norm2: feats = self.norm2(feats) return feats, egde_index, edge_attr
37.467925
164
0.5352
from torch_scatter import scatter_mean, scatter_max, scatter_add import torch from torch import nn import math import torch.nn.functional as F import numpy as np import torch import logging from .utils import * from .attentions import MultiHeadDotProduct import torch.utils.checkpoint as checkpoint logger = logging.getLogger('GNNReID.GNNModule') class MetaLayer(torch.nn.Module): def __init__(self, edge_model=None, node_model=None): super(MetaLayer, self).__init__() self.edge_model = edge_model self.node_model = node_model self.reset_parameters() def reset_parameters(self): for item in [self.node_model, self.edge_model]: if hasattr(item, 'reset_parameters'): item.reset_parameters() def forward(self, feats, edge_index, edge_attr=None): r, c = edge_index[:, 0], edge_index[:, 1] if self.edge_model is not None: edge_attr = torch.cat([feats[r], feats[c], edge_attr], dim=1) edge_attr = self.edge_model(edge_attr) if self.node_model is not None: feats, edge_index, edge_attr = self.node_model(feats, edge_index, edge_attr) return feats, edge_index, edge_attr def __repr__(self): if self.edge_model: return ('{}(\n' ' edge_model={},\n' ' node_model={},\n' ')').format(self.__class__.__name__, self.edge_model, self.node_model) else: return ('{}(\n' ' node_model={},\n' ')').format(self.__class__.__name__, self.node_model) class GNNReID(nn.Module): def __init__(self, dev, params: dict = None, embed_dim: int = 2048): super(GNNReID, self).__init__() num_classes = params['classifier']['num_classes'] self.dev = dev self.params = params self.gnn_params = params['gnn'] self.dim_red = nn.Linear(embed_dim, int(embed_dim/params['red'])) logger.info("Embed dim old {}, new".format(embed_dim, embed_dim/params['red'])) embed_dim = int(embed_dim/params['red']) logger.info("Embed dim {}".format(embed_dim)) self.gnn_model = self._build_GNN_Net(embed_dim=embed_dim) self.neck = params['classifier']['neck'] dim = self.gnn_params['num_layers'] * embed_dim if self.params['cat'] else embed_dim every = self.params['every'] if self.neck: layers = [nn.BatchNorm1d(dim) for _ in range(self.gnn_params['num_layers'])] if every else [nn.BatchNorm1d(dim)] self.bottleneck = Sequential(*layers) for layer in self.bottleneck: layer.bias.requires_grad_(False) layer.apply(weights_init_kaiming) layers = [nn.Linear(dim, num_classes, bias=False) for _ in range(self.gnn_params['num_layers'])] if every else [nn.Linear(dim, num_classes, bias=False)] self.fc = Sequential(*layers) for layer in self.fc: layer.apply(weights_init_classifier) else: layers = [nn.Linear(dim, num_classes) for _ in range(self.gnn_params['num_layers'])] if every else [nn.Linear(dim, num_classes)] self.fc = Sequential(*layers) def _build_GNN_Net(self, embed_dim: int = 2048): if self.gnn_params['aggregator'] == "add": self.aggr = lambda out, row, dim, x_size: scatter_add(out, row, dim=dim, dim_size=x_size) if self.gnn_params['aggregator'] == "mean": self.aggr = lambda out, row, dim, x_size: scatter_mean(out, row, dim=dim, dim_size=x_size) if self.gnn_params['aggregator'] == "max": self.aggr = lambda out, row, dim, x_size: scatter_max(out, row, dim=dim, dim_size=x_size) gnn = GNNNetwork(embed_dim, self.aggr, self.dev, self.gnn_params, self.gnn_params['num_layers'] ) return MetaLayer(node_model=gnn) def forward(self, feats, edge_index, edge_attr=None, output_option='norm'): r, c = edge_index[:, 0], edge_index[:, 1] if self.dim_red is not None: feats = self.dim_red(feats) feats, _, _ = self.gnn_model(feats, edge_index, edge_attr) if self.params['cat']: feats = [torch.cat(feats, dim=1).to(self.dev)] elif self.params['every']: feats = feats else: feats = [feats[-1]] if self.neck: features = list() for i, layer in enumerate(self.bottleneck): f = layer(feats[i]) features.append(f) else: features = feats x = list() for i, layer in enumerate(self.fc): f = layer(features[i]) x.append(f) if output_option == 'norm': return x, feats elif output_option == 'plain': return x, [F.normalize(f, p=2, dim=1) for f in feats] elif output_option == 'neck' and self.neck: return x, features elif output_option == 'neck' and not self.neck: print("Output option neck only avaiable if bottleneck (neck) is " "enabeled - giving back x and fc7") return x, feats return x, feats class GNNNetwork(nn.Module): def __init__(self, embed_dim, aggr, dev, gnn_params, num_layers): super(GNNNetwork, self).__init__() layers = [DotAttentionLayer(embed_dim, aggr, dev, gnn_params) for _ in range(num_layers)] self.layers = Sequential(*layers) def forward(self, feats, edge_index, edge_attr): out = list() for layer in self.layers: feats, egde_index, edge_attr = layer(feats, edge_index, edge_attr) out.append(feats) return out, edge_index, edge_attr class DotAttentionLayer(nn.Module): def __init__(self, embed_dim, aggr, dev, params, d_hid=None): super(DotAttentionLayer, self).__init__() num_heads = params['num_heads'] self.res1 = params['res1'] self.res2 = params['res2'] self.prenorm = True if params['prenorm'] else None self.att = MultiHeadDotProduct(embed_dim, num_heads, params['aggregator'], True, mult_attr=params['mult_attr']).to(dev) if params['att'] else None d_hid = 4 * embed_dim if d_hid is None else d_hid self.mlp = params['mlp'] self.linear1 = nn.Linear(embed_dim, d_hid) if params['mlp'] else None self.dropout = nn.Dropout(params['dropout_mlp']) self.linear2 = nn.Linear(d_hid, embed_dim) if params['mlp'] else None self.norm1 = LayerNorm(embed_dim) if params['norm1'] else None self.norm2 = LayerNorm(embed_dim) if params['norm2'] else None self.dropout1 = nn.Dropout(params['dropout_1']) self.dropout2 = nn.Dropout(params['dropout_2']) self.act = F.relu self.dummy_tensor = torch.ones(1, requires_grad=True) def custom(self): def custom_forward(*inputs): feats2 = self.att(inputs[0], inputs[1], inputs[2]) return feats2 return custom_forward def forward(self, feats, egde_index, edge_attr): if self.prenorm: if self.norm1: feats2 = self.norm1(feats) else: feats2 = feats if self.att: feats2 = self.att(feats2, egde_index, edge_attr) feats2 = self.dropout1(feats2) if self.res1: feats = feats + feats2 else: feats = feats2 if self.norm2: feats2 = self.norm2(feats) else: feats2 = feats if self.mlp: feats2 = self.linear2(self.dropout(self.act(self.linear1(feats2)))) feats2 = self.dropout2(feats2) if self.res2: feats = feats + feats2 else: feats = feats2 else: if self.att: feats2 = self.att(feats, egde_index, edge_attr) else: feats2 = feats feats2 = self.dropout1(feats2) if self.res1: feats = feats + feats2 else: feats = feats2 if self.norm1: feats = self.norm1(feats) if self.mlp: feats2 = self.linear2(self.dropout(self.act(self.linear1(feats)))) else: feats2 = feats feats2 = self.dropout2(feats2) if self.res2: feats = feats + feats2 else: feats = feats2 if self.norm2: feats = self.norm2(feats) return feats, egde_index, edge_attr
true
true
1c3c1a584c0796e1dee8b8abfa321415a02b745c
55,455
py
Python
search.py
mariac-molina/KR
742496b94d922e0c2ad8ed2443cfa5dbca2255ab
[ "MIT" ]
null
null
null
search.py
mariac-molina/KR
742496b94d922e0c2ad8ed2443cfa5dbca2255ab
[ "MIT" ]
null
null
null
search.py
mariac-molina/KR
742496b94d922e0c2ad8ed2443cfa5dbca2255ab
[ "MIT" ]
null
null
null
"""Search (Chapters 3-4) The way to use this code is to subclass Problem to create a class of problems, then create problem instances and solve them with calls to the various search functions.""" import bisect import math import random import sys from collections import deque from utils import ( is_in, argmin, argmax, argmax_random_tie, probability, weighted_sampler, memoize, print_table, open_data, PriorityQueue, name, distance, vector_add ) infinity = float('inf') # ______________________________________________________________________________ class Problem(object): """The abstract class for a formal problem. You should subclass this and implement the methods actions and result, and possibly __init__, goal_test, and path_cost. Then you will create instances of your subclass and solve them with the various search functions.""" def __init__(self, initial, goal=None): """The constructor specifies the initial state, and possibly a goal state, if there is a unique goal. Your subclass's constructor can add other arguments.""" self.initial = initial self.goal = goal def hasMoreCannibals(self, state): raise NotImplementedError def isValidState(self, state): raise NotImplementedError def isValidAction(self, state, action): raise NotImplementedError def actions(self, state): """Return the actions that can be executed in the given state. The result would typically be a list, but if there are many actions, consider yielding them one at a time in an iterator, rather than building them all at once.""" raise NotImplementedError def result(self, state, action): """Return the state that results from executing the given action in the given state. The action must be one of self.actions(state).""" raise NotImplementedError def goal_test(self, state): """Return True if the state is a goal. The default method compares the state to self.goal or checks for state in self.goal if it is a list, as specified in the constructor. Override this method if checking against a single self.goal is not enough.""" if isinstance(self.goal, list): return is_in(state, self.goal) else: return state == self.goal def path_cost(self, c, state1, action, state2): """Return the cost of a solution path that arrives at state2 from state1 via action, assuming cost c to get up to state1. If the problem is such that the path doesn't matter, this function will only look at state2. If the path does matter, it will consider c and maybe state1 and action. The default method costs 1 for every step in the path.""" return c + 1 def value(self, state): """For optimization problems, each state has a value. Hill-climbing and related algorithms try to maximize this value.""" raise NotImplementedError # ______________________________________________________________________________ class Node: """A node in a search tree. Contains a pointer to the parent (the node that this is a successor of) and to the actual state for this node. Note that if a state is arrived at by two paths, then there are two nodes with the same state. Also includes the action that got us to this state, and the total path_cost (also known as g) to reach the node. Other functions may add an f and h value; see best_first_graph_search and astar_search for an explanation of how the f and h values are handled. You will not need to subclass this class.""" def __init__(self, state, parent=None, action=None, path_cost=0): """Create a search tree Node, derived from a parent by an action.""" self.state = state self.parent = parent self.action = action self.path_cost = path_cost self.depth = 0 if parent: self.depth = parent.depth + 1 def __repr__(self): return "<Node {}>".format(self.state) def __lt__(self, node): return self.state < node.state def expand(self, problem): """List the nodes reachable in one step from this node.""" return [self.child_node(problem, action) for action in problem.actions(self.state)] def child_node(self, problem, action): """[Figure 3.10]""" next_state = problem.result(self.state, action) next_node = Node(next_state, self, action, problem.path_cost(self.path_cost, self.state, action, next_state)) return next_node def solution(self): """Return the sequence of actions to go from the root to this node.""" return [node.action for node in self.path()[1:]] def path(self): """Return a list of nodes forming the path from the root to this node.""" node, path_back = self, [] while node: path_back.append(node) node = node.parent return list(reversed(path_back)) # We want for a queue of nodes in breadth_first_graph_search or # astar_search to have no duplicated states, so we treat nodes # with the same state as equal. [Problem: this may not be what you # want in other contexts.] def __eq__(self, other): return isinstance(other, Node) and self.state == other.state def __hash__(self): return hash(self.state) # ______________________________________________________________________________ class SimpleProblemSolvingAgentProgram: """Abstract framework for a problem-solving agent. [Figure 3.1]""" def __init__(self, initial_state=None): """State is an abstract representation of the state of the world, and seq is the list of actions required to get to a particular state from the initial state(root).""" self.state = initial_state self.seq = [] def __call__(self, percept): """[Figure 3.1] Formulate a goal and problem, then search for a sequence of actions to solve it.""" self.state = self.update_state(self.state, percept) if not self.seq: goal = self.formulate_goal(self.state) problem = self.formulate_problem(self.state, goal) self.seq = self.search(problem) if not self.seq: return None return self.seq.pop(0) def update_state(self, state, percept): raise NotImplementedError def formulate_goal(self, state): raise NotImplementedError def formulate_problem(self, state, goal): raise NotImplementedError def search(self, problem): raise NotImplementedError # ______________________________________________________________________________ # Uninformed Search algorithms def breadth_first_tree_search(problem): """Search the shallowest nodes in the search tree first. Search through the successors of a problem to find a goal. The argument frontier should be an empty queue. Repeats infinitely in case of loops. [Figure 3.7]""" frontier = deque([Node(problem.initial)]) # FIFO queue while frontier: node = frontier.popleft() if problem.goal_test(node.state): return node frontier.extend(node.expand(problem)) return None def depth_first_tree_search(problem): """Search the deepest nodes in the search tree first. Search through the successors of a problem to find a goal. The argument frontier should be an empty queue. Repeats infinitely in case of loops. [Figure 3.7]""" frontier = [Node(problem.initial)] # Stack while frontier: node = frontier.pop() if problem.goal_test(node.state): return node frontier.extend(node.expand(problem)) return None def depth_first_graph_search(problem): """Search the deepest nodes in the search tree first. Search through the successors of a problem to find a goal. The argument frontier should be an empty queue. Does not get trapped by loops. If two paths reach a state, only use the first one. [Figure 3.7]""" frontier = [(Node(problem.initial))] # Stack explored = set() while frontier: node = frontier.pop() if problem.goal_test(node.state): return node explored.add(node.state) frontier.extend(child for child in node.expand(problem) if child.state not in explored and child not in frontier) return None def breadth_first_graph_search(problem): """[Figure 3.11] Note that this function can be implemented in a single line as below: return graph_search(problem, FIFOQueue()) """ node = Node(problem.initial) if problem.goal_test(node.state): return node frontier = deque([node]) explored = set() while frontier: node = frontier.popleft() explored.add(node.state) for child in node.expand(problem): if child.state not in explored and child not in frontier: if problem.goal_test(child.state): return child frontier.append(child) return None def best_first_graph_search(problem, f): """Search the nodes with the lowest f scores first. You specify the function f(node) that you want to minimize; for example, if f is a heuristic estimate to the goal, then we have greedy best first search; if f is node.depth then we have breadth-first search. There is a subtlety: the line "f = memoize(f, 'f')" means that the f values will be cached on the nodes as they are computed. So after doing a best first search you can examine the f values of the path returned.""" f = memoize(f, 'f') node = Node(problem.initial) frontier = PriorityQueue('min', f) frontier.append(node) explored = set() while frontier: node = frontier.pop() if problem.goal_test(node.state): return node explored.add(node.state) for child in node.expand(problem): if child.state not in explored and child not in frontier: frontier.append(child) elif child in frontier: if f(child) < frontier[child]: del frontier[child] frontier.append(child) return None def uniform_cost_search(problem): """[Figure 3.14]""" return best_first_graph_search(problem, lambda node: node.path_cost) def depth_limited_search(problem, limit=50): """[Figure 3.17]""" def recursive_dls(node, problem, limit): if problem.goal_test(node.state): return node elif limit == 0: return 'cutoff' else: cutoff_occurred = False for child in node.expand(problem): result = recursive_dls(child, problem, limit - 1) if result == 'cutoff': cutoff_occurred = True elif result is not None: return result return 'cutoff' if cutoff_occurred else None # Body of depth_limited_search: return recursive_dls(Node(problem.initial), problem, limit) def iterative_deepening_search(problem): """[Figure 3.18]""" for depth in range(sys.maxsize): result = depth_limited_search(problem, depth) if result != 'cutoff': return result # ______________________________________________________________________________ # Bidirectional Search # Pseudocode from https://webdocs.cs.ualberta.ca/%7Eholte/Publications/MM-AAAI2016.pdf def bidirectional_search(problem): e = problem.find_min_edge() gF, gB = {problem.initial: 0}, {problem.goal: 0} openF, openB = [problem.initial], [problem.goal] closedF, closedB = [], [] U = infinity def extend(U, open_dir, open_other, g_dir, g_other, closed_dir): """Extend search in given direction""" n = find_key(C, open_dir, g_dir) open_dir.remove(n) closed_dir.append(n) for c in problem.actions(n): if c in open_dir or c in closed_dir: if g_dir[c] <= problem.path_cost(g_dir[n], n, None, c): continue open_dir.remove(c) g_dir[c] = problem.path_cost(g_dir[n], n, None, c) open_dir.append(c) if c in open_other: U = min(U, g_dir[c] + g_other[c]) return U, open_dir, closed_dir, g_dir def find_min(open_dir, g): """Finds minimum priority, g and f values in open_dir""" m, m_f = infinity, infinity for n in open_dir: f = g[n] + problem.h(n) pr = max(f, 2 * g[n]) m = min(m, pr) m_f = min(m_f, f) return m, m_f, min(g.values()) def find_key(pr_min, open_dir, g): """Finds key in open_dir with value equal to pr_min and minimum g value.""" m = infinity state = -1 for n in open_dir: pr = max(g[n] + problem.h(n), 2 * g[n]) if pr == pr_min: if g[n] < m: m = g[n] state = n return state while openF and openB: pr_min_f, f_min_f, g_min_f = find_min(openF, gF) pr_min_b, f_min_b, g_min_b = find_min(openB, gB) C = min(pr_min_f, pr_min_b) if U <= max(C, f_min_f, f_min_b, g_min_f + g_min_b + e): return U if C == pr_min_f: # Extend forward U, openF, closedF, gF = extend(U, openF, openB, gF, gB, closedF) else: # Extend backward U, openB, closedB, gB = extend(U, openB, openF, gB, gF, closedB) return infinity # ______________________________________________________________________________ # Informed (Heuristic) Search greedy_best_first_graph_search = best_first_graph_search # Greedy best-first search is accomplished by specifying f(n) = h(n). def astar_search(problem, h=None): """A* search is best-first graph search with f(n) = g(n)+h(n). You need to specify the h function when you call astar_search, or else in your Problem subclass.""" h = memoize(h or problem.h, 'h') return best_first_graph_search(problem, lambda n: n.path_cost + h(n)) # ______________________________________________________________________________ # A* heuristics class EightPuzzle(Problem): """ The problem of sliding tiles numbered from 1 to 8 on a 3x3 board, where one of the squares is a blank. A state is represented as a tuple of length 9, where element at index i represents the tile number at index i (0 if it's an empty square) """ def __init__(self, initial, goal=(1, 2, 3, 4, 5, 6, 7, 8, 0)): """ Define goal state and initialize a problem """ self.goal = goal Problem.__init__(self, initial, goal) def find_blank_square(self, state): """Return the index of the blank square in a given state""" return state.index(0) def actions(self, state): """ Return the actions that can be executed in the given state. The result would be a list, since there are only four possible actions in any given state of the environment """ possible_actions = ['UP', 'DOWN', 'LEFT', 'RIGHT'] index_blank_square = self.find_blank_square(state) if index_blank_square % 3 == 0: possible_actions.remove('LEFT') if index_blank_square < 3: possible_actions.remove('UP') if index_blank_square % 3 == 2: possible_actions.remove('RIGHT') if index_blank_square > 5: possible_actions.remove('DOWN') return possible_actions def result(self, state, action): """ Given state and action, return a new state that is the result of the action. Action is assumed to be a valid action in the state """ # blank is the index of the blank square blank = self.find_blank_square(state) new_state = list(state) delta = {'UP': -3, 'DOWN': 3, 'LEFT': -1, 'RIGHT': 1} neighbor = blank + delta[action] new_state[blank], new_state[neighbor] = new_state[neighbor], new_state[blank] return tuple(new_state) def goal_test(self, state): """ Given a state, return True if state is a goal state or False, otherwise """ return state == self.goal def check_solvability(self, state): """ Checks if the given state is solvable """ inversion = 0 for i in range(len(state)): for j in range(i + 1, len(state)): if (state[i] > state[j]) and state[i] != 0 and state[j] != 0: inversion += 1 return inversion % 2 == 0 def h(self, node): """ Return the heuristic value for a given state. Default heuristic function used is h(n) = number of misplaced tiles """ return sum(s != g for (s, g) in zip(node.state, self.goal)) # ______________________________________________________________________________ class PlanRoute(Problem): """ The problem of moving the Hybrid Wumpus Agent from one place to other """ def __init__(self, initial, goal, allowed, dimrow): """ Define goal state and initialize a problem """ self.dimrow = dimrow self.goal = goal self.allowed = allowed Problem.__init__(self, initial, goal) def actions(self, state): """ Return the actions that can be executed in the given state. The result would be a list, since there are only three possible actions in any given state of the environment """ possible_actions = ['Forward', 'TurnLeft', 'TurnRight'] x, y = state.get_location() orientation = state.get_orientation() # Prevent Bumps if x == 1 and orientation == 'LEFT': if 'Forward' in possible_actions: possible_actions.remove('Forward') if y == 1 and orientation == 'DOWN': if 'Forward' in possible_actions: possible_actions.remove('Forward') if x == self.dimrow and orientation == 'RIGHT': if 'Forward' in possible_actions: possible_actions.remove('Forward') if y == self.dimrow and orientation == 'UP': if 'Forward' in possible_actions: possible_actions.remove('Forward') return possible_actions def result(self, state, action): """ Given state and action, return a new state that is the result of the action. Action is assumed to be a valid action in the state """ x, y = state.get_location() proposed_loc = list() # Move Forward if action == 'Forward': if state.get_orientation() == 'UP': proposed_loc = [x, y + 1] elif state.get_orientation() == 'DOWN': proposed_loc = [x, y - 1] elif state.get_orientation() == 'LEFT': proposed_loc = [x - 1, y] elif state.get_orientation() == 'RIGHT': proposed_loc = [x + 1, y] else: raise Exception('InvalidOrientation') # Rotate counter-clockwise elif action == 'TurnLeft': if state.get_orientation() == 'UP': state.set_orientation('LEFT') elif state.get_orientation() == 'DOWN': state.set_orientation('RIGHT') elif state.get_orientation() == 'LEFT': state.set_orientation('DOWN') elif state.get_orientation() == 'RIGHT': state.set_orientation('UP') else: raise Exception('InvalidOrientation') # Rotate clockwise elif action == 'TurnRight': if state.get_orientation() == 'UP': state.set_orientation('RIGHT') elif state.get_orientation() == 'DOWN': state.set_orientation('LEFT') elif state.get_orientation() == 'LEFT': state.set_orientation('UP') elif state.get_orientation() == 'RIGHT': state.set_orientation('DOWN') else: raise Exception('InvalidOrientation') if proposed_loc in self.allowed: state.set_location(proposed_loc[0], [proposed_loc[1]]) return state def goal_test(self, state): """ Given a state, return True if state is a goal state or False, otherwise """ return state.get_location() == tuple(self.goal) def h(self, node): """ Return the heuristic value for a given state.""" # Manhattan Heuristic Function x1, y1 = node.state.get_location() x2, y2 = self.goal return abs(x2 - x1) + abs(y2 - y1) # ______________________________________________________________________________ # Other search algorithms def recursive_best_first_search(problem, h=None): """[Figure 3.26]""" h = memoize(h or problem.h, 'h') def RBFS(problem, node, flimit): if problem.goal_test(node.state): return node, 0 # (The second value is immaterial) successors = node.expand(problem) if len(successors) == 0: return None, infinity for s in successors: s.f = max(s.path_cost + h(s), node.f) while True: # Order by lowest f value successors.sort(key=lambda x: x.f) best = successors[0] if best.f > flimit: return None, best.f if len(successors) > 1: alternative = successors[1].f else: alternative = infinity result, best.f = RBFS(problem, best, min(flimit, alternative)) if result is not None: return result, best.f node = Node(problem.initial) node.f = h(node) result, bestf = RBFS(problem, node, infinity) return result def hill_climbing(problem): """From the initial node, keep choosing the neighbor with highest value, stopping when no neighbor is better. [Figure 4.2]""" current = Node(problem.initial) while True: neighbors = current.expand(problem) if not neighbors: break neighbor = argmax_random_tie(neighbors, key=lambda node: problem.value(node.state)) if problem.value(neighbor.state) <= problem.value(current.state): break current = neighbor return current.state def exp_schedule(k=20, lam=0.005, limit=100): """One possible schedule function for simulated annealing""" return lambda t: (k * math.exp(-lam * t) if t < limit else 0) def simulated_annealing(problem, schedule=exp_schedule()): """[Figure 4.5] CAUTION: This differs from the pseudocode as it returns a state instead of a Node.""" current = Node(problem.initial) for t in range(sys.maxsize): T = schedule(t) if T == 0: return current.state neighbors = current.expand(problem) if not neighbors: return current.state next_choice = random.choice(neighbors) delta_e = problem.value(next_choice.state) - problem.value(current.state) if delta_e > 0 or probability(math.exp(delta_e / T)): current = next_choice def simulated_annealing_full(problem, schedule=exp_schedule()): """ This version returns all the states encountered in reaching the goal state.""" states = [] current = Node(problem.initial) for t in range(sys.maxsize): states.append(current.state) T = schedule(t) if T == 0: return states neighbors = current.expand(problem) if not neighbors: return current.state next_choice = random.choice(neighbors) delta_e = problem.value(next_choice.state) - problem.value(current.state) if delta_e > 0 or probability(math.exp(delta_e / T)): current = next_choice def and_or_graph_search(problem): """[Figure 4.11]Used when the environment is nondeterministic and completely observable. Contains OR nodes where the agent is free to choose any action. After every action there is an AND node which contains all possible states the agent may reach due to stochastic nature of environment. The agent must be able to handle all possible states of the AND node (as it may end up in any of them). Returns a conditional plan to reach goal state, or failure if the former is not possible.""" # functions used by and_or_search def or_search(state, problem, path): """returns a plan as a list of actions""" if problem.goal_test(state): return [] if state in path: return None for action in problem.actions(state): plan = and_search(problem.result(state, action), problem, path + [state, ]) if plan is not None: return [action, plan] def and_search(states, problem, path): """Returns plan in form of dictionary where we take action plan[s] if we reach state s.""" plan = {} for s in states: plan[s] = or_search(s, problem, path) if plan[s] is None: return None return plan # body of and or search return or_search(problem.initial, problem, []) # Pre-defined actions for PeakFindingProblem directions4 = {'W': (-1, 0), 'N': (0, 1), 'E': (1, 0), 'S': (0, -1)} directions8 = dict(directions4) directions8.update({'NW': (-1, 1), 'NE': (1, 1), 'SE': (1, -1), 'SW': (-1, -1)}) class PeakFindingProblem(Problem): """Problem of finding the highest peak in a limited grid""" def __init__(self, initial, grid, defined_actions=directions4): """The grid is a 2 dimensional array/list whose state is specified by tuple of indices""" Problem.__init__(self, initial) self.grid = grid self.defined_actions = defined_actions self.n = len(grid) assert self.n > 0 self.m = len(grid[0]) assert self.m > 0 def actions(self, state): """Returns the list of actions which are allowed to be taken from the given state""" allowed_actions = [] for action in self.defined_actions: next_state = vector_add(state, self.defined_actions[action]) if 0 <= next_state[0] <= self.n - 1 and next_state[1] >= 0 and next_state[1] <= self.m - 1: allowed_actions.append(action) return allowed_actions def result(self, state, action): """Moves in the direction specified by action""" return vector_add(state, self.defined_actions[action]) def value(self, state): """Value of a state is the value it is the index to""" x, y = state assert 0 <= x < self.n assert 0 <= y < self.m return self.grid[x][y] class OnlineDFSAgent: """[Figure 4.21] The abstract class for an OnlineDFSAgent. Override update_state method to convert percept to state. While initializing the subclass a problem needs to be provided which is an instance of a subclass of the Problem class.""" def __init__(self, problem): self.problem = problem self.s = None self.a = None self.untried = dict() self.unbacktracked = dict() self.result = {} def __call__(self, percept): s1 = self.update_state(percept) if self.problem.goal_test(s1): self.a = None else: if s1 not in self.untried.keys(): self.untried[s1] = self.problem.actions(s1) if self.s is not None: if s1 != self.result[(self.s, self.a)]: self.result[(self.s, self.a)] = s1 self.unbacktracked[s1].insert(0, self.s) if len(self.untried[s1]) == 0: if len(self.unbacktracked[s1]) == 0: self.a = None else: # else a <- an action b such that result[s', b] = POP(unbacktracked[s']) unbacktracked_pop = self.unbacktracked.pop(s1) for (s, b) in self.result.keys(): if self.result[(s, b)] == unbacktracked_pop: self.a = b break else: self.a = self.untried.pop(s1) self.s = s1 return self.a def update_state(self, percept): """To be overridden in most cases. The default case assumes the percept to be of type state.""" return percept # ______________________________________________________________________________ class OnlineSearchProblem(Problem): """ A problem which is solved by an agent executing actions, rather than by just computation. Carried in a deterministic and a fully observable environment.""" def __init__(self, initial, goal, graph): self.initial = initial self.goal = goal self.graph = graph def actions(self, state): return self.graph.graph_dict[state].keys() def output(self, state, action): return self.graph.graph_dict[state][action] def h(self, state): """Returns least possible cost to reach a goal for the given state.""" return self.graph.least_costs[state] def c(self, s, a, s1): """Returns a cost estimate for an agent to move from state 's' to state 's1'.""" return 1 def update_state(self, percept): raise NotImplementedError def goal_test(self, state): if state == self.goal: return True return False class LRTAStarAgent: """ [Figure 4.24] Abstract class for LRTA*-Agent. A problem needs to be provided which is an instance of a subclass of Problem Class. Takes a OnlineSearchProblem [Figure 4.23] as a problem. """ def __init__(self, problem): self.problem = problem # self.result = {} # no need as we are using problem.result self.H = {} self.s = None self.a = None def __call__(self, s1): # as of now s1 is a state rather than a percept if self.problem.goal_test(s1): self.a = None return self.a else: if s1 not in self.H: self.H[s1] = self.problem.h(s1) if self.s is not None: # self.result[(self.s, self.a)] = s1 # no need as we are using problem.output # minimum cost for action b in problem.actions(s) self.H[self.s] = min(self.LRTA_cost(self.s, b, self.problem.output(self.s, b), self.H) for b in self.problem.actions(self.s)) # an action b in problem.actions(s1) that minimizes costs self.a = argmin(self.problem.actions(s1), key=lambda b: self.LRTA_cost(s1, b, self.problem.output(s1, b), self.H)) self.s = s1 return self.a def LRTA_cost(self, s, a, s1, H): """Returns cost to move from state 's' to state 's1' plus estimated cost to get to goal from s1.""" print(s, a, s1) if s1 is None: return self.problem.h(s) else: # sometimes we need to get H[s1] which we haven't yet added to H # to replace this try, except: we can initialize H with values from problem.h try: return self.problem.c(s, a, s1) + self.H[s1] except: return self.problem.c(s, a, s1) + self.problem.h(s1) # ______________________________________________________________________________ # Genetic Algorithm def genetic_search(problem, fitness_fn, ngen=1000, pmut=0.1, n=20): """Call genetic_algorithm on the appropriate parts of a problem. This requires the problem to have states that can mate and mutate, plus a value method that scores states.""" # NOTE: This is not tested and might not work. # TODO: Use this function to make Problems work with genetic_algorithm. s = problem.initial_state states = [problem.result(s, a) for a in problem.actions(s)] random.shuffle(states) return genetic_algorithm(states[:n], problem.value, ngen, pmut) def genetic_algorithm(population, fitness_fn, gene_pool=[0, 1], f_thres=None, ngen=1000, pmut=0.1): """[Figure 4.8]""" for i in range(ngen): population = [mutate(recombine(*select(2, population, fitness_fn)), gene_pool, pmut) for i in range(len(population))] fittest_individual = fitness_threshold(fitness_fn, f_thres, population) if fittest_individual: return fittest_individual return argmax(population, key=fitness_fn) def fitness_threshold(fitness_fn, f_thres, population): if not f_thres: return None fittest_individual = argmax(population, key=fitness_fn) if fitness_fn(fittest_individual) >= f_thres: return fittest_individual return None def init_population(pop_number, gene_pool, state_length): """Initializes population for genetic algorithm pop_number : Number of individuals in population gene_pool : List of possible values for individuals state_length: The length of each individual""" g = len(gene_pool) population = [] for i in range(pop_number): new_individual = [gene_pool[random.randrange(0, g)] for j in range(state_length)] population.append(new_individual) return population def select(r, population, fitness_fn): fitnesses = map(fitness_fn, population) sampler = weighted_sampler(population, fitnesses) return [sampler() for i in range(r)] def recombine(x, y): n = len(x) c = random.randrange(0, n) return x[:c] + y[c:] def recombine_uniform(x, y): n = len(x) result = [0] * n indexes = random.sample(range(n), n) for i in range(n): ix = indexes[i] result[ix] = x[ix] if i < n / 2 else y[ix] return ''.join(str(r) for r in result) def mutate(x, gene_pool, pmut): if random.uniform(0, 1) >= pmut: return x n = len(x) g = len(gene_pool) c = random.randrange(0, n) r = random.randrange(0, g) new_gene = gene_pool[r] return x[:c] + [new_gene] + x[c + 1:] # _____________________________________________________________________________ # The remainder of this file implements examples for the search algorithms. # ______________________________________________________________________________ # Graphs and Graph Problems class Graph: """A graph connects nodes (vertices) by edges (links). Each edge can also have a length associated with it. The constructor call is something like: g = Graph({'A': {'B': 1, 'C': 2}) this makes a graph with 3 nodes, A, B, and C, with an edge of length 1 from A to B, and an edge of length 2 from A to C. You can also do: g = Graph({'A': {'B': 1, 'C': 2}, directed=False) This makes an undirected graph, so inverse links are also added. The graph stays undirected; if you add more links with g.connect('B', 'C', 3), then inverse link is also added. You can use g.nodes() to get a list of nodes, g.get('A') to get a dict of links out of A, and g.get('A', 'B') to get the length of the link from A to B. 'Lengths' can actually be any object at all, and nodes can be any hashable object.""" def __init__(self, graph_dict=None, directed=True): self.graph_dict = graph_dict or {} self.directed = directed if not directed: self.make_undirected() def make_undirected(self): """Make a digraph into an undirected graph by adding symmetric edges.""" for a in list(self.graph_dict.keys()): for (b, dist) in self.graph_dict[a].items(): self.connect1(b, a, dist) def connect(self, A, B, distance=1): """Add a link from A and B of given distance, and also add the inverse link if the graph is undirected.""" self.connect1(A, B, distance) if not self.directed: self.connect1(B, A, distance) def connect1(self, A, B, distance): """Add a link from A to B of given distance, in one direction only.""" self.graph_dict.setdefault(A, {})[B] = distance def get(self, a, b=None): """Return a link distance or a dict of {node: distance} entries. .get(a,b) returns the distance or None; .get(a) returns a dict of {node: distance} entries, possibly {}.""" links = self.graph_dict.setdefault(a, {}) if b is None: return links else: return links.get(b) def nodes(self): """Return a list of nodes in the graph.""" s1 = set([k for k in self.graph_dict.keys()]) s2 = set([k2 for v in self.graph_dict.values() for k2, v2 in v.items()]) nodes = s1.union(s2) return list(nodes) def UndirectedGraph(graph_dict=None): """Build a Graph where every edge (including future ones) goes both ways.""" return Graph(graph_dict=graph_dict, directed=False) def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300, curvature=lambda: random.uniform(1.1, 1.5)): """Construct a random graph, with the specified nodes, and random links. The nodes are laid out randomly on a (width x height) rectangle. Then each node is connected to the min_links nearest neighbors. Because inverse links are added, some nodes will have more connections. The distance between nodes is the hypotenuse times curvature(), where curvature() defaults to a random number between 1.1 and 1.5.""" g = UndirectedGraph() g.locations = {} # Build the cities for node in nodes: g.locations[node] = (random.randrange(width), random.randrange(height)) # Build roads from each city to at least min_links nearest neighbors. for i in range(min_links): for node in nodes: if len(g.get(node)) < min_links: here = g.locations[node] def distance_to_node(n): if n is node or g.get(node, n): return infinity return distance(g.locations[n], here) neighbor = argmin(nodes, key=distance_to_node) d = distance(g.locations[neighbor], here) * curvature() g.connect(node, neighbor, int(d)) return g """ [Figure 3.2] Simplified road map of Romania """ romania_map = UndirectedGraph(dict( Arad=dict(Zerind=75, Sibiu=140, Timisoara=118), Bucharest=dict(Urziceni=85, Pitesti=101, Giurgiu=90, Fagaras=211), Craiova=dict(Drobeta=120, Rimnicu=146, Pitesti=138), Drobeta=dict(Mehadia=75), Eforie=dict(Hirsova=86), Fagaras=dict(Sibiu=99), Hirsova=dict(Urziceni=98), Iasi=dict(Vaslui=92, Neamt=87), Lugoj=dict(Timisoara=111, Mehadia=70), Oradea=dict(Zerind=71, Sibiu=151), Pitesti=dict(Rimnicu=97), Rimnicu=dict(Sibiu=80), Urziceni=dict(Vaslui=142))) romania_map.locations = dict( Arad=(91, 492), Bucharest=(400, 327), Craiova=(253, 288), Drobeta=(165, 299), Eforie=(562, 293), Fagaras=(305, 449), Giurgiu=(375, 270), Hirsova=(534, 350), Iasi=(473, 506), Lugoj=(165, 379), Mehadia=(168, 339), Neamt=(406, 537), Oradea=(131, 571), Pitesti=(320, 368), Rimnicu=(233, 410), Sibiu=(207, 457), Timisoara=(94, 410), Urziceni=(456, 350), Vaslui=(509, 444), Zerind=(108, 531)) """ [Figure 4.9] Eight possible states of the vacumm world Each state is represented as * "State of the left room" "State of the right room" "Room in which the agent is present" 1 - DDL Dirty Dirty Left 2 - DDR Dirty Dirty Right 3 - DCL Dirty Clean Left 4 - DCR Dirty Clean Right 5 - CDL Clean Dirty Left 6 - CDR Clean Dirty Right 7 - CCL Clean Clean Left 8 - CCR Clean Clean Right """ vacuum_world = Graph(dict( State_1=dict(Suck=['State_7', 'State_5'], Right=['State_2']), State_2=dict(Suck=['State_8', 'State_4'], Left=['State_2']), State_3=dict(Suck=['State_7'], Right=['State_4']), State_4=dict(Suck=['State_4', 'State_2'], Left=['State_3']), State_5=dict(Suck=['State_5', 'State_1'], Right=['State_6']), State_6=dict(Suck=['State_8'], Left=['State_5']), State_7=dict(Suck=['State_7', 'State_3'], Right=['State_8']), State_8=dict(Suck=['State_8', 'State_6'], Left=['State_7']) )) """ [Figure 4.23] One-dimensional state space Graph """ one_dim_state_space = Graph(dict( State_1=dict(Right='State_2'), State_2=dict(Right='State_3', Left='State_1'), State_3=dict(Right='State_4', Left='State_2'), State_4=dict(Right='State_5', Left='State_3'), State_5=dict(Right='State_6', Left='State_4'), State_6=dict(Left='State_5') )) one_dim_state_space.least_costs = dict( State_1=8, State_2=9, State_3=2, State_4=2, State_5=4, State_6=3) """ [Figure 6.1] Principal states and territories of Australia """ australia_map = UndirectedGraph(dict( T=dict(), SA=dict(WA=1, NT=1, Q=1, NSW=1, V=1), NT=dict(WA=1, Q=1), NSW=dict(Q=1, V=1))) australia_map.locations = dict(WA=(120, 24), NT=(135, 20), SA=(135, 30), Q=(145, 20), NSW=(145, 32), T=(145, 42), V=(145, 37)) class GraphProblem(Problem): """The problem of searching a graph from one node to another.""" def __init__(self, initial, goal, graph): Problem.__init__(self, initial, goal) self.graph = graph def actions(self, A): """The actions at a graph node are just its neighbors.""" return list(self.graph.get(A).keys()) def result(self, state, action): """The result of going to a neighbor is just that neighbor.""" return action def path_cost(self, cost_so_far, A, action, B): return cost_so_far + (self.graph.get(A, B) or infinity) def find_min_edge(self): """Find minimum value of edges.""" m = infinity for d in self.graph.graph_dict.values(): local_min = min(d.values()) m = min(m, local_min) return m def h(self, node): """h function is straight-line distance from a node's state to goal.""" locs = getattr(self.graph, 'locations', None) if locs: if type(node) is str: return int(distance(locs[node], locs[self.goal])) return int(distance(locs[node.state], locs[self.goal])) else: return infinity class GraphProblemStochastic(GraphProblem): """ A version of GraphProblem where an action can lead to nondeterministic output i.e. multiple possible states. Define the graph as dict(A = dict(Action = [[<Result 1>, <Result 2>, ...], <cost>], ...), ...) A the dictionary format is different, make sure the graph is created as a directed graph. """ def result(self, state, action): return self.graph.get(state, action) def path_cost(self): raise NotImplementedError # ______________________________________________________________________________ class NQueensProblem(Problem): """The problem of placing N queens on an NxN board with none attacking each other. A state is represented as an N-element array, where a value of r in the c-th entry means there is a queen at column c, row r, and a value of -1 means that the c-th column has not been filled in yet. We fill in columns left to right. >>> depth_first_tree_search(NQueensProblem(8)) <Node (7, 3, 0, 2, 5, 1, 6, 4)> """ def __init__(self, N): self.N = N self.initial = tuple([-1] * N) Problem.__init__(self, self.initial) def actions(self, state): """In the leftmost empty column, try all non-conflicting rows.""" if state[-1] is not -1: return [] # All columns filled; no successors else: col = state.index(-1) return [row for row in range(self.N) if not self.conflicted(state, row, col)] def result(self, state, row): """Place the next queen at the given row.""" col = state.index(-1) new = list(state[:]) new[col] = row return tuple(new) def conflicted(self, state, row, col): """Would placing a queen at (row, col) conflict with anything?""" return any(self.conflict(row, col, state[c], c) for c in range(col)) def conflict(self, row1, col1, row2, col2): """Would putting two queens in (row1, col1) and (row2, col2) conflict?""" return (row1 == row2 or # same row col1 == col2 or # same column row1 - col1 == row2 - col2 or # same \ diagonal row1 + col1 == row2 + col2) # same / diagonal def goal_test(self, state): """Check if all columns filled, no conflicts.""" if state[-1] is -1: return False return not any(self.conflicted(state, state[col], col) for col in range(len(state))) def h(self, node): """Return number of conflicting queens for a given node""" num_conflicts = 0 for (r1, c1) in enumerate(node.state): for (r2, c2) in enumerate(node.state): if (r1, c1) != (r2, c2): num_conflicts += self.conflict(r1, c1, r2, c2) return num_conflicts # ______________________________________________________________________________ # Inverse Boggle: Search for a high-scoring Boggle board. A good domain for # iterative-repair and related search techniques, as suggested by Justin Boyan. ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' cubes16 = ['FORIXB', 'MOQABJ', 'GURILW', 'SETUPL', 'CMPDAE', 'ACITAO', 'SLCRAE', 'ROMASH', 'NODESW', 'HEFIYE', 'ONUDTK', 'TEVIGN', 'ANEDVZ', 'PINESH', 'ABILYT', 'GKYLEU'] def random_boggle(n=4): """Return a random Boggle board of size n x n. We represent a board as a linear list of letters.""" cubes = [cubes16[i % 16] for i in range(n * n)] random.shuffle(cubes) return list(map(random.choice, cubes)) # The best 5x5 board found by Boyan, with our word list this board scores # 2274 words, for a score of 9837 boyan_best = list('RSTCSDEIAEGNLRPEATESMSSID') def print_boggle(board): """Print the board in a 2-d array.""" n2 = len(board) n = exact_sqrt(n2) for i in range(n2): if i % n == 0 and i > 0: print() if board[i] == 'Q': print('Qu', end=' ') else: print(str(board[i]) + ' ', end=' ') print() def boggle_neighbors(n2, cache={}): """Return a list of lists, where the i-th element is the list of indexes for the neighbors of square i.""" if cache.get(n2): return cache.get(n2) n = exact_sqrt(n2) neighbors = [None] * n2 for i in range(n2): neighbors[i] = [] on_top = i < n on_bottom = i >= n2 - n on_left = i % n == 0 on_right = (i + 1) % n == 0 if not on_top: neighbors[i].append(i - n) if not on_left: neighbors[i].append(i - n - 1) if not on_right: neighbors[i].append(i - n + 1) if not on_bottom: neighbors[i].append(i + n) if not on_left: neighbors[i].append(i + n - 1) if not on_right: neighbors[i].append(i + n + 1) if not on_left: neighbors[i].append(i - 1) if not on_right: neighbors[i].append(i + 1) cache[n2] = neighbors return neighbors def exact_sqrt(n2): """If n2 is a perfect square, return its square root, else raise error.""" n = int(math.sqrt(n2)) assert n * n == n2 return n # _____________________________________________________________________________ class Wordlist: """This class holds a list of words. You can use (word in wordlist) to check if a word is in the list, or wordlist.lookup(prefix) to see if prefix starts any of the words in the list.""" def __init__(self, file, min_len=3): lines = file.read().upper().split() self.words = [word for word in lines if len(word) >= min_len] self.words.sort() self.bounds = {} for c in ALPHABET: c2 = chr(ord(c) + 1) self.bounds[c] = (bisect.bisect(self.words, c), bisect.bisect(self.words, c2)) def lookup(self, prefix, lo=0, hi=None): """See if prefix is in dictionary, as a full word or as a prefix. Return two values: the first is the lowest i such that words[i].startswith(prefix), or is None; the second is True iff prefix itself is in the Wordlist.""" words = self.words if hi is None: hi = len(words) i = bisect.bisect_left(words, prefix, lo, hi) if i < len(words) and words[i].startswith(prefix): return i, (words[i] == prefix) else: return None, False def __contains__(self, word): return self.lookup(word)[1] def __len__(self): return len(self.words) # _____________________________________________________________________________ class BoggleFinder: """A class that allows you to find all the words in a Boggle board.""" wordlist = None # A class variable, holding a wordlist def __init__(self, board=None): if BoggleFinder.wordlist is None: BoggleFinder.wordlist = Wordlist(open_data("EN-text/wordlist.txt")) self.found = {} if board: self.set_board(board) def set_board(self, board=None): """Set the board, and find all the words in it.""" if board is None: board = random_boggle() self.board = board self.neighbors = boggle_neighbors(len(board)) self.found = {} for i in range(len(board)): lo, hi = self.wordlist.bounds[board[i]] self.find(lo, hi, i, [], '') return self def find(self, lo, hi, i, visited, prefix): """Looking in square i, find the words that continue the prefix, considering the entries in self.wordlist.words[lo:hi], and not revisiting the squares in visited.""" if i in visited: return wordpos, is_word = self.wordlist.lookup(prefix, lo, hi) if wordpos is not None: if is_word: self.found[prefix] = True visited.append(i) c = self.board[i] if c == 'Q': c = 'QU' prefix += c for j in self.neighbors[i]: self.find(wordpos, hi, j, visited, prefix) visited.pop() def words(self): """The words found.""" return list(self.found.keys()) scores = [0, 0, 0, 0, 1, 2, 3, 5] + [11] * 100 def score(self): """The total score for the words found, according to the rules.""" return sum([self.scores[len(w)] for w in self.words()]) def __len__(self): """The number of words found.""" return len(self.found) # _____________________________________________________________________________ def boggle_hill_climbing(board=None, ntimes=100, verbose=True): """Solve inverse Boggle by hill-climbing: find a high-scoring board by starting with a random one and changing it.""" finder = BoggleFinder() if board is None: board = random_boggle() best = len(finder.set_board(board)) for _ in range(ntimes): i, oldc = mutate_boggle(board) new = len(finder.set_board(board)) if new > best: best = new if verbose: print(best, _, board) else: board[i] = oldc # Change back if verbose: print_boggle(board) return board, best def mutate_boggle(board): i = random.randrange(len(board)) oldc = board[i] # random.choice(boyan_best) board[i] = random.choice(random.choice(cubes16)) return i, oldc # ______________________________________________________________________________ # Code to compare searchers on various problems. class InstrumentedProblem(Problem): """Delegates to a problem, and keeps statistics.""" def __init__(self, problem): self.problem = problem self.succs = self.goal_tests = self.states = 0 self.found = None def actions(self, state): self.succs += 1 return self.problem.actions(state) def result(self, state, action): self.states += 1 return self.problem.result(state, action) def goal_test(self, state): self.goal_tests += 1 result = self.problem.goal_test(state) if result: self.found = state return result def path_cost(self, c, state1, action, state2): return self.problem.path_cost(c, state1, action, state2) def value(self, state): return self.problem.value(state) def __getattr__(self, attr): return getattr(self.problem, attr) def __repr__(self): return '<{:4d}/{:4d}/{:4d}/{}>'.format(self.succs, self.goal_tests, self.states, str(self.found)[:4]) def compare_searchers(problems, header, searchers=[breadth_first_tree_search, breadth_first_graph_search, depth_first_graph_search, iterative_deepening_search, depth_limited_search, recursive_best_first_search]): def do(searcher, problem): p = InstrumentedProblem(problem) searcher(p) return p table = [[name(s)] + [do(s, p) for p in problems] for s in searchers] print_table(table, header) def compare_graph_searchers(): """Prints a table of search results.""" compare_searchers(problems=[GraphProblem('Arad', 'Bucharest', romania_map), GraphProblem('Oradea', 'Neamt', romania_map), GraphProblem('Q', 'WA', australia_map)], header=['Searcher', 'romania_map(Arad, Bucharest)', 'romania_map(Oradea, Neamt)', 'australia_map'])
35.209524
103
0.606997
import bisect import math import random import sys from collections import deque from utils import ( is_in, argmin, argmax, argmax_random_tie, probability, weighted_sampler, memoize, print_table, open_data, PriorityQueue, name, distance, vector_add ) infinity = float('inf') class Problem(object): def __init__(self, initial, goal=None): self.initial = initial self.goal = goal def hasMoreCannibals(self, state): raise NotImplementedError def isValidState(self, state): raise NotImplementedError def isValidAction(self, state, action): raise NotImplementedError def actions(self, state): raise NotImplementedError def result(self, state, action): raise NotImplementedError def goal_test(self, state): if isinstance(self.goal, list): return is_in(state, self.goal) else: return state == self.goal def path_cost(self, c, state1, action, state2): return c + 1 def value(self, state): raise NotImplementedError class Node: def __init__(self, state, parent=None, action=None, path_cost=0): self.state = state self.parent = parent self.action = action self.path_cost = path_cost self.depth = 0 if parent: self.depth = parent.depth + 1 def __repr__(self): return "<Node {}>".format(self.state) def __lt__(self, node): return self.state < node.state def expand(self, problem): return [self.child_node(problem, action) for action in problem.actions(self.state)] def child_node(self, problem, action): next_state = problem.result(self.state, action) next_node = Node(next_state, self, action, problem.path_cost(self.path_cost, self.state, action, next_state)) return next_node def solution(self): return [node.action for node in self.path()[1:]] def path(self): node, path_back = self, [] while node: path_back.append(node) node = node.parent return list(reversed(path_back)) def __eq__(self, other): return isinstance(other, Node) and self.state == other.state def __hash__(self): return hash(self.state) class SimpleProblemSolvingAgentProgram: def __init__(self, initial_state=None): self.state = initial_state self.seq = [] def __call__(self, percept): self.state = self.update_state(self.state, percept) if not self.seq: goal = self.formulate_goal(self.state) problem = self.formulate_problem(self.state, goal) self.seq = self.search(problem) if not self.seq: return None return self.seq.pop(0) def update_state(self, state, percept): raise NotImplementedError def formulate_goal(self, state): raise NotImplementedError def formulate_problem(self, state, goal): raise NotImplementedError def search(self, problem): raise NotImplementedError def breadth_first_tree_search(problem): frontier = deque([Node(problem.initial)]) while frontier: node = frontier.popleft() if problem.goal_test(node.state): return node frontier.extend(node.expand(problem)) return None def depth_first_tree_search(problem): frontier = [Node(problem.initial)] while frontier: node = frontier.pop() if problem.goal_test(node.state): return node frontier.extend(node.expand(problem)) return None def depth_first_graph_search(problem): frontier = [(Node(problem.initial))] explored = set() while frontier: node = frontier.pop() if problem.goal_test(node.state): return node explored.add(node.state) frontier.extend(child for child in node.expand(problem) if child.state not in explored and child not in frontier) return None def breadth_first_graph_search(problem): node = Node(problem.initial) if problem.goal_test(node.state): return node frontier = deque([node]) explored = set() while frontier: node = frontier.popleft() explored.add(node.state) for child in node.expand(problem): if child.state not in explored and child not in frontier: if problem.goal_test(child.state): return child frontier.append(child) return None def best_first_graph_search(problem, f): f = memoize(f, 'f') node = Node(problem.initial) frontier = PriorityQueue('min', f) frontier.append(node) explored = set() while frontier: node = frontier.pop() if problem.goal_test(node.state): return node explored.add(node.state) for child in node.expand(problem): if child.state not in explored and child not in frontier: frontier.append(child) elif child in frontier: if f(child) < frontier[child]: del frontier[child] frontier.append(child) return None def uniform_cost_search(problem): return best_first_graph_search(problem, lambda node: node.path_cost) def depth_limited_search(problem, limit=50): def recursive_dls(node, problem, limit): if problem.goal_test(node.state): return node elif limit == 0: return 'cutoff' else: cutoff_occurred = False for child in node.expand(problem): result = recursive_dls(child, problem, limit - 1) if result == 'cutoff': cutoff_occurred = True elif result is not None: return result return 'cutoff' if cutoff_occurred else None return recursive_dls(Node(problem.initial), problem, limit) def iterative_deepening_search(problem): for depth in range(sys.maxsize): result = depth_limited_search(problem, depth) if result != 'cutoff': return result def bidirectional_search(problem): e = problem.find_min_edge() gF, gB = {problem.initial: 0}, {problem.goal: 0} openF, openB = [problem.initial], [problem.goal] closedF, closedB = [], [] U = infinity def extend(U, open_dir, open_other, g_dir, g_other, closed_dir): n = find_key(C, open_dir, g_dir) open_dir.remove(n) closed_dir.append(n) for c in problem.actions(n): if c in open_dir or c in closed_dir: if g_dir[c] <= problem.path_cost(g_dir[n], n, None, c): continue open_dir.remove(c) g_dir[c] = problem.path_cost(g_dir[n], n, None, c) open_dir.append(c) if c in open_other: U = min(U, g_dir[c] + g_other[c]) return U, open_dir, closed_dir, g_dir def find_min(open_dir, g): m, m_f = infinity, infinity for n in open_dir: f = g[n] + problem.h(n) pr = max(f, 2 * g[n]) m = min(m, pr) m_f = min(m_f, f) return m, m_f, min(g.values()) def find_key(pr_min, open_dir, g): m = infinity state = -1 for n in open_dir: pr = max(g[n] + problem.h(n), 2 * g[n]) if pr == pr_min: if g[n] < m: m = g[n] state = n return state while openF and openB: pr_min_f, f_min_f, g_min_f = find_min(openF, gF) pr_min_b, f_min_b, g_min_b = find_min(openB, gB) C = min(pr_min_f, pr_min_b) if U <= max(C, f_min_f, f_min_b, g_min_f + g_min_b + e): return U if C == pr_min_f: U, openF, closedF, gF = extend(U, openF, openB, gF, gB, closedF) else: U, openB, closedB, gB = extend(U, openB, openF, gB, gF, closedB) return infinity greedy_best_first_graph_search = best_first_graph_search def astar_search(problem, h=None): h = memoize(h or problem.h, 'h') return best_first_graph_search(problem, lambda n: n.path_cost + h(n)) class EightPuzzle(Problem): def __init__(self, initial, goal=(1, 2, 3, 4, 5, 6, 7, 8, 0)): self.goal = goal Problem.__init__(self, initial, goal) def find_blank_square(self, state): return state.index(0) def actions(self, state): possible_actions = ['UP', 'DOWN', 'LEFT', 'RIGHT'] index_blank_square = self.find_blank_square(state) if index_blank_square % 3 == 0: possible_actions.remove('LEFT') if index_blank_square < 3: possible_actions.remove('UP') if index_blank_square % 3 == 2: possible_actions.remove('RIGHT') if index_blank_square > 5: possible_actions.remove('DOWN') return possible_actions def result(self, state, action): blank = self.find_blank_square(state) new_state = list(state) delta = {'UP': -3, 'DOWN': 3, 'LEFT': -1, 'RIGHT': 1} neighbor = blank + delta[action] new_state[blank], new_state[neighbor] = new_state[neighbor], new_state[blank] return tuple(new_state) def goal_test(self, state): return state == self.goal def check_solvability(self, state): inversion = 0 for i in range(len(state)): for j in range(i + 1, len(state)): if (state[i] > state[j]) and state[i] != 0 and state[j] != 0: inversion += 1 return inversion % 2 == 0 def h(self, node): return sum(s != g for (s, g) in zip(node.state, self.goal)) class PlanRoute(Problem): def __init__(self, initial, goal, allowed, dimrow): self.dimrow = dimrow self.goal = goal self.allowed = allowed Problem.__init__(self, initial, goal) def actions(self, state): possible_actions = ['Forward', 'TurnLeft', 'TurnRight'] x, y = state.get_location() orientation = state.get_orientation() if x == 1 and orientation == 'LEFT': if 'Forward' in possible_actions: possible_actions.remove('Forward') if y == 1 and orientation == 'DOWN': if 'Forward' in possible_actions: possible_actions.remove('Forward') if x == self.dimrow and orientation == 'RIGHT': if 'Forward' in possible_actions: possible_actions.remove('Forward') if y == self.dimrow and orientation == 'UP': if 'Forward' in possible_actions: possible_actions.remove('Forward') return possible_actions def result(self, state, action): x, y = state.get_location() proposed_loc = list() if action == 'Forward': if state.get_orientation() == 'UP': proposed_loc = [x, y + 1] elif state.get_orientation() == 'DOWN': proposed_loc = [x, y - 1] elif state.get_orientation() == 'LEFT': proposed_loc = [x - 1, y] elif state.get_orientation() == 'RIGHT': proposed_loc = [x + 1, y] else: raise Exception('InvalidOrientation') elif action == 'TurnLeft': if state.get_orientation() == 'UP': state.set_orientation('LEFT') elif state.get_orientation() == 'DOWN': state.set_orientation('RIGHT') elif state.get_orientation() == 'LEFT': state.set_orientation('DOWN') elif state.get_orientation() == 'RIGHT': state.set_orientation('UP') else: raise Exception('InvalidOrientation') elif action == 'TurnRight': if state.get_orientation() == 'UP': state.set_orientation('RIGHT') elif state.get_orientation() == 'DOWN': state.set_orientation('LEFT') elif state.get_orientation() == 'LEFT': state.set_orientation('UP') elif state.get_orientation() == 'RIGHT': state.set_orientation('DOWN') else: raise Exception('InvalidOrientation') if proposed_loc in self.allowed: state.set_location(proposed_loc[0], [proposed_loc[1]]) return state def goal_test(self, state): return state.get_location() == tuple(self.goal) def h(self, node): x1, y1 = node.state.get_location() x2, y2 = self.goal return abs(x2 - x1) + abs(y2 - y1) def recursive_best_first_search(problem, h=None): h = memoize(h or problem.h, 'h') def RBFS(problem, node, flimit): if problem.goal_test(node.state): return node, 0 successors = node.expand(problem) if len(successors) == 0: return None, infinity for s in successors: s.f = max(s.path_cost + h(s), node.f) while True: successors.sort(key=lambda x: x.f) best = successors[0] if best.f > flimit: return None, best.f if len(successors) > 1: alternative = successors[1].f else: alternative = infinity result, best.f = RBFS(problem, best, min(flimit, alternative)) if result is not None: return result, best.f node = Node(problem.initial) node.f = h(node) result, bestf = RBFS(problem, node, infinity) return result def hill_climbing(problem): current = Node(problem.initial) while True: neighbors = current.expand(problem) if not neighbors: break neighbor = argmax_random_tie(neighbors, key=lambda node: problem.value(node.state)) if problem.value(neighbor.state) <= problem.value(current.state): break current = neighbor return current.state def exp_schedule(k=20, lam=0.005, limit=100): return lambda t: (k * math.exp(-lam * t) if t < limit else 0) def simulated_annealing(problem, schedule=exp_schedule()): current = Node(problem.initial) for t in range(sys.maxsize): T = schedule(t) if T == 0: return current.state neighbors = current.expand(problem) if not neighbors: return current.state next_choice = random.choice(neighbors) delta_e = problem.value(next_choice.state) - problem.value(current.state) if delta_e > 0 or probability(math.exp(delta_e / T)): current = next_choice def simulated_annealing_full(problem, schedule=exp_schedule()): states = [] current = Node(problem.initial) for t in range(sys.maxsize): states.append(current.state) T = schedule(t) if T == 0: return states neighbors = current.expand(problem) if not neighbors: return current.state next_choice = random.choice(neighbors) delta_e = problem.value(next_choice.state) - problem.value(current.state) if delta_e > 0 or probability(math.exp(delta_e / T)): current = next_choice def and_or_graph_search(problem): def or_search(state, problem, path): if problem.goal_test(state): return [] if state in path: return None for action in problem.actions(state): plan = and_search(problem.result(state, action), problem, path + [state, ]) if plan is not None: return [action, plan] def and_search(states, problem, path): plan = {} for s in states: plan[s] = or_search(s, problem, path) if plan[s] is None: return None return plan return or_search(problem.initial, problem, []) directions4 = {'W': (-1, 0), 'N': (0, 1), 'E': (1, 0), 'S': (0, -1)} directions8 = dict(directions4) directions8.update({'NW': (-1, 1), 'NE': (1, 1), 'SE': (1, -1), 'SW': (-1, -1)}) class PeakFindingProblem(Problem): def __init__(self, initial, grid, defined_actions=directions4): Problem.__init__(self, initial) self.grid = grid self.defined_actions = defined_actions self.n = len(grid) assert self.n > 0 self.m = len(grid[0]) assert self.m > 0 def actions(self, state): allowed_actions = [] for action in self.defined_actions: next_state = vector_add(state, self.defined_actions[action]) if 0 <= next_state[0] <= self.n - 1 and next_state[1] >= 0 and next_state[1] <= self.m - 1: allowed_actions.append(action) return allowed_actions def result(self, state, action): return vector_add(state, self.defined_actions[action]) def value(self, state): x, y = state assert 0 <= x < self.n assert 0 <= y < self.m return self.grid[x][y] class OnlineDFSAgent: def __init__(self, problem): self.problem = problem self.s = None self.a = None self.untried = dict() self.unbacktracked = dict() self.result = {} def __call__(self, percept): s1 = self.update_state(percept) if self.problem.goal_test(s1): self.a = None else: if s1 not in self.untried.keys(): self.untried[s1] = self.problem.actions(s1) if self.s is not None: if s1 != self.result[(self.s, self.a)]: self.result[(self.s, self.a)] = s1 self.unbacktracked[s1].insert(0, self.s) if len(self.untried[s1]) == 0: if len(self.unbacktracked[s1]) == 0: self.a = None else: unbacktracked_pop = self.unbacktracked.pop(s1) for (s, b) in self.result.keys(): if self.result[(s, b)] == unbacktracked_pop: self.a = b break else: self.a = self.untried.pop(s1) self.s = s1 return self.a def update_state(self, percept): return percept class OnlineSearchProblem(Problem): def __init__(self, initial, goal, graph): self.initial = initial self.goal = goal self.graph = graph def actions(self, state): return self.graph.graph_dict[state].keys() def output(self, state, action): return self.graph.graph_dict[state][action] def h(self, state): return self.graph.least_costs[state] def c(self, s, a, s1): return 1 def update_state(self, percept): raise NotImplementedError def goal_test(self, state): if state == self.goal: return True return False class LRTAStarAgent: def __init__(self, problem): self.problem = problem ne self.a = None def __call__(self, s1): if self.problem.goal_test(s1): self.a = None return self.a else: if s1 not in self.H: self.H[s1] = self.problem.h(s1) if self.s is not None: H[self.s] = min(self.LRTA_cost(self.s, b, self.problem.output(self.s, b), self.H) for b in self.problem.actions(self.s)) self.a = argmin(self.problem.actions(s1), key=lambda b: self.LRTA_cost(s1, b, self.problem.output(s1, b), self.H)) self.s = s1 return self.a def LRTA_cost(self, s, a, s1, H): print(s, a, s1) if s1 is None: return self.problem.h(s) else: # to replace this try, except: we can initialize H with values from problem.h try: return self.problem.c(s, a, s1) + self.H[s1] except: return self.problem.c(s, a, s1) + self.problem.h(s1) # ______________________________________________________________________________ # Genetic Algorithm def genetic_search(problem, fitness_fn, ngen=1000, pmut=0.1, n=20): # NOTE: This is not tested and might not work. # TODO: Use this function to make Problems work with genetic_algorithm. s = problem.initial_state states = [problem.result(s, a) for a in problem.actions(s)] random.shuffle(states) return genetic_algorithm(states[:n], problem.value, ngen, pmut) def genetic_algorithm(population, fitness_fn, gene_pool=[0, 1], f_thres=None, ngen=1000, pmut=0.1): for i in range(ngen): population = [mutate(recombine(*select(2, population, fitness_fn)), gene_pool, pmut) for i in range(len(population))] fittest_individual = fitness_threshold(fitness_fn, f_thres, population) if fittest_individual: return fittest_individual return argmax(population, key=fitness_fn) def fitness_threshold(fitness_fn, f_thres, population): if not f_thres: return None fittest_individual = argmax(population, key=fitness_fn) if fitness_fn(fittest_individual) >= f_thres: return fittest_individual return None def init_population(pop_number, gene_pool, state_length): g = len(gene_pool) population = [] for i in range(pop_number): new_individual = [gene_pool[random.randrange(0, g)] for j in range(state_length)] population.append(new_individual) return population def select(r, population, fitness_fn): fitnesses = map(fitness_fn, population) sampler = weighted_sampler(population, fitnesses) return [sampler() for i in range(r)] def recombine(x, y): n = len(x) c = random.randrange(0, n) return x[:c] + y[c:] def recombine_uniform(x, y): n = len(x) result = [0] * n indexes = random.sample(range(n), n) for i in range(n): ix = indexes[i] result[ix] = x[ix] if i < n / 2 else y[ix] return ''.join(str(r) for r in result) def mutate(x, gene_pool, pmut): if random.uniform(0, 1) >= pmut: return x n = len(x) g = len(gene_pool) c = random.randrange(0, n) r = random.randrange(0, g) new_gene = gene_pool[r] return x[:c] + [new_gene] + x[c + 1:] # _____________________________________________________________________________ # The remainder of this file implements examples for the search algorithms. # ______________________________________________________________________________ # Graphs and Graph Problems class Graph: def __init__(self, graph_dict=None, directed=True): self.graph_dict = graph_dict or {} self.directed = directed if not directed: self.make_undirected() def make_undirected(self): for a in list(self.graph_dict.keys()): for (b, dist) in self.graph_dict[a].items(): self.connect1(b, a, dist) def connect(self, A, B, distance=1): self.connect1(A, B, distance) if not self.directed: self.connect1(B, A, distance) def connect1(self, A, B, distance): self.graph_dict.setdefault(A, {})[B] = distance def get(self, a, b=None): links = self.graph_dict.setdefault(a, {}) if b is None: return links else: return links.get(b) def nodes(self): s1 = set([k for k in self.graph_dict.keys()]) s2 = set([k2 for v in self.graph_dict.values() for k2, v2 in v.items()]) nodes = s1.union(s2) return list(nodes) def UndirectedGraph(graph_dict=None): return Graph(graph_dict=graph_dict, directed=False) def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300, curvature=lambda: random.uniform(1.1, 1.5)): g = UndirectedGraph() g.locations = {} # Build the cities for node in nodes: g.locations[node] = (random.randrange(width), random.randrange(height)) # Build roads from each city to at least min_links nearest neighbors. for i in range(min_links): for node in nodes: if len(g.get(node)) < min_links: here = g.locations[node] def distance_to_node(n): if n is node or g.get(node, n): return infinity return distance(g.locations[n], here) neighbor = argmin(nodes, key=distance_to_node) d = distance(g.locations[neighbor], here) * curvature() g.connect(node, neighbor, int(d)) return g romania_map = UndirectedGraph(dict( Arad=dict(Zerind=75, Sibiu=140, Timisoara=118), Bucharest=dict(Urziceni=85, Pitesti=101, Giurgiu=90, Fagaras=211), Craiova=dict(Drobeta=120, Rimnicu=146, Pitesti=138), Drobeta=dict(Mehadia=75), Eforie=dict(Hirsova=86), Fagaras=dict(Sibiu=99), Hirsova=dict(Urziceni=98), Iasi=dict(Vaslui=92, Neamt=87), Lugoj=dict(Timisoara=111, Mehadia=70), Oradea=dict(Zerind=71, Sibiu=151), Pitesti=dict(Rimnicu=97), Rimnicu=dict(Sibiu=80), Urziceni=dict(Vaslui=142))) romania_map.locations = dict( Arad=(91, 492), Bucharest=(400, 327), Craiova=(253, 288), Drobeta=(165, 299), Eforie=(562, 293), Fagaras=(305, 449), Giurgiu=(375, 270), Hirsova=(534, 350), Iasi=(473, 506), Lugoj=(165, 379), Mehadia=(168, 339), Neamt=(406, 537), Oradea=(131, 571), Pitesti=(320, 368), Rimnicu=(233, 410), Sibiu=(207, 457), Timisoara=(94, 410), Urziceni=(456, 350), Vaslui=(509, 444), Zerind=(108, 531)) vacuum_world = Graph(dict( State_1=dict(Suck=['State_7', 'State_5'], Right=['State_2']), State_2=dict(Suck=['State_8', 'State_4'], Left=['State_2']), State_3=dict(Suck=['State_7'], Right=['State_4']), State_4=dict(Suck=['State_4', 'State_2'], Left=['State_3']), State_5=dict(Suck=['State_5', 'State_1'], Right=['State_6']), State_6=dict(Suck=['State_8'], Left=['State_5']), State_7=dict(Suck=['State_7', 'State_3'], Right=['State_8']), State_8=dict(Suck=['State_8', 'State_6'], Left=['State_7']) )) one_dim_state_space = Graph(dict( State_1=dict(Right='State_2'), State_2=dict(Right='State_3', Left='State_1'), State_3=dict(Right='State_4', Left='State_2'), State_4=dict(Right='State_5', Left='State_3'), State_5=dict(Right='State_6', Left='State_4'), State_6=dict(Left='State_5') )) one_dim_state_space.least_costs = dict( State_1=8, State_2=9, State_3=2, State_4=2, State_5=4, State_6=3) australia_map = UndirectedGraph(dict( T=dict(), SA=dict(WA=1, NT=1, Q=1, NSW=1, V=1), NT=dict(WA=1, Q=1), NSW=dict(Q=1, V=1))) australia_map.locations = dict(WA=(120, 24), NT=(135, 20), SA=(135, 30), Q=(145, 20), NSW=(145, 32), T=(145, 42), V=(145, 37)) class GraphProblem(Problem): def __init__(self, initial, goal, graph): Problem.__init__(self, initial, goal) self.graph = graph def actions(self, A): return list(self.graph.get(A).keys()) def result(self, state, action): return action def path_cost(self, cost_so_far, A, action, B): return cost_so_far + (self.graph.get(A, B) or infinity) def find_min_edge(self): m = infinity for d in self.graph.graph_dict.values(): local_min = min(d.values()) m = min(m, local_min) return m def h(self, node): locs = getattr(self.graph, 'locations', None) if locs: if type(node) is str: return int(distance(locs[node], locs[self.goal])) return int(distance(locs[node.state], locs[self.goal])) else: return infinity class GraphProblemStochastic(GraphProblem): def result(self, state, action): return self.graph.get(state, action) def path_cost(self): raise NotImplementedError # ______________________________________________________________________________ class NQueensProblem(Problem): def __init__(self, N): self.N = N self.initial = tuple([-1] * N) Problem.__init__(self, self.initial) def actions(self, state): if state[-1] is not -1: return [] # All columns filled; no successors else: col = state.index(-1) return [row for row in range(self.N) if not self.conflicted(state, row, col)] def result(self, state, row): col = state.index(-1) new = list(state[:]) new[col] = row return tuple(new) def conflicted(self, state, row, col): return any(self.conflict(row, col, state[c], c) for c in range(col)) def conflict(self, row1, col1, row2, col2): return (row1 == row2 or # same row col1 == col2 or # same column row1 - col1 == row2 - col2 or # same \ diagonal row1 + col1 == row2 + col2) # same / diagonal def goal_test(self, state): if state[-1] is -1: return False return not any(self.conflicted(state, state[col], col) for col in range(len(state))) def h(self, node): num_conflicts = 0 for (r1, c1) in enumerate(node.state): for (r2, c2) in enumerate(node.state): if (r1, c1) != (r2, c2): num_conflicts += self.conflict(r1, c1, r2, c2) return num_conflicts # ______________________________________________________________________________ # Inverse Boggle: Search for a high-scoring Boggle board. A good domain for # iterative-repair and related search techniques, as suggested by Justin Boyan. ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' cubes16 = ['FORIXB', 'MOQABJ', 'GURILW', 'SETUPL', 'CMPDAE', 'ACITAO', 'SLCRAE', 'ROMASH', 'NODESW', 'HEFIYE', 'ONUDTK', 'TEVIGN', 'ANEDVZ', 'PINESH', 'ABILYT', 'GKYLEU'] def random_boggle(n=4): cubes = [cubes16[i % 16] for i in range(n * n)] random.shuffle(cubes) return list(map(random.choice, cubes)) # The best 5x5 board found by Boyan, with our word list this board scores # 2274 words, for a score of 9837 boyan_best = list('RSTCSDEIAEGNLRPEATESMSSID') def print_boggle(board): n2 = len(board) n = exact_sqrt(n2) for i in range(n2): if i % n == 0 and i > 0: print() if board[i] == 'Q': print('Qu', end=' ') else: print(str(board[i]) + ' ', end=' ') print() def boggle_neighbors(n2, cache={}): if cache.get(n2): return cache.get(n2) n = exact_sqrt(n2) neighbors = [None] * n2 for i in range(n2): neighbors[i] = [] on_top = i < n on_bottom = i >= n2 - n on_left = i % n == 0 on_right = (i + 1) % n == 0 if not on_top: neighbors[i].append(i - n) if not on_left: neighbors[i].append(i - n - 1) if not on_right: neighbors[i].append(i - n + 1) if not on_bottom: neighbors[i].append(i + n) if not on_left: neighbors[i].append(i + n - 1) if not on_right: neighbors[i].append(i + n + 1) if not on_left: neighbors[i].append(i - 1) if not on_right: neighbors[i].append(i + 1) cache[n2] = neighbors return neighbors def exact_sqrt(n2): n = int(math.sqrt(n2)) assert n * n == n2 return n # _____________________________________________________________________________ class Wordlist: def __init__(self, file, min_len=3): lines = file.read().upper().split() self.words = [word for word in lines if len(word) >= min_len] self.words.sort() self.bounds = {} for c in ALPHABET: c2 = chr(ord(c) + 1) self.bounds[c] = (bisect.bisect(self.words, c), bisect.bisect(self.words, c2)) def lookup(self, prefix, lo=0, hi=None): words = self.words if hi is None: hi = len(words) i = bisect.bisect_left(words, prefix, lo, hi) if i < len(words) and words[i].startswith(prefix): return i, (words[i] == prefix) else: return None, False def __contains__(self, word): return self.lookup(word)[1] def __len__(self): return len(self.words) # _____________________________________________________________________________ class BoggleFinder: wordlist = None # A class variable, holding a wordlist def __init__(self, board=None): if BoggleFinder.wordlist is None: BoggleFinder.wordlist = Wordlist(open_data("EN-text/wordlist.txt")) self.found = {} if board: self.set_board(board) def set_board(self, board=None): if board is None: board = random_boggle() self.board = board self.neighbors = boggle_neighbors(len(board)) self.found = {} for i in range(len(board)): lo, hi = self.wordlist.bounds[board[i]] self.find(lo, hi, i, [], '') return self def find(self, lo, hi, i, visited, prefix): if i in visited: return wordpos, is_word = self.wordlist.lookup(prefix, lo, hi) if wordpos is not None: if is_word: self.found[prefix] = True visited.append(i) c = self.board[i] if c == 'Q': c = 'QU' prefix += c for j in self.neighbors[i]: self.find(wordpos, hi, j, visited, prefix) visited.pop() def words(self): return list(self.found.keys()) scores = [0, 0, 0, 0, 1, 2, 3, 5] + [11] * 100 def score(self): return sum([self.scores[len(w)] for w in self.words()]) def __len__(self): return len(self.found) # _____________________________________________________________________________ def boggle_hill_climbing(board=None, ntimes=100, verbose=True): finder = BoggleFinder() if board is None: board = random_boggle() best = len(finder.set_board(board)) for _ in range(ntimes): i, oldc = mutate_boggle(board) new = len(finder.set_board(board)) if new > best: best = new if verbose: print(best, _, board) else: board[i] = oldc # Change back if verbose: print_boggle(board) return board, best def mutate_boggle(board): i = random.randrange(len(board)) oldc = board[i] # random.choice(boyan_best) board[i] = random.choice(random.choice(cubes16)) return i, oldc # ______________________________________________________________________________ # Code to compare searchers on various problems. class InstrumentedProblem(Problem): def __init__(self, problem): self.problem = problem self.succs = self.goal_tests = self.states = 0 self.found = None def actions(self, state): self.succs += 1 return self.problem.actions(state) def result(self, state, action): self.states += 1 return self.problem.result(state, action) def goal_test(self, state): self.goal_tests += 1 result = self.problem.goal_test(state) if result: self.found = state return result def path_cost(self, c, state1, action, state2): return self.problem.path_cost(c, state1, action, state2) def value(self, state): return self.problem.value(state) def __getattr__(self, attr): return getattr(self.problem, attr) def __repr__(self): return '<{:4d}/{:4d}/{:4d}/{}>'.format(self.succs, self.goal_tests, self.states, str(self.found)[:4]) def compare_searchers(problems, header, searchers=[breadth_first_tree_search, breadth_first_graph_search, depth_first_graph_search, iterative_deepening_search, depth_limited_search, recursive_best_first_search]): def do(searcher, problem): p = InstrumentedProblem(problem) searcher(p) return p table = [[name(s)] + [do(s, p) for p in problems] for s in searchers] print_table(table, header) def compare_graph_searchers(): compare_searchers(problems=[GraphProblem('Arad', 'Bucharest', romania_map), GraphProblem('Oradea', 'Neamt', romania_map), GraphProblem('Q', 'WA', australia_map)], header=['Searcher', 'romania_map(Arad, Bucharest)', 'romania_map(Oradea, Neamt)', 'australia_map'])
true
true
1c3c1a89991aca11b841886d909194893dc2d35d
3,207
py
Python
tests/__init__.py
fperetti/callee
58740f73ff9a76f5fe0075bf18d7345a0f9d961c
[ "BSD-3-Clause" ]
72
2016-03-21T03:58:33.000Z
2022-03-29T10:24:51.000Z
tests/__init__.py
fperetti/callee
58740f73ff9a76f5fe0075bf18d7345a0f9d961c
[ "BSD-3-Clause" ]
14
2016-03-21T03:58:39.000Z
2021-09-07T16:26:03.000Z
tests/__init__.py
fperetti/callee
58740f73ff9a76f5fe0075bf18d7345a0f9d961c
[ "BSD-3-Clause" ]
9
2016-10-26T14:39:00.000Z
2021-08-13T17:39:35.000Z
""" Test package. """ import os import sys try: import unittest.mock as mock except ImportError: import mock from taipan.testing import TestCase as _TestCase from callee._compat import asyncio __all__ = [ 'IS_PY34', 'IS_PY35', 'MatcherTestCase', 'python_code' ] IS_PY34 = sys.version_info >= (3, 4) IS_PY35 = sys.version_info >= (3, 5) class TestCase(_TestCase): """Base class for all test cases.""" def setUp(self): super(TestCase, self).setUpClass() # display full diffs when equality assertions fail under py.test self.maxDiff = None class MatcherTestCase(TestCase): """Base class for matcher test cases.""" def assert_match(self, matcher, value): m = mock.Mock() m(value) m.assert_called_with(matcher) return True def assert_no_match(self, matcher, value): m = mock.Mock() m(value) with self.assertRaises(AssertionError): m.assert_called_with(matcher) return True def assert_repr(self, matcher, *args): """Assert on the representation of a matcher. :param matcher: Matcher object Positional arguments are expected to have their repr's be contained within the matcher's repr. """ repr_ = "%r" % matcher for arg in args: arg_repr = "%r" % arg self.assertIn( arg_repr, repr_, msg="%s (repr of %s) didn't contain expected value %s" % ( repr_, matcher.__class__.__name__, arg_repr)) def await_(self, coroutine): """Run given asynchronous coroutine to completion. This prevents a warning from being emitted when it goes out of scope. :param coroutine: A coroutine or a coroutine function """ self.assertIsNotNone( asyncio, msg="Tried to use asyncio on unsupported Python version") loop = asyncio.new_event_loop() if asyncio.iscoroutinefunction(coroutine): coroutine = coroutine(loop) loop.run_until_complete(coroutine) loop.close() return coroutine # Utility functions def python_code(source): """Format Python source code, given as a string, for use with ``exec``. Use it like so:: exec(python_code(''' async def foo(): pass ''')) This allows to use newer syntactic constructs that'd cause SyntaxError on older Python versions. """ # (Whitespace shenanigans adapted from sphinx.utils.prepare_docstring) # remove excess whitespace from source code lines which will be there # if the code was given as indented, multiline string lines = source.expandtabs().splitlines() margin = sys.maxsize for line in lines: code_len = len(line.strip()) if code_len > 0: indent = len(line) - code_len margin = min(margin, indent) if margin < sys.maxsize: for i in range(len(lines)): lines[i] = lines[i][margin:] # ensure there is an empty line at the end if lines and lines[-1]: lines.append('') return os.linesep.join(lines)
25.862903
77
0.61584
import os import sys try: import unittest.mock as mock except ImportError: import mock from taipan.testing import TestCase as _TestCase from callee._compat import asyncio __all__ = [ 'IS_PY34', 'IS_PY35', 'MatcherTestCase', 'python_code' ] IS_PY34 = sys.version_info >= (3, 4) IS_PY35 = sys.version_info >= (3, 5) class TestCase(_TestCase): def setUp(self): super(TestCase, self).setUpClass() self.maxDiff = None class MatcherTestCase(TestCase): def assert_match(self, matcher, value): m = mock.Mock() m(value) m.assert_called_with(matcher) return True def assert_no_match(self, matcher, value): m = mock.Mock() m(value) with self.assertRaises(AssertionError): m.assert_called_with(matcher) return True def assert_repr(self, matcher, *args): repr_ = "%r" % matcher for arg in args: arg_repr = "%r" % arg self.assertIn( arg_repr, repr_, msg="%s (repr of %s) didn't contain expected value %s" % ( repr_, matcher.__class__.__name__, arg_repr)) def await_(self, coroutine): self.assertIsNotNone( asyncio, msg="Tried to use asyncio on unsupported Python version") loop = asyncio.new_event_loop() if asyncio.iscoroutinefunction(coroutine): coroutine = coroutine(loop) loop.run_until_complete(coroutine) loop.close() return coroutine # Utility functions def python_code(source): # (Whitespace shenanigans adapted from sphinx.utils.prepare_docstring) # remove excess whitespace from source code lines which will be there # if the code was given as indented, multiline string lines = source.expandtabs().splitlines() margin = sys.maxsize for line in lines: code_len = len(line.strip()) if code_len > 0: indent = len(line) - code_len margin = min(margin, indent) if margin < sys.maxsize: for i in range(len(lines)): lines[i] = lines[i][margin:] # ensure there is an empty line at the end if lines and lines[-1]: lines.append('') return os.linesep.join(lines)
true
true
1c3c1b6d1bf3418e30f84f8cf25639559ef31943
3,970
py
Python
utils/polus-imagej-util/{{cookiecutter.project_slug}}/src/ij_converter.py
LabShare/polus-plugin-utils
9332ca6c229401d57b063a81973d48ce718c654c
[ "MIT" ]
null
null
null
utils/polus-imagej-util/{{cookiecutter.project_slug}}/src/ij_converter.py
LabShare/polus-plugin-utils
9332ca6c229401d57b063a81973d48ce718c654c
[ "MIT" ]
null
null
null
utils/polus-imagej-util/{{cookiecutter.project_slug}}/src/ij_converter.py
LabShare/polus-plugin-utils
9332ca6c229401d57b063a81973d48ce718c654c
[ "MIT" ]
null
null
null
''' A conversion utility built to convert abstract to primitive ''' import imagej import logging import imglyb import jpype import numpy as np import scyjava # Initialize the logger logging.basicConfig(format='%(asctime)s - %(name)-8s - %(levelname)-8s - %(message)s', datefmt='%d-%b-%y %H:%M:%S') logger = logging.getLogger("ij_converter") logger.setLevel(logging.INFO) ## fill in types to convert ABSTRACT_ITERABLES = [ 'IterableInterval', 'Iterable', ] IMG_ARRAYS = [ 'ArrayImg' ] ABSTRACT_SCALARS = [ 'RealType', ] SCALARS = [ 'double', 'float', 'long', #long type (int64) not supported by bfio 'int', 'short', 'char', 'byte', 'boolean' ] ## recognize array objects as scalar objects + '[]' ARRAYS = [s+'[]' for s in SCALARS] def _java_setup(): global IMGLYB_PRIMITIVES, PRIMITIVES, PRIMITIVE_ARRAYS IMGLYB_PRIMITIVES = { 'float32' : imglyb.types.FloatType, 'float64' : imglyb.types.DoubleType, 'int8' : imglyb.types.ByteType, 'int16' : imglyb.types.ShortType, 'int32' : imglyb.types.IntType, 'int64' : imglyb.types.LongType, 'uint8' : imglyb.types.UnsignedByteType, 'uint16' : imglyb.types.UnsignedShortType, 'uint32' : imglyb.types.UnsignedIntType, 'uint64' : imglyb.types.UnsignedLongType } # PRIMITIVES = { # 'double' : jpype.JDouble, # 'float' : jpype.JFloat, # 'long' : jpype.JLong, # 'int' : jpype.JInt, # 'short' : jpype.JShort, # 'char' : jpype.JChar, # 'byte' : jpype.JByte, # 'boolean' : jpype.JBoolean # } PRIMITIVES = { 'double' : jpype.JDouble, 'float' : jpype.JFloat, 'long' : jpype.JLong, 'int' : jpype.JInt, 'short' : jpype.JShort, 'char' : jpype.JChar, 'byte' : jpype.JByte, 'boolean' : jpype.JBoolean } PRIMITIVE_ARRAYS = { 'double[]' : jpype.JDouble[:], 'float[]' : jpype.JFloat[:], 'long[]' : jpype.JLong[:], 'int[]' : jpype.JInt[:], 'short[]' : jpype.JShort[:], 'char[]' : jpype.JChar[:], 'byte[]' : jpype.JByte[:], 'boolean[]' : jpype.JBoolean[:] } scyjava.when_jvm_starts(_java_setup) JAVA_CONVERT = {} JAVA_CONVERT.update({ t:lambda s,t,st: IMGLYB_PRIMITIVES[str(st)](st.type(s)) for t in ABSTRACT_SCALARS }) JAVA_CONVERT.update({ t:lambda s,t,st: PRIMITIVES[t](float(s)) for t in SCALARS }) JAVA_CONVERT.update({ t:lambda s,t,st: PRIMITIVE_ARRAYS[t]([float(si) for si in s.split(',')]) for t in ARRAYS }) # JAVA_CONVERT.update({ # t: lambda s,t,st: IMGLYB_PRIMITIVES[str(st)](s) for t in SCALARS # }) JAVA_CONVERT.update({ t:lambda s,ij: imglyb.util.Views.iterable(ij.py.to_java(s)) for t in ABSTRACT_ITERABLES }) JAVA_CONVERT.update({ t:lambda s,ij: imglyb.util._to_imglib(s) for t in IMG_ARRAYS }) def to_java(ij, np_array,java_type,java_dtype=None): if ij == None: raise ValueError('No imagej instance found.') if isinstance(np_array,type(None)): return None if java_type in JAVA_CONVERT.keys(): if str(java_dtype) != 'None': out_array = JAVA_CONVERT[java_type](np_array,java_type,java_dtype) else: out_array = JAVA_CONVERT[java_type](np_array, ij) else: logger.warning('Did not recognize type, {}, will pass default.'.format(java_type)) out_array = ij.py.to_java(np_array) return out_array def from_java(ij, java_array,java_type): if ij == None: raise ValueError('No imagej instance found.') if ij.py.dtype(java_array) == bool: java_array = ij.op().convert().uint8(java_array) return ij.py.from_java(java_array)
27.569444
92
0.581612
import imagej import logging import imglyb import jpype import numpy as np import scyjava logging.basicConfig(format='%(asctime)s - %(name)-8s - %(levelname)-8s - %(message)s', datefmt='%d-%b-%y %H:%M:%S') logger = logging.getLogger("ij_converter") logger.setLevel(logging.INFO) 'IterableInterval', 'Iterable', ] IMG_ARRAYS = [ 'ArrayImg' ] ABSTRACT_SCALARS = [ 'RealType', ] SCALARS = [ 'double', 'float', 'long', 'int', 'short', 'char', 'byte', 'boolean' ] up(): global IMGLYB_PRIMITIVES, PRIMITIVES, PRIMITIVE_ARRAYS IMGLYB_PRIMITIVES = { 'float32' : imglyb.types.FloatType, 'float64' : imglyb.types.DoubleType, 'int8' : imglyb.types.ByteType, 'int16' : imglyb.types.ShortType, 'int32' : imglyb.types.IntType, 'int64' : imglyb.types.LongType, 'uint8' : imglyb.types.UnsignedByteType, 'uint16' : imglyb.types.UnsignedShortType, 'uint32' : imglyb.types.UnsignedIntType, 'uint64' : imglyb.types.UnsignedLongType } PRIMITIVES = { 'double' : jpype.JDouble, 'float' : jpype.JFloat, 'long' : jpype.JLong, 'int' : jpype.JInt, 'short' : jpype.JShort, 'char' : jpype.JChar, 'byte' : jpype.JByte, 'boolean' : jpype.JBoolean } PRIMITIVE_ARRAYS = { 'double[]' : jpype.JDouble[:], 'float[]' : jpype.JFloat[:], 'long[]' : jpype.JLong[:], 'int[]' : jpype.JInt[:], 'short[]' : jpype.JShort[:], 'char[]' : jpype.JChar[:], 'byte[]' : jpype.JByte[:], 'boolean[]' : jpype.JBoolean[:] } scyjava.when_jvm_starts(_java_setup) JAVA_CONVERT = {} JAVA_CONVERT.update({ t:lambda s,t,st: IMGLYB_PRIMITIVES[str(st)](st.type(s)) for t in ABSTRACT_SCALARS }) JAVA_CONVERT.update({ t:lambda s,t,st: PRIMITIVES[t](float(s)) for t in SCALARS }) JAVA_CONVERT.update({ t:lambda s,t,st: PRIMITIVE_ARRAYS[t]([float(si) for si in s.split(',')]) for t in ARRAYS }) JAVA_CONVERT.update({ t:lambda s,ij: imglyb.util.Views.iterable(ij.py.to_java(s)) for t in ABSTRACT_ITERABLES }) JAVA_CONVERT.update({ t:lambda s,ij: imglyb.util._to_imglib(s) for t in IMG_ARRAYS }) def to_java(ij, np_array,java_type,java_dtype=None): if ij == None: raise ValueError('No imagej instance found.') if isinstance(np_array,type(None)): return None if java_type in JAVA_CONVERT.keys(): if str(java_dtype) != 'None': out_array = JAVA_CONVERT[java_type](np_array,java_type,java_dtype) else: out_array = JAVA_CONVERT[java_type](np_array, ij) else: logger.warning('Did not recognize type, {}, will pass default.'.format(java_type)) out_array = ij.py.to_java(np_array) return out_array def from_java(ij, java_array,java_type): if ij == None: raise ValueError('No imagej instance found.') if ij.py.dtype(java_array) == bool: java_array = ij.op().convert().uint8(java_array) return ij.py.from_java(java_array)
true
true
1c3c1b943af1cf8f343f2b4dac3ce1ef888fde1d
1,202
py
Python
ex100.py
ArthurCorrea/python-exercises
0c2ac46b8c40dd9868b132e847cfa42e025095e3
[ "MIT" ]
null
null
null
ex100.py
ArthurCorrea/python-exercises
0c2ac46b8c40dd9868b132e847cfa42e025095e3
[ "MIT" ]
null
null
null
ex100.py
ArthurCorrea/python-exercises
0c2ac46b8c40dd9868b132e847cfa42e025095e3
[ "MIT" ]
null
null
null
# Crie um programa que tenha uma lista chamada números e duas # funções chamadas sorteia() e somaPar(). A primeira função # vai sortear 5 números e vai colocá-los dentro da lista e # a segunda função vai mostrar a soma entre todos os valores # PARES sorteados pela função anterior. from random import randint from time import sleep def sorteia(): soma = 0 valores = [randint(1, 15), randint(1, 15), randint(1, 15), randint(1, 15), randint(1, 15)] print(f'5 valores sorteados: ', end='') for item in valores: print(f'{item} ', end='') sleep(0.3) for n in valores: if n % 2 == 0: soma += n sleep(1) print(f'\nSoma de todos os números pares: {soma}') sorteia() print('-='*20) # Resolução do professor def sorteie(lista): print('Sorteando 5 valores: ', end='') for cont in range(0, 5): n = randint(1, 15) lista.append(n) print(f'{n} ', end='') sleep(0.3) def somaPar(lista): som = 0 for valor in lista: if valor % 2 == 0: som += valor sleep(1) print(f'\nA soma entre todos os valores pares dessa lista é {som}.') nums = [] sorteie(nums) somaPar(nums)
21.854545
94
0.601498
from random import randint from time import sleep def sorteia(): soma = 0 valores = [randint(1, 15), randint(1, 15), randint(1, 15), randint(1, 15), randint(1, 15)] print(f'5 valores sorteados: ', end='') for item in valores: print(f'{item} ', end='') sleep(0.3) for n in valores: if n % 2 == 0: soma += n sleep(1) print(f'\nSoma de todos os números pares: {soma}') sorteia() print('-='*20) def sorteie(lista): print('Sorteando 5 valores: ', end='') for cont in range(0, 5): n = randint(1, 15) lista.append(n) print(f'{n} ', end='') sleep(0.3) def somaPar(lista): som = 0 for valor in lista: if valor % 2 == 0: som += valor sleep(1) print(f'\nA soma entre todos os valores pares dessa lista é {som}.') nums = [] sorteie(nums) somaPar(nums)
true
true
1c3c1bc0bdfeb11d42c1fefef32e5893a855a255
8,658
py
Python
tests/p2p/test_discovery.py
jestersimpps/py-evm
6135904fb27b322619559e7637be40014ae254ac
[ "MIT" ]
null
null
null
tests/p2p/test_discovery.py
jestersimpps/py-evm
6135904fb27b322619559e7637be40014ae254ac
[ "MIT" ]
4
2018-12-07T21:32:48.000Z
2019-02-22T15:25:01.000Z
tests/p2p/test_discovery.py
jestersimpps/py-evm
6135904fb27b322619559e7637be40014ae254ac
[ "MIT" ]
null
null
null
import random import string import rlp from eth_utils import ( decode_hex, keccak, to_bytes, ) from eth_keys import keys from p2p import discovery from p2p import kademlia from p2p.utils import safe_ord def test_ping_pong(): alice = get_discovery_protocol(b"alice") bob = get_discovery_protocol(b"bob") # Connect alice's and bob's transports directly so we don't need to deal with the complexities # of going over the wire. link_transports(alice, bob) # Collect all pongs received by alice in a list for later inspection. received_pongs = [] alice.recv_pong = lambda node, payload, hash_: received_pongs.append((node, payload)) token = alice.send_ping(bob.this_node) assert len(received_pongs) == 1 node, payload = received_pongs[0] assert node.id == bob.this_node.id assert token == payload[1] def test_find_node_neighbours(): alice = get_discovery_protocol(b"alice") bob = get_discovery_protocol(b"bob") # Add some nodes to bob's routing table so that it has something to use when replying to # alice's find_node. for _ in range(kademlia.k_bucket_size * 2): bob.kademlia.update_routing_table(random_node()) # Connect alice's and bob's transports directly so we don't need to deal with the complexities # of going over the wire. link_transports(alice, bob) # Collect all neighbours packets received by alice in a list for later inspection. received_neighbours = [] alice.recv_neighbours = lambda node, payload, hash_: received_neighbours.append((node, payload)) # Pretend that bob and alice have already bonded, otherwise bob will ignore alice's find_node. bob.kademlia.update_routing_table(alice.this_node) alice.send_find_node(bob.this_node, alice.this_node.id) # Bob should have sent two neighbours packets in order to keep the total packet size under the # 1280 bytes limit. assert len(received_neighbours) == 2 packet1, packet2 = received_neighbours neighbours = [] for packet in [packet1, packet2]: node, payload = packet assert node == bob.this_node neighbours.extend(discovery._extract_nodes_from_payload(payload[0])) assert len(neighbours) == kademlia.k_bucket_size def test_get_max_neighbours_per_packet(): proto = get_discovery_protocol() # This test is just a safeguard against changes that inadvertently modify the behaviour of # _get_max_neighbours_per_packet(). assert proto._get_max_neighbours_per_packet() == 12 def test_pack(): sender, recipient = random_address(), random_address() version = rlp.sedes.big_endian_int.serialize(discovery.PROTO_VERSION) payload = [version, sender.to_endpoint(), recipient.to_endpoint()] privkey = keys.PrivateKey(keccak(b"seed")) message = discovery._pack(discovery.CMD_PING.id, payload, privkey) pubkey, cmd_id, payload, _ = discovery._unpack(message) assert pubkey == privkey.public_key assert cmd_id == discovery.CMD_PING.id assert len(payload) == discovery.CMD_PING.elem_count def test_unpack_eip8_packets(): # Test our _unpack() function against the sample packets specified in # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-8.md for cmd, packets in eip8_packets.items(): for _, packet in packets.items(): pubkey, cmd_id, payload, _ = discovery._unpack(packet) assert pubkey.to_hex() == '0xca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be00812904767bf5ccd1fc7f' # noqa: E501 assert cmd.id == cmd_id assert cmd.elem_count == len(payload) def remove_chars(s, chars): d = {safe_ord(c): None for c in chars} return s.translate(d) eip8_packets = { discovery.CMD_PING: dict( # ping packet with version 4, additional list elements ping1=decode_hex(remove_chars(''' e9614ccfd9fc3e74360018522d30e1419a143407ffcce748de3e22116b7e8dc92ff74788c0b6663a aa3d67d641936511c8f8d6ad8698b820a7cf9e1be7155e9a241f556658c55428ec0563514365799a 4be2be5a685a80971ddcfa80cb422cdd0101ec04cb847f000001820cfa8215a8d790000000000000 000000000000000000018208ae820d058443b9a3550102 ''', ' \n\t')), # ping packet with version 555, additional list elements and additional random data ping2=decode_hex(remove_chars(''' 577be4349c4dd26768081f58de4c6f375a7a22f3f7adda654d1428637412c3d7fe917cadc56d4e5e 7ffae1dbe3efffb9849feb71b262de37977e7c7a44e677295680e9e38ab26bee2fcbae207fba3ff3 d74069a50b902a82c9903ed37cc993c50001f83e82022bd79020010db83c4d001500000000abcdef 12820cfa8215a8d79020010db885a308d313198a2e037073488208ae82823a8443b9a355c5010203 040531b9019afde696e582a78fa8d95ea13ce3297d4afb8ba6433e4154caa5ac6431af1b80ba7602 3fa4090c408f6b4bc3701562c031041d4702971d102c9ab7fa5eed4cd6bab8f7af956f7d565ee191 7084a95398b6a21eac920fe3dd1345ec0a7ef39367ee69ddf092cbfe5b93e5e568ebc491983c09c7 6d922dc3 ''', ' \n\t')), ), discovery.CMD_PONG: dict( # pong packet with additional list elements and additional random data pong=decode_hex(remove_chars(''' 09b2428d83348d27cdf7064ad9024f526cebc19e4958f0fdad87c15eb598dd61d08423e0bf66b206 9869e1724125f820d851c136684082774f870e614d95a2855d000f05d1648b2d5945470bc187c2d2 216fbe870f43ed0909009882e176a46b0102f846d79020010db885a308d313198a2e037073488208 ae82823aa0fbc914b16819237dcd8801d7e53f69e9719adecb3cc0e790c57e91ca4461c9548443b9 a355c6010203c2040506a0c969a58f6f9095004c0177a6b47f451530cab38966a25cca5cb58f0555 42124e ''', ' \n\t')), ), discovery.CMD_FIND_NODE: dict( # findnode packet with additional list elements and additional random data findnode=decode_hex(remove_chars(''' c7c44041b9f7c7e41934417ebac9a8e1a4c6298f74553f2fcfdcae6ed6fe53163eb3d2b52e39fe91 831b8a927bf4fc222c3902202027e5e9eb812195f95d20061ef5cd31d502e47ecb61183f74a504fe 04c51e73df81f25c4d506b26db4517490103f84eb840ca634cae0d49acb401d8a4c6b6fe8c55b70d 115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be0081290476 7bf5ccd1fc7f8443b9a35582999983999999280dc62cc8255c73471e0a61da0c89acdc0e035e260a dd7fc0c04ad9ebf3919644c91cb247affc82b69bd2ca235c71eab8e49737c937a2c396 ''', ' \t\n')), ), discovery.CMD_NEIGHBOURS: dict( # neighbours packet with additional list elements and additional random data neighbours=decode_hex(remove_chars(''' c679fc8fe0b8b12f06577f2e802d34f6fa257e6137a995f6f4cbfc9ee50ed3710faf6e66f932c4c8 d81d64343f429651328758b47d3dbc02c4042f0fff6946a50f4a49037a72bb550f3a7872363a83e1 b9ee6469856c24eb4ef80b7535bcf99c0004f9015bf90150f84d846321163782115c82115db84031 55e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa8291 15d224c523596b401065a97f74010610fce76382c0bf32f84984010203040101b840312c55512422 cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e82 9f04c2d314fc2d4e255e0d3bc08792b069dbf8599020010db83c4d001500000000abcdef12820d05 820d05b84038643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2 d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aacf8599020010db885a308d3 13198a2e037073488203e78203e8b8408dcab8618c3253b558d459da53bd8fa68935a719aff8b811 197101a4b2b47dd2d47295286fc00cc081bb542d760717d1bdd6bec2c37cd72eca367d6dd3b9df73 8443b9a355010203b525a138aa34383fec3d2719a0 ''', ' \n\t')), ), } def get_discovery_protocol(seed=b"seed"): privkey = keys.PrivateKey(keccak(seed)) return discovery.DiscoveryProtocol(privkey, random_address(), bootstrap_nodes=[]) def link_transports(proto1, proto2): # Link both protocol's transports directly by having one's sendto() call the other's # datagram_received(). proto1.transport = type( "mock-transport", (object,), {"sendto": lambda msg, addr: proto2.datagram_received(msg, addr)}, ) proto2.transport = type( "mock-transport", (object,), {"sendto": lambda msg, addr: proto1.datagram_received(msg, addr)}, ) def random_address(): return kademlia.Address( '10.0.0.{}'.format(random.randint(0, 255)), random.randint(0, 9999)) def random_node(): seed = to_bytes(text="".join(random.sample(string.ascii_lowercase, 10))) priv_key = keys.PrivateKey(keccak(seed)) return kademlia.Node(priv_key.public_key, random_address())
42.861386
184
0.763918
import random import string import rlp from eth_utils import ( decode_hex, keccak, to_bytes, ) from eth_keys import keys from p2p import discovery from p2p import kademlia from p2p.utils import safe_ord def test_ping_pong(): alice = get_discovery_protocol(b"alice") bob = get_discovery_protocol(b"bob") # of going over the wire. link_transports(alice, bob) # Collect all pongs received by alice in a list for later inspection. received_pongs = [] alice.recv_pong = lambda node, payload, hash_: received_pongs.append((node, payload)) token = alice.send_ping(bob.this_node) assert len(received_pongs) == 1 node, payload = received_pongs[0] assert node.id == bob.this_node.id assert token == payload[1] def test_find_node_neighbours(): alice = get_discovery_protocol(b"alice") bob = get_discovery_protocol(b"bob") # Add some nodes to bob's routing table so that it has something to use when replying to for _ in range(kademlia.k_bucket_size * 2): bob.kademlia.update_routing_table(random_node()) # Connect alice's and bob's transports directly so we don't need to deal with the complexities link_transports(alice, bob) received_neighbours = [] alice.recv_neighbours = lambda node, payload, hash_: received_neighbours.append((node, payload)) bob.kademlia.update_routing_table(alice.this_node) alice.send_find_node(bob.this_node, alice.this_node.id) # Bob should have sent two neighbours packets in order to keep the total packet size under the # 1280 bytes limit. assert len(received_neighbours) == 2 packet1, packet2 = received_neighbours neighbours = [] for packet in [packet1, packet2]: node, payload = packet assert node == bob.this_node neighbours.extend(discovery._extract_nodes_from_payload(payload[0])) assert len(neighbours) == kademlia.k_bucket_size def test_get_max_neighbours_per_packet(): proto = get_discovery_protocol() # This test is just a safeguard against changes that inadvertently modify the behaviour of # _get_max_neighbours_per_packet(). assert proto._get_max_neighbours_per_packet() == 12 def test_pack(): sender, recipient = random_address(), random_address() version = rlp.sedes.big_endian_int.serialize(discovery.PROTO_VERSION) payload = [version, sender.to_endpoint(), recipient.to_endpoint()] privkey = keys.PrivateKey(keccak(b"seed")) message = discovery._pack(discovery.CMD_PING.id, payload, privkey) pubkey, cmd_id, payload, _ = discovery._unpack(message) assert pubkey == privkey.public_key assert cmd_id == discovery.CMD_PING.id assert len(payload) == discovery.CMD_PING.elem_count def test_unpack_eip8_packets(): # Test our _unpack() function against the sample packets specified in # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-8.md for cmd, packets in eip8_packets.items(): for _, packet in packets.items(): pubkey, cmd_id, payload, _ = discovery._unpack(packet) assert pubkey.to_hex() == '0xca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be00812904767bf5ccd1fc7f' # noqa: E501 assert cmd.id == cmd_id assert cmd.elem_count == len(payload) def remove_chars(s, chars): d = {safe_ord(c): None for c in chars} return s.translate(d) eip8_packets = { discovery.CMD_PING: dict( # ping packet with version 4, additional list elements ping1=decode_hex(remove_chars(''' e9614ccfd9fc3e74360018522d30e1419a143407ffcce748de3e22116b7e8dc92ff74788c0b6663a aa3d67d641936511c8f8d6ad8698b820a7cf9e1be7155e9a241f556658c55428ec0563514365799a 4be2be5a685a80971ddcfa80cb422cdd0101ec04cb847f000001820cfa8215a8d790000000000000 000000000000000000018208ae820d058443b9a3550102 ''', ' \n\t')), # ping packet with version 555, additional list elements and additional random data ping2=decode_hex(remove_chars(''' 577be4349c4dd26768081f58de4c6f375a7a22f3f7adda654d1428637412c3d7fe917cadc56d4e5e 7ffae1dbe3efffb9849feb71b262de37977e7c7a44e677295680e9e38ab26bee2fcbae207fba3ff3 d74069a50b902a82c9903ed37cc993c50001f83e82022bd79020010db83c4d001500000000abcdef 12820cfa8215a8d79020010db885a308d313198a2e037073488208ae82823a8443b9a355c5010203 040531b9019afde696e582a78fa8d95ea13ce3297d4afb8ba6433e4154caa5ac6431af1b80ba7602 3fa4090c408f6b4bc3701562c031041d4702971d102c9ab7fa5eed4cd6bab8f7af956f7d565ee191 7084a95398b6a21eac920fe3dd1345ec0a7ef39367ee69ddf092cbfe5b93e5e568ebc491983c09c7 6d922dc3 ''', ' \n\t')), ), discovery.CMD_PONG: dict( # pong packet with additional list elements and additional random data pong=decode_hex(remove_chars(''' 09b2428d83348d27cdf7064ad9024f526cebc19e4958f0fdad87c15eb598dd61d08423e0bf66b206 9869e1724125f820d851c136684082774f870e614d95a2855d000f05d1648b2d5945470bc187c2d2 216fbe870f43ed0909009882e176a46b0102f846d79020010db885a308d313198a2e037073488208 ae82823aa0fbc914b16819237dcd8801d7e53f69e9719adecb3cc0e790c57e91ca4461c9548443b9 a355c6010203c2040506a0c969a58f6f9095004c0177a6b47f451530cab38966a25cca5cb58f0555 42124e ''', ' \n\t')), ), discovery.CMD_FIND_NODE: dict( # findnode packet with additional list elements and additional random data findnode=decode_hex(remove_chars(''' c7c44041b9f7c7e41934417ebac9a8e1a4c6298f74553f2fcfdcae6ed6fe53163eb3d2b52e39fe91 831b8a927bf4fc222c3902202027e5e9eb812195f95d20061ef5cd31d502e47ecb61183f74a504fe 04c51e73df81f25c4d506b26db4517490103f84eb840ca634cae0d49acb401d8a4c6b6fe8c55b70d 115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be0081290476 7bf5ccd1fc7f8443b9a35582999983999999280dc62cc8255c73471e0a61da0c89acdc0e035e260a dd7fc0c04ad9ebf3919644c91cb247affc82b69bd2ca235c71eab8e49737c937a2c396 ''', ' \t\n')), ), discovery.CMD_NEIGHBOURS: dict( # neighbours packet with additional list elements and additional random data neighbours=decode_hex(remove_chars(''' c679fc8fe0b8b12f06577f2e802d34f6fa257e6137a995f6f4cbfc9ee50ed3710faf6e66f932c4c8 d81d64343f429651328758b47d3dbc02c4042f0fff6946a50f4a49037a72bb550f3a7872363a83e1 b9ee6469856c24eb4ef80b7535bcf99c0004f9015bf90150f84d846321163782115c82115db84031 55e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa8291 15d224c523596b401065a97f74010610fce76382c0bf32f84984010203040101b840312c55512422 cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e82 9f04c2d314fc2d4e255e0d3bc08792b069dbf8599020010db83c4d001500000000abcdef12820d05 820d05b84038643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2 d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aacf8599020010db885a308d3 13198a2e037073488203e78203e8b8408dcab8618c3253b558d459da53bd8fa68935a719aff8b811 197101a4b2b47dd2d47295286fc00cc081bb542d760717d1bdd6bec2c37cd72eca367d6dd3b9df73 8443b9a355010203b525a138aa34383fec3d2719a0 ''', ' \n\t')), ), } def get_discovery_protocol(seed=b"seed"): privkey = keys.PrivateKey(keccak(seed)) return discovery.DiscoveryProtocol(privkey, random_address(), bootstrap_nodes=[]) def link_transports(proto1, proto2): # Link both protocol's transports directly by having one's sendto() call the other's proto1.transport = type( "mock-transport", (object,), {"sendto": lambda msg, addr: proto2.datagram_received(msg, addr)}, ) proto2.transport = type( "mock-transport", (object,), {"sendto": lambda msg, addr: proto1.datagram_received(msg, addr)}, ) def random_address(): return kademlia.Address( '10.0.0.{}'.format(random.randint(0, 255)), random.randint(0, 9999)) def random_node(): seed = to_bytes(text="".join(random.sample(string.ascii_lowercase, 10))) priv_key = keys.PrivateKey(keccak(seed)) return kademlia.Node(priv_key.public_key, random_address())
true
true
1c3c1d296dc79fc3d50fbd66b4bbe1736789472f
1,818
py
Python
setup.py
karinakozarova/luxconnector
a814f2b123dc6508a5f9042186470bc44c7098f2
[ "Apache-2.0" ]
null
null
null
setup.py
karinakozarova/luxconnector
a814f2b123dc6508a5f9042186470bc44c7098f2
[ "Apache-2.0" ]
null
null
null
setup.py
karinakozarova/luxconnector
a814f2b123dc6508a5f9042186470bc44c7098f2
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open("README.md") as readme_file: readme = readme_file.read() with open("HISTORY.rst") as history_file: history = history_file.read() requirements = [ "pillow>=6.2.2, <8", "requests>=2.24.0, <3", "websocket>=0.2.1, <0.3", "websocket-client>=0.57.0, <0.58", ] setup_requirements = ["pytest-runner"] test_requirements = ["pytest", "pillow"] setup( author="Tom Nijhof", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Operating System :: Microsoft", "Natural Language :: English", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only ", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Topic :: Scientific/Engineering :: Bio-Informatics ", "Topic :: Scientific/Engineering :: Medical Science Apps.", ], description="This is a python wrapper around the Lux Client windows solution", entry_points={"console_scripts": ["luxconnector=luxconnector.cli:__init__"]}, install_requires=requirements, long_description=readme + "\n\n" + history, long_description_content_type="text/markdown", include_package_data=True, keywords="luxconnector", name="luxconnector", packages=find_packages(include=["luxconnector*"], exclude=["docs*"]), setup_requires=setup_requirements, test_suite="tests", tests_require=test_requirements, url="https://github.com/cytosmart-bv/luxconnector", version="1.0.0", zip_safe=False, )
31.894737
82
0.648515
from setuptools import setup, find_packages with open("README.md") as readme_file: readme = readme_file.read() with open("HISTORY.rst") as history_file: history = history_file.read() requirements = [ "pillow>=6.2.2, <8", "requests>=2.24.0, <3", "websocket>=0.2.1, <0.3", "websocket-client>=0.57.0, <0.58", ] setup_requirements = ["pytest-runner"] test_requirements = ["pytest", "pillow"] setup( author="Tom Nijhof", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Operating System :: Microsoft", "Natural Language :: English", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only ", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Topic :: Scientific/Engineering :: Bio-Informatics ", "Topic :: Scientific/Engineering :: Medical Science Apps.", ], description="This is a python wrapper around the Lux Client windows solution", entry_points={"console_scripts": ["luxconnector=luxconnector.cli:__init__"]}, install_requires=requirements, long_description=readme + "\n\n" + history, long_description_content_type="text/markdown", include_package_data=True, keywords="luxconnector", name="luxconnector", packages=find_packages(include=["luxconnector*"], exclude=["docs*"]), setup_requires=setup_requirements, test_suite="tests", tests_require=test_requirements, url="https://github.com/cytosmart-bv/luxconnector", version="1.0.0", zip_safe=False, )
true
true
1c3c1d81a04b1d86f1b8141bb3e96163b116f969
667
py
Python
portal/urls.py
eugenechia95/sherpalearn
27dc5e0e70521e15d266d9decbb4efe2b12f5583
[ "MIT" ]
null
null
null
portal/urls.py
eugenechia95/sherpalearn
27dc5e0e70521e15d266d9decbb4efe2b12f5583
[ "MIT" ]
null
null
null
portal/urls.py
eugenechia95/sherpalearn
27dc5e0e70521e15d266d9decbb4efe2b12f5583
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Fri Oct 19 14:35:04 2018 @author: Eugene """ from django.urls import path from portal import views from django.contrib.auth import views as auth_views urlpatterns = [ path('', views.checkauth, name='checkauth'), ] urlpatterns += [ path('users/', views.users, name='users'), path('gwoo/', views.gwoo, name='gwoo'), path('circle/', views.circle, name='circle'), #path('bulkcreate/', views.bulk, name='bulk') path('beta/', views.beta, name='beta'), path('updatedetails/', views.updatedetails, name='updatedetails'), path('password_reset/', views.change_password, name='pwreset'), ]
24.703704
70
0.647676
from django.urls import path from portal import views from django.contrib.auth import views as auth_views urlpatterns = [ path('', views.checkauth, name='checkauth'), ] urlpatterns += [ path('users/', views.users, name='users'), path('gwoo/', views.gwoo, name='gwoo'), path('circle/', views.circle, name='circle'), path('beta/', views.beta, name='beta'), path('updatedetails/', views.updatedetails, name='updatedetails'), path('password_reset/', views.change_password, name='pwreset'), ]
true
true
1c3c1dbcedc7c4aac85625f49cd4c14ae2ccab97
2,460
py
Python
src/moca_modules/moca_level_db.py
el-ideal-ideas/MocaUsersAPI
8acc17d14ad1e3c57142b24a812a1806c44180a5
[ "MIT" ]
null
null
null
src/moca_modules/moca_level_db.py
el-ideal-ideas/MocaUsersAPI
8acc17d14ad1e3c57142b24a812a1806c44180a5
[ "MIT" ]
null
null
null
src/moca_modules/moca_level_db.py
el-ideal-ideas/MocaUsersAPI
8acc17d14ad1e3c57142b24a812a1806c44180a5
[ "MIT" ]
null
null
null
# Ω* #             ■          ■■■■■   #             ■         ■■   ■■  #             ■        ■■     ■  #             ■        ■■        #   ■■■■■     ■        ■■■       #  ■■   ■■    ■         ■■■      # ■■     ■■   ■          ■■■■    # ■■     ■■   ■            ■■■■  # ■■■■■■■■■   ■              ■■■ # ■■          ■               ■■ # ■■          ■               ■■ # ■■     ■    ■        ■■     ■■ #  ■■   ■■    ■   ■■■  ■■■   ■■  #   ■■■■■     ■   ■■■    ■■■■■ """ Copyright (c) 2020.5.28 [el.ideal-ideas] This software is released under the MIT License. see LICENSE.txt or following URL. https://www.el-ideal-ideas.com/MocaSystem/LICENSE/ """ # -- Imports -------------------------------------------------------------------------- from typing import * from leveldb import LevelDB, LevelDBError from .moca_base_class import MocaClassCache, MocaNamedInstance from pathlib import Path from .moca_utils import moca_dumps as dumps, moca_loads as loads # -------------------------------------------------------------------------- Imports -- # -- Moca Level DB -------------------------------------------------------------------------- class MocaLevelDB(MocaClassCache, MocaNamedInstance): """ Level DB. Attributes ---------- self._db: LevelDB the level db. """ def __init__(self, db: Union[Path, str]): """ :param db: the filename of level database. """ MocaClassCache.__init__(self) MocaNamedInstance.__init__(self) self._db: LevelDB = LevelDB(str(db)) @property def db(self) -> LevelDB: return self._db def put(self, key: bytes, value: Any) -> bool: """Add a data to core database.""" try: self._db.Put(key, dumps(value)) return True except (LevelDBError, ValueError, TypeError): return False def get(self, key: bytes, default: Any = None) -> Any: """Get a data from core database.""" try: return loads(self._db.Get(key)) except (LevelDBError, ValueError, TypeError, KeyError): return default def delete(self, key: bytes) -> bool: """Delete data from core database.""" try: self._db.Delete(key) return True except LevelDBError: return False # -------------------------------------------------------------------------- Moca Level DB --
28.941176
93
0.411789
from typing import * from leveldb import LevelDB, LevelDBError from .moca_base_class import MocaClassCache, MocaNamedInstance from pathlib import Path from .moca_utils import moca_dumps as dumps, moca_loads as loads class MocaLevelDB(MocaClassCache, MocaNamedInstance): def __init__(self, db: Union[Path, str]): MocaClassCache.__init__(self) MocaNamedInstance.__init__(self) self._db: LevelDB = LevelDB(str(db)) @property def db(self) -> LevelDB: return self._db def put(self, key: bytes, value: Any) -> bool: try: self._db.Put(key, dumps(value)) return True except (LevelDBError, ValueError, TypeError): return False def get(self, key: bytes, default: Any = None) -> Any: try: return loads(self._db.Get(key)) except (LevelDBError, ValueError, TypeError, KeyError): return default def delete(self, key: bytes) -> bool: try: self._db.Delete(key) return True except LevelDBError: return False
true
true
1c3c1e5cc3ad2e80f9355c2aa54874bcf5276034
4,312
py
Python
tests/cmdline/commands/test_group_ls.py
mkrack/aiida-core
bab1ad6cfc8e4ff041bce268f9270c613663cb35
[ "MIT", "BSD-3-Clause" ]
null
null
null
tests/cmdline/commands/test_group_ls.py
mkrack/aiida-core
bab1ad6cfc8e4ff041bce268f9270c613663cb35
[ "MIT", "BSD-3-Clause" ]
8
2022-01-18T10:45:50.000Z
2022-03-19T18:49:42.000Z
tests/cmdline/commands/test_group_ls.py
mkrack/aiida-core
bab1ad6cfc8e4ff041bce268f9270c613663cb35
[ "MIT", "BSD-3-Clause" ]
1
2019-02-12T16:57:54.000Z
2019-02-12T16:57:54.000Z
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### """Tests for GroupPath command line interface""" # pylint: disable=redefined-outer-name,unused-argument from textwrap import dedent from click.testing import CliRunner import pytest from aiida import orm from aiida.cmdline.commands.cmd_group import group_path_ls @pytest.fixture def setup_groups(aiida_profile_clean): """Setup some groups for testing.""" for label in ['a', 'a/b', 'a/c/d', 'a/c/e/g', 'a/f']: group, _ = orm.Group.objects.get_or_create(label) group.description = f'A description of {label}' orm.UpfFamily.objects.get_or_create('a/x') yield def test_with_no_opts(setup_groups): """Test ``verdi group path ls``""" cli_runner = CliRunner() result = cli_runner.invoke(group_path_ls) assert result.exit_code == 0, result.exception assert result.output == 'a\n' result = cli_runner.invoke(group_path_ls, ['a']) assert result.exit_code == 0, result.exception assert result.output == 'a/b\na/c\na/f\n' result = cli_runner.invoke(group_path_ls, ['a/c']) assert result.exit_code == 0, result.exception assert result.output == 'a/c/d\na/c/e\n' def test_recursive(setup_groups): """Test ``verdi group path ls --recursive``""" cli_runner = CliRunner() for tag in ['-R', '--recursive']: result = cli_runner.invoke(group_path_ls, [tag]) assert result.exit_code == 0, result.exception assert result.output == 'a\na/b\na/c\na/c/d\na/c/e\na/c/e/g\na/f\n' result = cli_runner.invoke(group_path_ls, [tag, 'a/c']) assert result.exit_code == 0, result.exception assert result.output == 'a/c/d\na/c/e\na/c/e/g\n' @pytest.mark.parametrize('tag', ['-l', '--long']) def test_long(setup_groups, tag): """Test ``verdi group path ls --long``""" cli_runner = CliRunner() result = cli_runner.invoke(group_path_ls, [tag]) assert result.exit_code == 0, result.exception assert result.output == dedent( """\ Path Sub-Groups ------ ------------ a 4 """ ) result = cli_runner.invoke(group_path_ls, [tag, '-d', 'a']) assert result.exit_code == 0, result.exception assert result.output == dedent( """\ Path Sub-Groups Description ------ ------------ -------------------- a/b 0 A description of a/b a/c 2 - a/f 0 A description of a/f """ ) result = cli_runner.invoke(group_path_ls, [tag, '-R']) assert result.exit_code == 0, result.exception assert result.output == dedent( """\ Path Sub-Groups ------- ------------ a 4 a/b 0 a/c 2 a/c/d 0 a/c/e 1 a/c/e/g 0 a/f 0 """ ) @pytest.mark.parametrize('tag', ['--no-virtual']) def test_groups_only(setup_groups, tag): """Test ``verdi group path ls --no-virtual``""" cli_runner = CliRunner() result = cli_runner.invoke(group_path_ls, [tag, '-l', '-R', '--with-description']) assert result.exit_code == 0, result.exception assert result.output == dedent( """\ Path Sub-Groups Description ------- ------------ ------------------------ a 4 A description of a a/b 0 A description of a/b a/c/d 0 A description of a/c/d a/c/e/g 0 A description of a/c/e/g a/f 0 A description of a/f """ )
33.6875
86
0.513451
true
true
1c3c1f372fd25f32ecd58709d57a52a7aaea2810
8,493
py
Python
preliminaries/filtering.py
Asichurter/APISeqFewShot
b4b7843da1f53cdc1d1711537c31305e7d5c6555
[ "MIT" ]
8
2020-05-14T19:29:41.000Z
2022-03-09T03:29:51.000Z
preliminaries/filtering.py
Asichurter/APISeqFewShot
b4b7843da1f53cdc1d1711537c31305e7d5c6555
[ "MIT" ]
null
null
null
preliminaries/filtering.py
Asichurter/APISeqFewShot
b4b7843da1f53cdc1d1711537c31305e7d5c6555
[ "MIT" ]
null
null
null
from sklearn.decomposition import PCA import matplotlib.pyplot as plt from sklearn.cluster import KMeans, AffinityPropagation from utils.color import getRandomColor from preliminaries.embedding import aggregateApiSequences, trainW2Vmodel from preliminaries.preprocessing import mappingApiNormalize, \ apiStat, removeApiRedundance, filterApiSequence, statApiFrequency from utils.file import loadJson, dumpJson from utils.display import printState base_path = 'D:/peimages/PEs/virushare_20/' path = base_path + 'jsons/' apiSetPath = base_path + 'api_set.json' reportPath = base_path + 'json_w_e_report.json' original_word2cluster_path = base_path + 'ApiClusterTable(ori).json' real_word2cluster_path = base_path + 'ApiClusterTable(subs).json' #-------------------------统计--------------------------------- # statApiFrequency(json_path=path, # is_class_dir=False, # threshold=None)#5e-3 #------------------------------------------------------------- #-------------------------过滤--------------------------------- # filterApiSequence(json_path=path, # filterd_apis=['NtOpenKeyEx', 'NtOpenDirectoryObject', 'SHGetFolderPathW', 'NtOpenProcess', 'FindWindowA', 'OutputDebugStringA', 'LoadResource', 'FindWindowExA', 'InternetReadFile', 'CopyFileExW', 'LoadStringA', 'LdrGetDllHandle', 'Thread32Next', 'NtProtectVirtualMemory', 'NtOpenKey', 'LdrUnloadDll', 'WriteConsoleW', 'NtCreateMutant', 'GetCursorPos', 'CryptDecrypt', 'NtSetInformationFile', 'FindResourceA', 'GetFileSizeEx', 'NtQueryInformationFile', 'NtMapViewOfSection', 'RegEnumKeyW', 'RegQueryValueExA', 'EnumWindows', 'DrawTextExW', 'CoInitializeEx', 'CoUninitialize', 'NtUnmapViewOfSection', 'CoCreateInstance', 'GetFileAttributesExW', 'RegSetValueExA', 'LoadStringW', 'GetVolumeNameForVolumeMountPointW', 'NtQuerySystemInformation', 'NtCreateSection', 'RegCreateKeyExA', 'SizeofResource', 'SetFilePointerEx', 'NtOpenMutant', 'RegEnumKeyExW', 'NtTerminateProcess', 'NtQueryAttributesFile', 'CreateToolhelp32Snapshot', 'FindWindowW', 'FindResourceExA', 'SetEndOfFile', 'RegEnumValueA', 'GetSystemInfo', 'NtDuplicateObject', 'RegEnumValueW', 'GetShortPathNameW', 'Process32FirstW', 'NtReadVirtualMemory', 'RegEnumKeyExA', 'GetSystemDirectoryA', 'SearchPathW', 'GetUserNameA', 'recvfrom', 'Module32NextW', 'FindResourceW', 'GetSystemWindowsDirectoryW', 'CreateDirectoryW', 'NtOpenSection', 'RegCreateKeyExW', 'NtEnumerateValueKey', 'SetFileAttributesW', 'CreateActCtxW', 'select', 'GetVolumePathNamesForVolumeNameW', 'GetTempPathW', 'StartServiceA', 'CreateProcessInternalW', 'CoGetClassObject', 'NtEnumerateKey', 'GetKeyboardState', 'RegDeleteValueA', 'SetFileTime', 'RegQueryInfoKeyW', 'CopyFileA', 'RegSetValueExW', 'CreateThread', 'IsDebuggerPresent', 'OleInitialize', 'NtResumeThread', 'GetFileInformationByHandleEx', 'GlobalMemoryStatus', 'GetSystemDirectoryW', 'OpenServiceA', 'OpenSCManagerA', 'GetTimeZoneInformation', 'LookupPrivilegeValueW', 'InternetSetOptionA', 'RegQueryInfoKeyA', 'SetWindowsHookExA', 'UnhookWindowsHookEx', 'NtSetValueKey', 'SetStdHandle', 'CryptAcquireContextW', 'NtCreateKey', 'CryptDecodeObjectEx', 'NtOpenThread', 'CreateDirectoryExW', 'SetUnhandledExceptionFilter', 'DrawTextExA', 'GetComputerNameA', 'RegDeleteValueW', 'FindWindowExW', 'GetDiskFreeSpaceExW', 'NtSuspendThread', 'DeviceIoControl', 'closesocket', 'UuidCreate', 'InternetCloseHandle', 'NtGetContextThread', 'CopyFileW', 'getaddrinfo', 'WSAStartup', 'socket', 'GetNativeSystemInfo', 'GetFileVersionInfoSizeW', 'ShellExecuteExW', 'GetFileVersionInfoW', 'SendNotifyMessageW', 'gethostbyname', 'SetFileInformationByHandle', 'ioctlsocket', 'GetAdaptersAddresses', 'InternetGetConnectedState', 'InternetQueryOptionA', 'InternetCrackUrlA', 'GlobalMemoryStatusEx', 'LookupAccountSidW', 'ControlService', 'connect', 'GetComputerNameW', 'GetFileInformationByHandle', 'Module32FirstW', 'setsockopt', 'InternetOpenA', 'CWindow_AddTimeoutCode', 'SHGetSpecialFolderLocation', 'WriteConsoleA', 'NtCreateThreadEx', 'GetFileVersionInfoSizeExW', 'GetFileVersionInfoExW', 'CoCreateInstanceEx', 'GetVolumePathNameW', 'GetUserNameW', 'CreateRemoteThread', 'OpenSCManagerW', 'OpenServiceW', 'InternetOpenW', 'SetWindowsHookExW', 'NtWriteVirtualMemory', 'MessageBoxTimeoutA', 'InternetCrackUrlW', 'InternetConnectW', 'HttpSendRequestW', 'HttpOpenRequestW', 'GetUserNameExA', 'CoInitializeSecurity', 'shutdown', 'HttpQueryInfoA', 'RegDeleteKeyA', 'RtlAddVectoredExceptionHandler', 'NtQueryFullAttributesFile', 'NtSetContextThread', 'CryptExportKey', 'WSASocketW', 'bind', 'GetBestInterfaceEx', 'RtlRemoveVectoredExceptionHandler', 'NtTerminateThread', 'GetDiskFreeSpaceW', 'CryptAcquireContextA', 'InternetOpenUrlA', 'ReadCabinetState', 'InternetConnectA', 'NtQueueApcThread', 'GetSystemWindowsDirectoryA', 'Thread32First', 'getsockname', 'RtlDecompressBuffer', 'HttpOpenRequestA', 'IWbemServices_ExecQuery', 'HttpSendRequestA', 'CertOpenStore', 'GetAdaptersInfo', 'InternetOpenUrlW', 'GetAddrInfoW', 'WSASocketA', 'MoveFileWithProgressW', 'GetUserNameExW', 'WSARecv', 'CDocument_write', 'WSASend', 'NtDeleteKey', 'InternetSetStatusCallback', 'sendto', 'URLDownloadToFileW', 'RegDeleteKeyW', 'RtlAddVectoredContinueHandler', 'NetShareEnum', 'RemoveDirectoryA', 'AssignProcessToJobObject', 'CreateServiceA', 'CertControlStore', 'listen', 'accept', 'CreateJobObjectW', 'DnsQuery_A', 'CIFrameElement_CreateElement', 'CryptEncrypt', 'RemoveDirectoryW', 'DeleteService', 'send', 'WSASendTo', 'SetInformationJobObject', 'ObtainUserAgentString', 'WSAConnect', 'StartServiceW', 'CImgElement_put_src', 'WSAAccept', 'NtDeleteValueKey', 'recv', 'COleScript_Compile', 'NetUserGetInfo', 'Math_random', 'CryptUnprotectData', 'CElement_put_innerHTML', 'DeleteUrlCacheEntryA', 'CryptProtectMemory', 'CryptGenKey', 'ActiveXObjectFncObj_Construct', 'CryptUnprotectMemory', 'IWbemServices_ExecMethod', 'CreateServiceW', '__anomaly__', 'NtQueryMultipleValueKey', 'RtlCreateUserThread', 'RtlCompressBuffer', 'NtSaveKey', 'SendNotifyMessageA', 'WSARecvFrom', 'DeleteUrlCacheEntryW', 'CScriptElement_put_src', 'EnumServicesStatusA', 'CryptProtectData', 'CertOpenSystemStoreA', 'NtLoadKey', 'PRF', 'NtDeleteFile', 'InternetGetConnectedStateExW', 'ExitWindowsEx', 'CHyperlink_SetUrlComponent', 'NetUserGetLocalGroups', 'NetGetJoinInformation', 'FindFirstFileExA', 'RegisterHotKey', 'system', 'InternetGetConnectedStateExA', 'CertCreateCertificateContext']) #------------------------------------------------------------- #-------------------------移除冗余--------------------------------- # removeApiRedundance(path, selected_apis=None) #------------------------------------------------------------- #-------------------------查看长度--------------------------------- apiStat(path=path, dump_apiset_path=apiSetPath, dump_report_path=reportPath, ratio_stairs=[100, 200, 500, 600, 1000, 2000, 3000, 5000, 7000, 10000], class_dir=False) # ------------------------------------------------------------- #-------------------------API聚类过滤--------------------------------- # 收集API集合 # printState('Collecting APIs...') # apiStat(path, # dump_apiset_path=apiSetPath, # class_dir=False) # # # 制作API名称到名称下标的映射,用于减少内存消耗 # api_set = loadJson(apiSetPath)['api_set'] # apiMap = {name:str(i) for i,name in enumerate(api_set)} # # # 使用映射替换数据集中的API名称 # printState('Mapping...') # mappingApiNormalize(path, mapping=apiMap) # # printState('Aggregating...') # seqs = aggregateApiSequences(path, is_class_dir=False) # # printState('Training Word2Vector') # matrix, word2idx = trainW2Vmodel(seqs, # size=32, # padding=False) # # plt.scatter(matrix[:,0], matrix[:,1]) # plt.show() # # # 聚类 # printState('Clustering...') # af = AffinityPropagation().fit(matrix) # # word2cluster = {} # for word, idx in word2idx.items(): # word2cluster[word] = str(af.labels_[idx] + 1) # 由于要给<PAD>留一个位置,因此类簇下标要加1 # # word2cluster_org = {} # for org_word, subs_word in apiMap.items(): # word2cluster_org[org_word] = word2cluster[subs_word] # # dumpJson(word2cluster, real_word2cluster_path) # dumpJson(word2cluster_org, original_word2cluster_path) # # printState('Mapping word to cluster index...') # mappingApiNormalize(path, # mapping=word2cluster) # # printState('Removing redundancy...') # removeApiRedundance(path,selected_apis=None) # # printState('Done') #-------------------------------------------------------------
82.456311
5,333
0.713176
from sklearn.decomposition import PCA import matplotlib.pyplot as plt from sklearn.cluster import KMeans, AffinityPropagation from utils.color import getRandomColor from preliminaries.embedding import aggregateApiSequences, trainW2Vmodel from preliminaries.preprocessing import mappingApiNormalize, \ apiStat, removeApiRedundance, filterApiSequence, statApiFrequency from utils.file import loadJson, dumpJson from utils.display import printState base_path = 'D:/peimages/PEs/virushare_20/' path = base_path + 'jsons/' apiSetPath = base_path + 'api_set.json' reportPath = base_path + 'json_w_e_report.json' original_word2cluster_path = base_path + 'ApiClusterTable(ori).json' real_word2cluster_path = base_path + 'ApiClusterTable(subs).json' apiStat(path=path, dump_apiset_path=apiSetPath, dump_report_path=reportPath, ratio_stairs=[100, 200, 500, 600, 1000, 2000, 3000, 5000, 7000, 10000], class_dir=False)
true
true
1c3c1f8189be70f87b6c864b7af1e8bb8ee5b5af
6,205
py
Python
sdk/python/pulumi_azure_native/operationalinsights/v20200801/linked_storage_account.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/operationalinsights/v20200801/linked_storage_account.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/operationalinsights/v20200801/linked_storage_account.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = ['LinkedStorageAccount'] class LinkedStorageAccount(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, data_source_type: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, storage_account_ids: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, workspace_name: Optional[pulumi.Input[str]] = None, __props__=None, __name__=None, __opts__=None): """ Linked storage accounts top level resource container. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] data_source_type: Linked storage accounts type. :param pulumi.Input[str] resource_group_name: The name of the resource group. The name is case insensitive. :param pulumi.Input[Sequence[pulumi.Input[str]]] storage_account_ids: Linked storage accounts resources ids. :param pulumi.Input[str] workspace_name: The name of the workspace. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['data_source_type'] = data_source_type if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['storage_account_ids'] = storage_account_ids if workspace_name is None and not opts.urn: raise TypeError("Missing required property 'workspace_name'") __props__['workspace_name'] = workspace_name __props__['name'] = None __props__['type'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:operationalinsights/v20200801:LinkedStorageAccount"), pulumi.Alias(type_="azure-native:operationalinsights:LinkedStorageAccount"), pulumi.Alias(type_="azure-nextgen:operationalinsights:LinkedStorageAccount"), pulumi.Alias(type_="azure-native:operationalinsights/latest:LinkedStorageAccount"), pulumi.Alias(type_="azure-nextgen:operationalinsights/latest:LinkedStorageAccount"), pulumi.Alias(type_="azure-native:operationalinsights/v20190801preview:LinkedStorageAccount"), pulumi.Alias(type_="azure-nextgen:operationalinsights/v20190801preview:LinkedStorageAccount"), pulumi.Alias(type_="azure-native:operationalinsights/v20200301preview:LinkedStorageAccount"), pulumi.Alias(type_="azure-nextgen:operationalinsights/v20200301preview:LinkedStorageAccount")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(LinkedStorageAccount, __self__).__init__( 'azure-native:operationalinsights/v20200801:LinkedStorageAccount', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'LinkedStorageAccount': """ Get an existing LinkedStorageAccount resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__["data_source_type"] = None __props__["name"] = None __props__["storage_account_ids"] = None __props__["type"] = None return LinkedStorageAccount(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="dataSourceType") def data_source_type(self) -> pulumi.Output[str]: """ Linked storage accounts type. """ return pulumi.get(self, "data_source_type") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ The name of the resource """ return pulumi.get(self, "name") @property @pulumi.getter(name="storageAccountIds") def storage_account_ids(self) -> pulumi.Output[Optional[Sequence[str]]]: """ Linked storage accounts resources ids. """ return pulumi.get(self, "storage_account_ids") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" """ return pulumi.get(self, "type") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
47.730769
843
0.677518
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = ['LinkedStorageAccount'] class LinkedStorageAccount(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, data_source_type: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, storage_account_ids: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, workspace_name: Optional[pulumi.Input[str]] = None, __props__=None, __name__=None, __opts__=None): if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['data_source_type'] = data_source_type if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['storage_account_ids'] = storage_account_ids if workspace_name is None and not opts.urn: raise TypeError("Missing required property 'workspace_name'") __props__['workspace_name'] = workspace_name __props__['name'] = None __props__['type'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:operationalinsights/v20200801:LinkedStorageAccount"), pulumi.Alias(type_="azure-native:operationalinsights:LinkedStorageAccount"), pulumi.Alias(type_="azure-nextgen:operationalinsights:LinkedStorageAccount"), pulumi.Alias(type_="azure-native:operationalinsights/latest:LinkedStorageAccount"), pulumi.Alias(type_="azure-nextgen:operationalinsights/latest:LinkedStorageAccount"), pulumi.Alias(type_="azure-native:operationalinsights/v20190801preview:LinkedStorageAccount"), pulumi.Alias(type_="azure-nextgen:operationalinsights/v20190801preview:LinkedStorageAccount"), pulumi.Alias(type_="azure-native:operationalinsights/v20200301preview:LinkedStorageAccount"), pulumi.Alias(type_="azure-nextgen:operationalinsights/v20200301preview:LinkedStorageAccount")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(LinkedStorageAccount, __self__).__init__( 'azure-native:operationalinsights/v20200801:LinkedStorageAccount', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'LinkedStorageAccount': opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__["data_source_type"] = None __props__["name"] = None __props__["storage_account_ids"] = None __props__["type"] = None return LinkedStorageAccount(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="dataSourceType") def data_source_type(self) -> pulumi.Output[str]: return pulumi.get(self, "data_source_type") @property @pulumi.getter def name(self) -> pulumi.Output[str]: return pulumi.get(self, "name") @property @pulumi.getter(name="storageAccountIds") def storage_account_ids(self) -> pulumi.Output[Optional[Sequence[str]]]: return pulumi.get(self, "storage_account_ids") @property @pulumi.getter def type(self) -> pulumi.Output[str]: return pulumi.get(self, "type") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
true
true
1c3c208bc3115e328bdbaa03eb1d900c68f5300d
5,072
py
Python
contrib/codeanalysis/src/python/pants/contrib/codeanalysis/tasks/extract_java.py
AllClearID/pants
c4fdf00a3bdf9f26f876e85c46909d0729f7132c
[ "Apache-2.0" ]
1
2018-12-10T21:31:02.000Z
2018-12-10T21:31:02.000Z
contrib/codeanalysis/src/python/pants/contrib/codeanalysis/tasks/extract_java.py
AllClearID/pants
c4fdf00a3bdf9f26f876e85c46909d0729f7132c
[ "Apache-2.0" ]
2
2016-10-13T21:37:42.000Z
2018-07-20T20:14:33.000Z
contrib/codeanalysis/src/python/pants/contrib/codeanalysis/tasks/extract_java.py
AllClearID/pants
c4fdf00a3bdf9f26f876e85c46909d0729f7132c
[ "Apache-2.0" ]
1
2018-03-08T22:21:44.000Z
2018-03-08T22:21:44.000Z
# coding=utf-8 # Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pants.backend.jvm.subsystems.shader import Shader from pants.backend.jvm.tasks.jvm_tool_task_mixin import JvmToolTaskMixin from pants.base.exceptions import TaskError from pants.contrib.codeanalysis.tasks.indexable_java_targets import IndexableJavaTargets # Kythe requires various system properties to be set (sigh). So we can't use nailgun. class ExtractJava(JvmToolTaskMixin): cache_target_dirs = True _KYTHE_JAVA_EXTRACTOR_MAIN = 'com.google.devtools.kythe.extractors.java.standalone.Javac8Wrapper' @classmethod def subsystem_dependencies(cls): return super(ExtractJava, cls).subsystem_dependencies() + (IndexableJavaTargets,) @classmethod def implementation_version(cls): # Bump this version to invalidate all past artifacts generated by this task. return super(ExtractJava, cls).implementation_version() + [('KytheExtract', 7), ] @classmethod def product_types(cls): # TODO: Support indexpack files? return ['kindex_files'] @classmethod def prepare(cls, options, round_manager): super(ExtractJava, cls).prepare(options, round_manager) round_manager.require_data('zinc_args') @classmethod def register_options(cls, register): super(ExtractJava, cls).register_options(register) cls.register_jvm_tool(register, 'kythe-java-extractor', custom_rules=[ # These need to remain unshaded so that Kythe can interact with the # javac embedded in its jar. Shader.exclude_package('com.sun', recursive=True), ], main=cls._KYTHE_JAVA_EXTRACTOR_MAIN) def execute(self): indexable_targets = IndexableJavaTargets.global_instance().get(self.context) targets_to_zinc_args = self.context.products.get_data('zinc_args') with self.invalidated(indexable_targets, invalidate_dependents=True) as invalidation_check: extractor_cp = self.tool_classpath('kythe-java-extractor') for vt in invalidation_check.invalid_vts: self.context.log.info('Kythe extracting from {}\n'.format(vt.target.address.spec)) javac_args = self._get_javac_args_from_zinc_args(targets_to_zinc_args[vt.target]) # Kythe jars embed a copy of Java 9's com.sun.tools.javac and javax.tools, for use on JDK8. # We must put these jars on the bootclasspath, ahead of any others, to ensure that we load # the Java 9 versions, and not the runtime's versions. jvm_options = ['-Xbootclasspath/p:{}'.format(':'.join(extractor_cp))] jvm_options.extend(self.get_options().jvm_options) jvm_options.extend([ '-DKYTHE_CORPUS={}'.format(vt.target.address.spec), '-DKYTHE_ROOT_DIRECTORY={}'.format(vt.target.target_base), '-DKYTHE_OUTPUT_DIRECTORY={}'.format(vt.results_dir) ]) result = self.dist.execute_java( classpath=extractor_cp, main=self._KYTHE_JAVA_EXTRACTOR_MAIN, jvm_options=jvm_options, args=javac_args, workunit_name='kythe-extract') if result != 0: raise TaskError('java {main} ... exited non-zero ({result})'.format( main=self._KYTHE_JAVA_EXTRACTOR_MAIN, result=result)) for vt in invalidation_check.all_vts: created_files = os.listdir(vt.results_dir) if len(created_files) != 1: raise TaskError('Expected a single .kindex file in {}. Got: {}.'.format( vt.results_dir, ', '.join(created_files) if created_files else 'none')) kindex_files = self.context.products.get_data('kindex_files', dict) kindex_files[vt.target] = os.path.join(vt.results_dir, created_files[0]) @staticmethod def _get_javac_args_from_zinc_args(zinc_args): javac_args = [] i = iter(zinc_args) arg = next(i, None) output_dir = None while arg is not None: arg = arg.strip() if arg in ['-d', '-cp', '-classpath']: # These are passed through from zinc to javac. javac_args.append(arg) javac_args.append(next(i)) if arg == '-d': output_dir = javac_args[-1] elif arg.startswith('-C'): javac_args.append(arg[2:]) elif arg.endswith('.java'): javac_args.append(arg) arg = next(i, None) # Strip output dir from classpaths. If we don't then javac will read annotation definitions # from there instead of from the source files, which will cause the vnames to reflect the .class # file instead of the .java file. if output_dir: for i, a in enumerate(javac_args): if a in ['-cp', '-classpath']: javac_args[i + 1] = ':'.join([p for p in javac_args[i + 1].split(':') if p != output_dir]) return javac_args
43.724138
100
0.680402
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pants.backend.jvm.subsystems.shader import Shader from pants.backend.jvm.tasks.jvm_tool_task_mixin import JvmToolTaskMixin from pants.base.exceptions import TaskError from pants.contrib.codeanalysis.tasks.indexable_java_targets import IndexableJavaTargets class ExtractJava(JvmToolTaskMixin): cache_target_dirs = True _KYTHE_JAVA_EXTRACTOR_MAIN = 'com.google.devtools.kythe.extractors.java.standalone.Javac8Wrapper' @classmethod def subsystem_dependencies(cls): return super(ExtractJava, cls).subsystem_dependencies() + (IndexableJavaTargets,) @classmethod def implementation_version(cls): # Bump this version to invalidate all past artifacts generated by this task. return super(ExtractJava, cls).implementation_version() + [('KytheExtract', 7), ] @classmethod def product_types(cls): # TODO: Support indexpack files? return ['kindex_files'] @classmethod def prepare(cls, options, round_manager): super(ExtractJava, cls).prepare(options, round_manager) round_manager.require_data('zinc_args') @classmethod def register_options(cls, register): super(ExtractJava, cls).register_options(register) cls.register_jvm_tool(register, 'kythe-java-extractor', custom_rules=[ # These need to remain unshaded so that Kythe can interact with the # javac embedded in its jar. Shader.exclude_package('com.sun', recursive=True), ], main=cls._KYTHE_JAVA_EXTRACTOR_MAIN) def execute(self): indexable_targets = IndexableJavaTargets.global_instance().get(self.context) targets_to_zinc_args = self.context.products.get_data('zinc_args') with self.invalidated(indexable_targets, invalidate_dependents=True) as invalidation_check: extractor_cp = self.tool_classpath('kythe-java-extractor') for vt in invalidation_check.invalid_vts: self.context.log.info('Kythe extracting from {}\n'.format(vt.target.address.spec)) javac_args = self._get_javac_args_from_zinc_args(targets_to_zinc_args[vt.target]) # Kythe jars embed a copy of Java 9's com.sun.tools.javac and javax.tools, for use on JDK8. jvm_options = ['-Xbootclasspath/p:{}'.format(':'.join(extractor_cp))] jvm_options.extend(self.get_options().jvm_options) jvm_options.extend([ '-DKYTHE_CORPUS={}'.format(vt.target.address.spec), '-DKYTHE_ROOT_DIRECTORY={}'.format(vt.target.target_base), '-DKYTHE_OUTPUT_DIRECTORY={}'.format(vt.results_dir) ]) result = self.dist.execute_java( classpath=extractor_cp, main=self._KYTHE_JAVA_EXTRACTOR_MAIN, jvm_options=jvm_options, args=javac_args, workunit_name='kythe-extract') if result != 0: raise TaskError('java {main} ... exited non-zero ({result})'.format( main=self._KYTHE_JAVA_EXTRACTOR_MAIN, result=result)) for vt in invalidation_check.all_vts: created_files = os.listdir(vt.results_dir) if len(created_files) != 1: raise TaskError('Expected a single .kindex file in {}. Got: {}.'.format( vt.results_dir, ', '.join(created_files) if created_files else 'none')) kindex_files = self.context.products.get_data('kindex_files', dict) kindex_files[vt.target] = os.path.join(vt.results_dir, created_files[0]) @staticmethod def _get_javac_args_from_zinc_args(zinc_args): javac_args = [] i = iter(zinc_args) arg = next(i, None) output_dir = None while arg is not None: arg = arg.strip() if arg in ['-d', '-cp', '-classpath']: # These are passed through from zinc to javac. javac_args.append(arg) javac_args.append(next(i)) if arg == '-d': output_dir = javac_args[-1] elif arg.startswith('-C'): javac_args.append(arg[2:]) elif arg.endswith('.java'): javac_args.append(arg) arg = next(i, None) # Strip output dir from classpaths. If we don't then javac will read annotation definitions if output_dir: for i, a in enumerate(javac_args): if a in ['-cp', '-classpath']: javac_args[i + 1] = ':'.join([p for p in javac_args[i + 1].split(':') if p != output_dir]) return javac_args
true
true
1c3c212e7a2dc8acb2f8c2353668660dbf5ad18d
11,367
py
Python
google/cloud/vision_v1p3beta1/types/text_annotation.py
dylancaponi/python-vision
f94fb5b03bf8932e75967249292d23fed2ae2213
[ "Apache-2.0" ]
null
null
null
google/cloud/vision_v1p3beta1/types/text_annotation.py
dylancaponi/python-vision
f94fb5b03bf8932e75967249292d23fed2ae2213
[ "Apache-2.0" ]
1
2021-02-23T12:41:14.000Z
2021-02-23T12:41:14.000Z
google/cloud/vision_v1p3beta1/types/text_annotation.py
dylancaponi/python-vision
f94fb5b03bf8932e75967249292d23fed2ae2213
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import proto # type: ignore from google.cloud.vision_v1p3beta1.types import geometry __protobuf__ = proto.module( package="google.cloud.vision.v1p3beta1", manifest={"TextAnnotation", "Page", "Block", "Paragraph", "Word", "Symbol",}, ) class TextAnnotation(proto.Message): r"""TextAnnotation contains a structured representation of OCR extracted text. The hierarchy of an OCR extracted text structure is like this: TextAnnotation -> Page -> Block -> Paragraph -> Word -> Symbol Each structural component, starting from Page, may further have their own properties. Properties describe detected languages, breaks etc.. Please refer to the [TextAnnotation.TextProperty][google.cloud.vision.v1p3beta1.TextAnnotation.TextProperty] message definition below for more detail. Attributes: pages (Sequence[~.text_annotation.Page]): List of pages detected by OCR. text (str): UTF-8 text detected on the pages. """ class DetectedLanguage(proto.Message): r"""Detected language for a structural component. Attributes: language_code (str): The BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. confidence (float): Confidence of detected language. Range [0, 1]. """ language_code = proto.Field(proto.STRING, number=1) confidence = proto.Field(proto.FLOAT, number=2) class DetectedBreak(proto.Message): r"""Detected start or end of a structural component. Attributes: type_ (~.text_annotation.TextAnnotation.DetectedBreak.BreakType): Detected break type. is_prefix (bool): True if break prepends the element. """ class BreakType(proto.Enum): r"""Enum to denote the type of break found. New line, space etc.""" UNKNOWN = 0 SPACE = 1 SURE_SPACE = 2 EOL_SURE_SPACE = 3 HYPHEN = 4 LINE_BREAK = 5 type_ = proto.Field( proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", ) is_prefix = proto.Field(proto.BOOL, number=2) class TextProperty(proto.Message): r"""Additional information detected on the structural component. Attributes: detected_languages (Sequence[~.text_annotation.TextAnnotation.DetectedLanguage]): A list of detected languages together with confidence. detected_break (~.text_annotation.TextAnnotation.DetectedBreak): Detected start or end of a text segment. """ detected_languages = proto.RepeatedField( proto.MESSAGE, number=1, message="TextAnnotation.DetectedLanguage", ) detected_break = proto.Field( proto.MESSAGE, number=2, message="TextAnnotation.DetectedBreak", ) pages = proto.RepeatedField(proto.MESSAGE, number=1, message="Page",) text = proto.Field(proto.STRING, number=2) class Page(proto.Message): r"""Detected page from OCR. Attributes: property (~.text_annotation.TextAnnotation.TextProperty): Additional information detected on the page. width (int): Page width. For PDFs the unit is points. For images (including TIFFs) the unit is pixels. height (int): Page height. For PDFs the unit is points. For images (including TIFFs) the unit is pixels. blocks (Sequence[~.text_annotation.Block]): List of blocks of text, images etc on this page. confidence (float): Confidence of the OCR results on the page. Range [0, 1]. """ property = proto.Field( proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, ) width = proto.Field(proto.INT32, number=2) height = proto.Field(proto.INT32, number=3) blocks = proto.RepeatedField(proto.MESSAGE, number=4, message="Block",) confidence = proto.Field(proto.FLOAT, number=5) class Block(proto.Message): r"""Logical element on the page. Attributes: property (~.text_annotation.TextAnnotation.TextProperty): Additional information detected for the block. bounding_box (~.geometry.BoundingPoly): The bounding box for the block. The vertices are in the order of top-left, top-right, bottom-right, bottom-left. When a rotation of the bounding box is detected the rotation is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - when the text is horizontal it might look like: :: 0----1 | | 3----2 - when it's rotated 180 degrees around the top-left corner it becomes: :: 2----3 | | 1----0 and the vertice order will still be (0, 1, 2, 3). paragraphs (Sequence[~.text_annotation.Paragraph]): List of paragraphs in this block (if this blocks is of type text). block_type (~.text_annotation.Block.BlockType): Detected block type (text, image etc) for this block. confidence (float): Confidence of the OCR results on the block. Range [0, 1]. """ class BlockType(proto.Enum): r"""Type of a block (text, image etc) as identified by OCR.""" UNKNOWN = 0 TEXT = 1 TABLE = 2 PICTURE = 3 RULER = 4 BARCODE = 5 property = proto.Field( proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, ) bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) paragraphs = proto.RepeatedField(proto.MESSAGE, number=3, message="Paragraph",) block_type = proto.Field(proto.ENUM, number=4, enum=BlockType,) confidence = proto.Field(proto.FLOAT, number=5) class Paragraph(proto.Message): r"""Structural unit of text representing a number of words in certain order. Attributes: property (~.text_annotation.TextAnnotation.TextProperty): Additional information detected for the paragraph. bounding_box (~.geometry.BoundingPoly): The bounding box for the paragraph. The vertices are in the order of top-left, top-right, bottom-right, bottom-left. When a rotation of the bounding box is detected the rotation is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - when the text is horizontal it might look like: 0----1 \| \| 3----2 - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertice order will still be (0, 1, 2, 3). words (Sequence[~.text_annotation.Word]): List of words in this paragraph. confidence (float): Confidence of the OCR results for the paragraph. Range [0, 1]. """ property = proto.Field( proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, ) bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) words = proto.RepeatedField(proto.MESSAGE, number=3, message="Word",) confidence = proto.Field(proto.FLOAT, number=4) class Word(proto.Message): r"""A word representation. Attributes: property (~.text_annotation.TextAnnotation.TextProperty): Additional information detected for the word. bounding_box (~.geometry.BoundingPoly): The bounding box for the word. The vertices are in the order of top-left, top-right, bottom-right, bottom-left. When a rotation of the bounding box is detected the rotation is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - when the text is horizontal it might look like: 0----1 \| \| 3----2 - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertice order will still be (0, 1, 2, 3). symbols (Sequence[~.text_annotation.Symbol]): List of symbols in the word. The order of the symbols follows the natural reading order. confidence (float): Confidence of the OCR results for the word. Range [0, 1]. """ property = proto.Field( proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, ) bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) symbols = proto.RepeatedField(proto.MESSAGE, number=3, message="Symbol",) confidence = proto.Field(proto.FLOAT, number=4) class Symbol(proto.Message): r"""A single symbol representation. Attributes: property (~.text_annotation.TextAnnotation.TextProperty): Additional information detected for the symbol. bounding_box (~.geometry.BoundingPoly): The bounding box for the symbol. The vertices are in the order of top-left, top-right, bottom-right, bottom-left. When a rotation of the bounding box is detected the rotation is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: - when the text is horizontal it might look like: 0----1 \| \| 3----2 - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertice order will still be (0, 1, 2, 3). text (str): The actual UTF-8 representation of the symbol. confidence (float): Confidence of the OCR results for the symbol. Range [0, 1]. """ property = proto.Field( proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, ) bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) text = proto.Field(proto.STRING, number=3) confidence = proto.Field(proto.FLOAT, number=4) __all__ = tuple(sorted(__protobuf__.manifest))
35.411215
93
0.6218
import proto from google.cloud.vision_v1p3beta1.types import geometry __protobuf__ = proto.module( package="google.cloud.vision.v1p3beta1", manifest={"TextAnnotation", "Page", "Block", "Paragraph", "Word", "Symbol",}, ) class TextAnnotation(proto.Message): class DetectedLanguage(proto.Message): language_code = proto.Field(proto.STRING, number=1) confidence = proto.Field(proto.FLOAT, number=2) class DetectedBreak(proto.Message): class BreakType(proto.Enum): UNKNOWN = 0 SPACE = 1 SURE_SPACE = 2 EOL_SURE_SPACE = 3 HYPHEN = 4 LINE_BREAK = 5 type_ = proto.Field( proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", ) is_prefix = proto.Field(proto.BOOL, number=2) class TextProperty(proto.Message): detected_languages = proto.RepeatedField( proto.MESSAGE, number=1, message="TextAnnotation.DetectedLanguage", ) detected_break = proto.Field( proto.MESSAGE, number=2, message="TextAnnotation.DetectedBreak", ) pages = proto.RepeatedField(proto.MESSAGE, number=1, message="Page",) text = proto.Field(proto.STRING, number=2) class Page(proto.Message): property = proto.Field( proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, ) width = proto.Field(proto.INT32, number=2) height = proto.Field(proto.INT32, number=3) blocks = proto.RepeatedField(proto.MESSAGE, number=4, message="Block",) confidence = proto.Field(proto.FLOAT, number=5) class Block(proto.Message): class BlockType(proto.Enum): UNKNOWN = 0 TEXT = 1 TABLE = 2 PICTURE = 3 RULER = 4 BARCODE = 5 property = proto.Field( proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, ) bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) paragraphs = proto.RepeatedField(proto.MESSAGE, number=3, message="Paragraph",) block_type = proto.Field(proto.ENUM, number=4, enum=BlockType,) confidence = proto.Field(proto.FLOAT, number=5) class Paragraph(proto.Message): property = proto.Field( proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, ) bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) words = proto.RepeatedField(proto.MESSAGE, number=3, message="Word",) confidence = proto.Field(proto.FLOAT, number=4) class Word(proto.Message): property = proto.Field( proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, ) bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) symbols = proto.RepeatedField(proto.MESSAGE, number=3, message="Symbol",) confidence = proto.Field(proto.FLOAT, number=4) class Symbol(proto.Message): property = proto.Field( proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, ) bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) text = proto.Field(proto.STRING, number=3) confidence = proto.Field(proto.FLOAT, number=4) __all__ = tuple(sorted(__protobuf__.manifest))
true
true
1c3c21d0c4a699da716e72bd35a8ee5be65f2683
1,015
py
Python
hackathon/column0/problem_17_1_score_combinations.py
abdurahmanadilovic/elements-of-programming-interviews
14d05935aa901f453ea2086e449b670e993a4c83
[ "MIT" ]
null
null
null
hackathon/column0/problem_17_1_score_combinations.py
abdurahmanadilovic/elements-of-programming-interviews
14d05935aa901f453ea2086e449b670e993a4c83
[ "MIT" ]
null
null
null
hackathon/column0/problem_17_1_score_combinations.py
abdurahmanadilovic/elements-of-programming-interviews
14d05935aa901f453ea2086e449b670e993a4c83
[ "MIT" ]
null
null
null
def solution(score): # solutions = {} # solve(0, score, [], solutions) # return len(solutions.keys()) return solve2(score) def solve(current_score, target_score, path, solutions): if current_score > target_score: return 0 elif current_score == target_score: path_sorted = str(sorted(path)) if path_sorted not in solutions: solutions[path_sorted] = 1 print(path) return 1 else: combinations = solve(current_score + 7, target_score, path[:] + [7], solutions) combinations += solve(current_score + 3, target_score, path[:] + [3], solutions) combinations += solve(current_score + 2, target_score, path[:] + [2], solutions) return combinations def solve2(score): solutions = [0] * (score + 1) solutions[0] = 1 for single_score in [7, 3, 2]: for index in range(single_score, score + 1): solutions[index] += solutions[index - single_score] return solutions[score]
30.757576
88
0.618719
def solution(score): return solve2(score) def solve(current_score, target_score, path, solutions): if current_score > target_score: return 0 elif current_score == target_score: path_sorted = str(sorted(path)) if path_sorted not in solutions: solutions[path_sorted] = 1 print(path) return 1 else: combinations = solve(current_score + 7, target_score, path[:] + [7], solutions) combinations += solve(current_score + 3, target_score, path[:] + [3], solutions) combinations += solve(current_score + 2, target_score, path[:] + [2], solutions) return combinations def solve2(score): solutions = [0] * (score + 1) solutions[0] = 1 for single_score in [7, 3, 2]: for index in range(single_score, score + 1): solutions[index] += solutions[index - single_score] return solutions[score]
true
true
1c3c223ac0a6341c7f6c17c1b2f4f4166e4fb6d7
4,636
py
Python
examples/motor-imagery/plot_single.py
gabelstein/parRiemann
466c20570c797f588cbe58f2f93d32180ea1e533
[ "BSD-3-Clause" ]
null
null
null
examples/motor-imagery/plot_single.py
gabelstein/parRiemann
466c20570c797f588cbe58f2f93d32180ea1e533
[ "BSD-3-Clause" ]
null
null
null
examples/motor-imagery/plot_single.py
gabelstein/parRiemann
466c20570c797f588cbe58f2f93d32180ea1e533
[ "BSD-3-Clause" ]
null
null
null
""" ==================================================================== Motor imagery classification ==================================================================== Classify Motor imagery data with Riemannian Geometry. """ # generic import import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt # mne import from mne import Epochs, pick_types, events_from_annotations from mne.io import concatenate_raws from mne.io.edf import read_raw_edf from mne.datasets import eegbci from mne.decoding import CSP # parriemann import from parriemann.classification import MDM, TSclassifier from parriemann.estimation import Covariances # sklearn imports from sklearn.model_selection import cross_val_score, KFold from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression ############################################################################### # Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = 1., 2. event_id = dict(hands=2, feet=3) subject = 7 runs = [6, 10, 14] # motor imagery: hands vs feet raw_files = [ read_raw_edf(f, preload=True) for f in eegbci.load_data(subject, runs) ] raw = concatenate_raws(raw_files) picks = pick_types( raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads') # subsample elecs picks = picks[::2] # Apply band-pass filter raw.filter(7., 35., method='iir', picks=picks) events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3)) # Read epochs (train will be done only between 1 and 2s) # Testing will be done with a running classifier epochs = Epochs( raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=None, preload=True, verbose=False) labels = epochs.events[:, -1] - 2 # cross validation cv = KFold(n_splits=10, random_state=42) # get epochs epochs_data_train = 1e6 * epochs.get_data() # compute covariance matrices cov_data_train = Covariances().transform(epochs_data_train) ############################################################################### # Classification with Minimum distance to mean mdm = MDM(metric=dict(mean='riemann', distance='riemann')) # Use scikit-learn Pipeline with cross_val_score function scores = cross_val_score(mdm, cov_data_train, labels, cv=cv, n_jobs=1) # Printing the results class_balance = np.mean(labels == labels[0]) class_balance = max(class_balance, 1. - class_balance) print("MDM Classification accuracy: %f / Chance level: %f" % (np.mean(scores), class_balance)) ############################################################################### # Classification with Tangent Space Logistic Regression clf = TSclassifier() # Use scikit-learn Pipeline with cross_val_score function scores = cross_val_score(clf, cov_data_train, labels, cv=cv, n_jobs=1) # Printing the results class_balance = np.mean(labels == labels[0]) class_balance = max(class_balance, 1. - class_balance) print("Tangent space Classification accuracy: %f / Chance level: %f" % (np.mean(scores), class_balance)) ############################################################################### # Classification with CSP + logistic regression # Assemble a classifier lr = LogisticRegression() csp = CSP(n_components=4, reg='ledoit_wolf', log=True) clf = Pipeline([('CSP', csp), ('LogisticRegression', lr)]) scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1) # Printing the results class_balance = np.mean(labels == labels[0]) class_balance = max(class_balance, 1. - class_balance) print("CSP + LDA Classification accuracy: %f / Chance level: %f" % (np.mean(scores), class_balance)) ############################################################################### # Display MDM centroid mdm = MDM() mdm.fit(cov_data_train, labels) fig, axes = plt.subplots(1, 2, figsize=[8, 4]) ch_names = [ch.replace('.', '') for ch in epochs.ch_names] df = pd.DataFrame(data=mdm.covmeans_[0], index=ch_names, columns=ch_names) g = sns.heatmap( df, ax=axes[0], square=True, cbar=False, xticklabels=2, yticklabels=2) g.set_title('Mean covariance - hands') df = pd.DataFrame(data=mdm.covmeans_[1], index=ch_names, columns=ch_names) g = sns.heatmap( df, ax=axes[1], square=True, cbar=False, xticklabels=2, yticklabels=2) plt.xticks(rotation='vertical') plt.yticks(rotation='horizontal') g.set_title('Mean covariance - feets') # dirty fix plt.sca(axes[0]) plt.xticks(rotation='vertical') plt.yticks(rotation='horizontal') plt.show()
32.194444
79
0.648619
import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt from mne import Epochs, pick_types, events_from_annotations from mne.io import concatenate_raws from mne.io.edf import read_raw_edf from mne.datasets import eegbci from mne.decoding import CSP from parriemann.classification import MDM, TSclassifier from parriemann.estimation import Covariances from sklearn.model_selection import cross_val_score, KFold from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression
true
true
1c3c22847d924bebf8aacb779617861b86eb5501
5,442
py
Python
zhengma/source.py
smaji-org/cjkv_info_sample
12440b938a58b2384a3c9d11c0897dd4101d6fe6
[ "MIT" ]
null
null
null
zhengma/source.py
smaji-org/cjkv_info_sample
12440b938a58b2384a3c9d11c0897dd4101d6fe6
[ "MIT" ]
null
null
null
zhengma/source.py
smaji-org/cjkv_info_sample
12440b938a58b2384a3c9d11c0897dd4101d6fe6
[ "MIT" ]
null
null
null
#!/usr/bin/env python2 # -*- coding:utf-8 -*- info= { "China": { "G0": "GB 2312-80", "G1": "GB 12345-90", "G3": "GB 7589-87 traditional form", "G5": "GB 7590-87 traditional form", "G7": "Modern Chinese general character chart (Simplified Chinese: 现代汉语通用字表)", "G8": "GB8565-88", "GCE": "National Academy for Educational Research", "GE": "GB16500-95", "GFC": "Modern Chinese Standard Dictionary (现代汉语规范词典)", "GGFZ": "General Chinese Standard Dictionary (通用规范汉字字典)", "GH": "GB/T 15564-1995", "GHZ": "Hanyu Da Zidian", "GHZR": "Hanyu Da Zidian(second edition) (汉语大字典(第二版))", "GK": "GB 12052-89", "GKJ": "Terms in Sciences and Technologies (科技用字) approved by the China National Committee for Terms in Sciences and Technologies (CNCTST)", "GKX": "Kangxi Dictionary", "GLK": "龍龕手鑑", "GT": "Standard Telegraph Codebook (revised), 1983", "GZFY": "Dictionary of Chinese Dialects (汉语方言大辞典)", "GS": "Singapore Chinese characters", "G4K": "Siku Quanshu", "GBK": "Encyclopedia of China", "GCH": "Cihai", "GCY": "Ciyuan", "GFZ": "Founder Press System", "GHC": "Hanyu Da Cidian", "GHF": "漢文佛典疑難俗字彙釋與研究", "GCYY": "Chinese Academy of Surveying and Mapping ideographs", "GGH": "Old Chinese Dictionary (古代汉语词典)", "GJZ": "Commercial Press ideographs", "GXC": "Xiandai Hanyu Cidian", "GZJW": "Collections of Bronze Inscriptions from Yin and Zhou Dynasties (殷周金文集成引得)", "GIDC": "ID System of the Ministry of Public Security of China", "GZH": "Zhonghua Zihai", "GDZ": "Geology Press ideographs", "GRM": "People's Daily ideographs", "GWZ": "Hanyu Da Cidian Press ideographs", "GXH": "Xinhua Zidian", "GLGYJ": "Zhuang Liao Songs Research (壮族嘹歌研究)", "GOCD": "Oxford English-Chinese Chinese-English Dictionary (牛津英汉汉英词典)", "GPGLG": "Zhuang Folk Song Culture Series - Pingguo County Liao Songs (壮族民歌文化丛书・平果嘹歌)", "GXHZ": "Xinhua Big Dictionary (新华大字典)", "GZ": "Ancient Zhuang Character Dictionary (古壮字字典)", "GZYS": "Chinese Ancient Ethnic Characters Research (中国民族古文字研究)" }, "Hong Kong": { "H": "Hong Kong Supplementary Character Set, 2008", "HB0": "Computer Chinese Glyph and Character Code Mapping Table, Technical Report C-26 (電腦用中文字型與字碼對照表, 技術通報C-26)", "HB1": "Big-5, Level 1", "HB2": "Big-5, Level 2", "HD": "Hong Kong Supplementary Character Set, 2016" }, "Japan": { "J0": "JIS X 0208-1990", "J1": "JIS X 0212-1990", "J13": "JIS X 0213:2004 level-3 characters replacing J1 characters", "J13A": "JIS X 0213:2004 level-3 character addendum from JIS X 0213:2000 level-3 replacing J1 character", "J14": "JIS X 0213:2004 level-4 characters replacing J1 characters", "J3": "JIS X 0213:2004 Level 3", "J3A": "JIS X 0213:2004 Level 3 addendum", "J4": "JIS X 0213:2004 Level 4", "JARIB": "ARIB STD-B24", "JMJ": "Character Information Development and Maintenance Project for e-Government \"MojiJoho-Kiban Project\" (文字情報基盤整備事業)", "JH": "Hanyo-Denshi Program (汎用電子情報交換環境整備プログラム)", "JA": "Japanese IT Vendors Contemporary Ideographs, 1993", "JA3": "JIS X 0213:2004 level-3 characters replacing JA characters", "JA4": "JIS X 0213:2004 level-4 characters replacing JA characters", "JK": "Japanese Kokuji Collection" }, "Macau": { "MAC": "Macao Information System Character Set (澳門資訊系統字集)" }, "North Korea": { "KP0": "KPS 9566-97", "KP1": "KPS 10721-2000" }, "South Korea": { "K0": "KS C 5601-87 (now KS X 1001:2004)", "K1": "KS C 5657-91 (now KS X 1002:2004)", "K2": "PKS C 5700-1:1994", "K3": "PKS C 5700-2:1994", "K4": "PKS 5700-3:1998", "K6": "KS X 1027-5:2014", "K5": "Korean IRG Hanja Character Set", "KC": "Korean History On-Line (한국 역사 정보 통합 시스템)" }, "Taiwan": { "T1": "CNS 11643-1992 plane 1", "T2": "CNS 11643-1992 plane 2", "T3": "CNS 11643-1992 plane 3", "T4": "CNS 11643-1992 plane 4", "T5": "CNS 11643-1992 plane 5", "T6": "CNS 11643-1992 plane 6", "T7": "CNS 11643-1992 plane 7", "TB": "CNS 11643-1992 plane 11", "TC": "CNS 11643-1992 plane 12", "TD": "CNS 11643-1992 plane 13", "TE": "CNS 11643-1992 plane 14", "TF": "CNS 11643-1992 plane 15", "TA": "Chemical Nomenclature: 4th Edition (化學命名原則(第四版))", "T13": "TCA-CNS 11643 19th plane (pending new version)" }, "Vietnam": { "V0": "TCVN 5773-1993", "V1": "TCVN 6056:1995", "V2": "VHN 01-1998", "V3": "VHN 02-1998", "V4": "Dictionary on Nom (Từ điển chữ Nôm)\nDictionary on Nom of Tay ethnic (Từ điển chữ Nôm Tày)\nLookup Table for Nom in the South (Bảng tra chữ Nôm miền Nam)", "VU": "Vietnamese horizontal extensions" }, "United Kingdom": { "UK": "IRG N2107R2" }, "N/A": { "UTC": "UTC sources", "UCI": "UTC sources", "SAT": "SAT Daizōkyō Text Database" } } rev= {} for region in info: for sub in info[region]: rev[sub]= region
41.227273
170
0.571849
info= { "China": { "G0": "GB 2312-80", "G1": "GB 12345-90", "G3": "GB 7589-87 traditional form", "G5": "GB 7590-87 traditional form", "G7": "Modern Chinese general character chart (Simplified Chinese: 现代汉语通用字表)", "G8": "GB8565-88", "GCE": "National Academy for Educational Research", "GE": "GB16500-95", "GFC": "Modern Chinese Standard Dictionary (现代汉语规范词典)", "GGFZ": "General Chinese Standard Dictionary (通用规范汉字字典)", "GH": "GB/T 15564-1995", "GHZ": "Hanyu Da Zidian", "GHZR": "Hanyu Da Zidian(second edition) (汉语大字典(第二版))", "GK": "GB 12052-89", "GKJ": "Terms in Sciences and Technologies (科技用字) approved by the China National Committee for Terms in Sciences and Technologies (CNCTST)", "GKX": "Kangxi Dictionary", "GLK": "龍龕手鑑", "GT": "Standard Telegraph Codebook (revised), 1983", "GZFY": "Dictionary of Chinese Dialects (汉语方言大辞典)", "GS": "Singapore Chinese characters", "G4K": "Siku Quanshu", "GBK": "Encyclopedia of China", "GCH": "Cihai", "GCY": "Ciyuan", "GFZ": "Founder Press System", "GHC": "Hanyu Da Cidian", "GHF": "漢文佛典疑難俗字彙釋與研究", "GCYY": "Chinese Academy of Surveying and Mapping ideographs", "GGH": "Old Chinese Dictionary (古代汉语词典)", "GJZ": "Commercial Press ideographs", "GXC": "Xiandai Hanyu Cidian", "GZJW": "Collections of Bronze Inscriptions from Yin and Zhou Dynasties (殷周金文集成引得)", "GIDC": "ID System of the Ministry of Public Security of China", "GZH": "Zhonghua Zihai", "GDZ": "Geology Press ideographs", "GRM": "People's Daily ideographs", "GWZ": "Hanyu Da Cidian Press ideographs", "GXH": "Xinhua Zidian", "GLGYJ": "Zhuang Liao Songs Research (壮族嘹歌研究)", "GOCD": "Oxford English-Chinese Chinese-English Dictionary (牛津英汉汉英词典)", "GPGLG": "Zhuang Folk Song Culture Series - Pingguo County Liao Songs (壮族民歌文化丛书・平果嘹歌)", "GXHZ": "Xinhua Big Dictionary (新华大字典)", "GZ": "Ancient Zhuang Character Dictionary (古壮字字典)", "GZYS": "Chinese Ancient Ethnic Characters Research (中国民族古文字研究)" }, "Hong Kong": { "H": "Hong Kong Supplementary Character Set, 2008", "HB0": "Computer Chinese Glyph and Character Code Mapping Table, Technical Report C-26 (電腦用中文字型與字碼對照表, 技術通報C-26)", "HB1": "Big-5, Level 1", "HB2": "Big-5, Level 2", "HD": "Hong Kong Supplementary Character Set, 2016" }, "Japan": { "J0": "JIS X 0208-1990", "J1": "JIS X 0212-1990", "J13": "JIS X 0213:2004 level-3 characters replacing J1 characters", "J13A": "JIS X 0213:2004 level-3 character addendum from JIS X 0213:2000 level-3 replacing J1 character", "J14": "JIS X 0213:2004 level-4 characters replacing J1 characters", "J3": "JIS X 0213:2004 Level 3", "J3A": "JIS X 0213:2004 Level 3 addendum", "J4": "JIS X 0213:2004 Level 4", "JARIB": "ARIB STD-B24", "JMJ": "Character Information Development and Maintenance Project for e-Government \"MojiJoho-Kiban Project\" (文字情報基盤整備事業)", "JH": "Hanyo-Denshi Program (汎用電子情報交換環境整備プログラム)", "JA": "Japanese IT Vendors Contemporary Ideographs, 1993", "JA3": "JIS X 0213:2004 level-3 characters replacing JA characters", "JA4": "JIS X 0213:2004 level-4 characters replacing JA characters", "JK": "Japanese Kokuji Collection" }, "Macau": { "MAC": "Macao Information System Character Set (澳門資訊系統字集)" }, "North Korea": { "KP0": "KPS 9566-97", "KP1": "KPS 10721-2000" }, "South Korea": { "K0": "KS C 5601-87 (now KS X 1001:2004)", "K1": "KS C 5657-91 (now KS X 1002:2004)", "K2": "PKS C 5700-1:1994", "K3": "PKS C 5700-2:1994", "K4": "PKS 5700-3:1998", "K6": "KS X 1027-5:2014", "K5": "Korean IRG Hanja Character Set", "KC": "Korean History On-Line (한국 역사 정보 통합 시스템)" }, "Taiwan": { "T1": "CNS 11643-1992 plane 1", "T2": "CNS 11643-1992 plane 2", "T3": "CNS 11643-1992 plane 3", "T4": "CNS 11643-1992 plane 4", "T5": "CNS 11643-1992 plane 5", "T6": "CNS 11643-1992 plane 6", "T7": "CNS 11643-1992 plane 7", "TB": "CNS 11643-1992 plane 11", "TC": "CNS 11643-1992 plane 12", "TD": "CNS 11643-1992 plane 13", "TE": "CNS 11643-1992 plane 14", "TF": "CNS 11643-1992 plane 15", "TA": "Chemical Nomenclature: 4th Edition (化學命名原則(第四版))", "T13": "TCA-CNS 11643 19th plane (pending new version)" }, "Vietnam": { "V0": "TCVN 5773-1993", "V1": "TCVN 6056:1995", "V2": "VHN 01-1998", "V3": "VHN 02-1998", "V4": "Dictionary on Nom (Từ điển chữ Nôm)\nDictionary on Nom of Tay ethnic (Từ điển chữ Nôm Tày)\nLookup Table for Nom in the South (Bảng tra chữ Nôm miền Nam)", "VU": "Vietnamese horizontal extensions" }, "United Kingdom": { "UK": "IRG N2107R2" }, "N/A": { "UTC": "UTC sources", "UCI": "UTC sources", "SAT": "SAT Daizōkyō Text Database" } } rev= {} for region in info: for sub in info[region]: rev[sub]= region
true
true
1c3c23c2c041ff29f3353f05b8b75d5b32b84180
176
py
Python
kub/services/archive/cdk/python/sample-app/app.py
randyzingle/tools
8ef80f15665d2c3f58a419c79eec049ade7a4d40
[ "Apache-2.0" ]
null
null
null
kub/services/archive/cdk/python/sample-app/app.py
randyzingle/tools
8ef80f15665d2c3f58a419c79eec049ade7a4d40
[ "Apache-2.0" ]
1
2021-06-23T20:28:53.000Z
2021-06-23T20:28:53.000Z
kub/services/archive/cdk/python/sample-app/app.py
randyzingle/tools
8ef80f15665d2c3f58a419c79eec049ade7a4d40
[ "Apache-2.0" ]
2
2018-09-21T01:01:07.000Z
2020-03-06T20:21:49.000Z
#!/usr/bin/env python3 from aws_cdk import core from hello.hello_stack import MyStack app = core.App() MyStack(app, "baldur-cdk", env={'region': 'us-east-1'}) app.synth()
14.666667
55
0.698864
from aws_cdk import core from hello.hello_stack import MyStack app = core.App() MyStack(app, "baldur-cdk", env={'region': 'us-east-1'}) app.synth()
true
true
1c3c24037502dd9466339d6e17744833d41471d2
2,517
py
Python
lab/refactoring-pep8/docstrings_blank_lines.py
Andre-Williams22/SPD-2.31-Testing-and-Architecture
a28abb56c7b0c920144867f5aa138f70aae65260
[ "MIT" ]
null
null
null
lab/refactoring-pep8/docstrings_blank_lines.py
Andre-Williams22/SPD-2.31-Testing-and-Architecture
a28abb56c7b0c920144867f5aa138f70aae65260
[ "MIT" ]
null
null
null
lab/refactoring-pep8/docstrings_blank_lines.py
Andre-Williams22/SPD-2.31-Testing-and-Architecture
a28abb56c7b0c920144867f5aa138f70aae65260
[ "MIT" ]
null
null
null
# by Kami Bigdely # Docstrings and blank lines class OnBoardTemperatureSensor: '''Calculates Temperature Sensor''' VOLTAGE_TO_TEMP_FACTOR = 5.6 def __init__(self): ''' Initializes variables ''' pass def read_voltage(self): ''' Initializes variables ''' return 2.7 def get_temperature(self): ''' Initializes variables ''' return self.read_voltage() * OnBoardTemperatureSensor.VOLTAGE_TO_TEMP_FACTOR # [celcius] class CarbonMonoxideSensor: '''Calculates the Carbon Monoxide ''' VOLTAGE_TO_CO_FACTOR = 0.048 def __init__(self, temperature_sensor): ''' Initializes variables ''' self.on_board_temp_sensor = temperature_sensor if not self.on_board_temp_sensor: self.on_board_temp_sensor = OnBoardTemperatureSensor() def get_carbon_monoxide_level(self): ''' Initializes variables ''' sensor_voltage = self.read_sensor_voltage() self.carbon_monoxide = CarbonMonoxideSensor.convert_voltage_to_carbon_monoxide_level( sensor_voltage, self.on_board_temp_sensor.get_temperature()) return self.carbon_monoxide def read_sensor_voltage(self): ''' Initializes variables ''' # In real life, it should read from hardware. return 2.3 def convert_voltage_to_carbon_monoxide_level(voltage, temperature): ''' Initializes variables ''' return voltage * CarbonMonoxideSensor.VOLTAGE_TO_CO_FACTOR * temperature class DisplayUnit: ''' Visualizes a unit''' def __init__(self): ''' Initializes variables ''' self.string = '' def display(self, msg): ''' Initializes variables ''' print(msg) class CarbonMonoxideDevice(): ''' A device capable of Carbon Monoxide''' def __init__(self, co_sensor, display_unit): ''' Initializes variables ''' self.carbonMonoxideSensor = co_sensor self.display_unit = display_unit def display(self): ''' Initializes variables ''' msg = 'Carbon Monoxide Level is : ' + str(self.carbonMonoxideSensor.get_carbon_monoxide_level()) self.display_unit.display(msg) if __name__ == "__main__": temp_sensor = OnBoardTemperatureSensor() co_sensor = CarbonMonoxideSensor(temp_sensor) display_unit = DisplayUnit() co_device = CarbonMonoxideDevice(co_sensor, display_unit) co_device.display()
34.958333
104
0.658323
class OnBoardTemperatureSensor: VOLTAGE_TO_TEMP_FACTOR = 5.6 def __init__(self): pass def read_voltage(self): return 2.7 def get_temperature(self): return self.read_voltage() * OnBoardTemperatureSensor.VOLTAGE_TO_TEMP_FACTOR class CarbonMonoxideSensor: VOLTAGE_TO_CO_FACTOR = 0.048 def __init__(self, temperature_sensor): self.on_board_temp_sensor = temperature_sensor if not self.on_board_temp_sensor: self.on_board_temp_sensor = OnBoardTemperatureSensor() def get_carbon_monoxide_level(self): sensor_voltage = self.read_sensor_voltage() self.carbon_monoxide = CarbonMonoxideSensor.convert_voltage_to_carbon_monoxide_level( sensor_voltage, self.on_board_temp_sensor.get_temperature()) return self.carbon_monoxide def read_sensor_voltage(self): return 2.3 def convert_voltage_to_carbon_monoxide_level(voltage, temperature): return voltage * CarbonMonoxideSensor.VOLTAGE_TO_CO_FACTOR * temperature class DisplayUnit: def __init__(self): self.string = '' def display(self, msg): print(msg) class CarbonMonoxideDevice(): def __init__(self, co_sensor, display_unit): self.carbonMonoxideSensor = co_sensor self.display_unit = display_unit def display(self): msg = 'Carbon Monoxide Level is : ' + str(self.carbonMonoxideSensor.get_carbon_monoxide_level()) self.display_unit.display(msg) if __name__ == "__main__": temp_sensor = OnBoardTemperatureSensor() co_sensor = CarbonMonoxideSensor(temp_sensor) display_unit = DisplayUnit() co_device = CarbonMonoxideDevice(co_sensor, display_unit) co_device.display()
true
true
1c3c255519b39d2e52290b2a72f7aeb0882989ba
2,277
py
Python
backend/module_options_test_29674/urls.py
crowdbotics-apps/module-options-test-29674
914d0b52507564bcd382e973bd31c879f3059d79
[ "FTL", "AML", "RSA-MD" ]
null
null
null
backend/module_options_test_29674/urls.py
crowdbotics-apps/module-options-test-29674
914d0b52507564bcd382e973bd31c879f3059d79
[ "FTL", "AML", "RSA-MD" ]
19
2021-08-15T17:17:39.000Z
2021-12-12T17:09:48.000Z
backend/module_options_test_29674/urls.py
crowdbotics-apps/module-options-test-29674
914d0b52507564bcd382e973bd31c879f3059d79
[ "FTL", "AML", "RSA-MD" ]
null
null
null
"""module_options_test_29674 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include, re_path from django.views.generic.base import TemplateView from allauth.account.views import confirm_email from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi urlpatterns = [ path("", include("home.urls")), path("accounts/", include("allauth.urls")), path("modules/", include("modules.urls")), path("api/v1/", include("home.api.v1.urls")), path("admin/", admin.site.urls), path("users/", include("users.urls", namespace="users")), path("rest-auth/", include("rest_auth.urls")), # Override email confirm to use allauth's HTML view instead of rest_auth's API view path("rest-auth/registration/account-confirm-email/<str:key>/", confirm_email), path("rest-auth/registration/", include("rest_auth.registration.urls")), ] admin.site.site_header = "module options test" admin.site.site_title = "module options test Admin Portal" admin.site.index_title = "module options test Admin" # swagger api_info = openapi.Info( title="module options test API", default_version="v1", description="API documentation for module options test App", ) schema_view = get_schema_view( api_info, public=True, permission_classes=(permissions.IsAuthenticated,), ) urlpatterns += [ path("api-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="api_docs") ] urlpatterns += [path("", TemplateView.as_view(template_name='index.html'))] urlpatterns += [re_path(r"^(?:.*)/?$", TemplateView.as_view(template_name='index.html'))]
36.142857
87
0.716293
from django.contrib import admin from django.urls import path, include, re_path from django.views.generic.base import TemplateView from allauth.account.views import confirm_email from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi urlpatterns = [ path("", include("home.urls")), path("accounts/", include("allauth.urls")), path("modules/", include("modules.urls")), path("api/v1/", include("home.api.v1.urls")), path("admin/", admin.site.urls), path("users/", include("users.urls", namespace="users")), path("rest-auth/", include("rest_auth.urls")), path("rest-auth/registration/account-confirm-email/<str:key>/", confirm_email), path("rest-auth/registration/", include("rest_auth.registration.urls")), ] admin.site.site_header = "module options test" admin.site.site_title = "module options test Admin Portal" admin.site.index_title = "module options test Admin" api_info = openapi.Info( title="module options test API", default_version="v1", description="API documentation for module options test App", ) schema_view = get_schema_view( api_info, public=True, permission_classes=(permissions.IsAuthenticated,), ) urlpatterns += [ path("api-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="api_docs") ] urlpatterns += [path("", TemplateView.as_view(template_name='index.html'))] urlpatterns += [re_path(r"^(?:.*)/?$", TemplateView.as_view(template_name='index.html'))]
true
true
1c3c258d6a6997ded70db7b88526e0f209e43b1c
812
py
Python
google-cloud-sdk/lib/surface/genomics/referencesets/__init__.py
bopopescu/searchparty
afdc2805cb1b77bd5ac9fdd1a76217f4841f0ea6
[ "Apache-2.0" ]
1
2017-11-29T18:52:27.000Z
2017-11-29T18:52:27.000Z
google-cloud-sdk/lib/surface/genomics/referencesets/__init__.py
bopopescu/searchparty
afdc2805cb1b77bd5ac9fdd1a76217f4841f0ea6
[ "Apache-2.0" ]
null
null
null
google-cloud-sdk/lib/surface/genomics/referencesets/__init__.py
bopopescu/searchparty
afdc2805cb1b77bd5ac9fdd1a76217f4841f0ea6
[ "Apache-2.0" ]
3
2017-07-27T18:44:13.000Z
2020-07-25T17:48:53.000Z
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Genomics reference sets sub-group.""" from googlecloudsdk.calliope import base class ReferenceSets(base.Group): """Commands for Genomics reference sets. Commands to describe and list reference sets. """
32.48
74
0.759852
from googlecloudsdk.calliope import base class ReferenceSets(base.Group):
true
true
1c3c26a85503f2e2bc5ed297f4de94cbd014dbfe
163
py
Python
stravapy/resources/segment_efforts.py
JoshGuarino/stravapy
b7cb404137535f2ccda2fa03b9ba65fc6d4e289d
[ "MIT" ]
null
null
null
stravapy/resources/segment_efforts.py
JoshGuarino/stravapy
b7cb404137535f2ccda2fa03b9ba65fc6d4e289d
[ "MIT" ]
null
null
null
stravapy/resources/segment_efforts.py
JoshGuarino/stravapy
b7cb404137535f2ccda2fa03b9ba65fc6d4e289d
[ "MIT" ]
null
null
null
from request import Request class SegmentEfforts(object): def get_efforts_by_segment_id(): return def get_segment_effort_by_id(): return
18.111111
36
0.711656
from request import Request class SegmentEfforts(object): def get_efforts_by_segment_id(): return def get_segment_effort_by_id(): return
true
true
1c3c26d50ae1aefb8f8a05348b29b560a04e3f0d
2,253
py
Python
tests/models/symbol/iscsi_negotiation_defaults_test.py
NetApp/santricity-webapi-pythonsdk
1d3df4a00561192f4cdcdd1890f4d27547ed2de2
[ "BSD-3-Clause-Clear" ]
5
2016-08-23T17:52:22.000Z
2019-05-16T08:45:30.000Z
tests/models/symbol/iscsi_negotiation_defaults_test.py
NetApp/santricity-webapi-pythonsdk
1d3df4a00561192f4cdcdd1890f4d27547ed2de2
[ "BSD-3-Clause-Clear" ]
2
2016-11-10T05:30:21.000Z
2019-04-05T15:03:37.000Z
tests/models/symbol/iscsi_negotiation_defaults_test.py
NetApp/santricity-webapi-pythonsdk
1d3df4a00561192f4cdcdd1890f4d27547ed2de2
[ "BSD-3-Clause-Clear" ]
7
2016-08-25T16:11:44.000Z
2021-02-22T05:31:25.000Z
#!/usr/bin/env python # coding: utf-8 """ The Clear BSD License Copyright (c) – 2016, NetApp, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) 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 NetApp, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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. """ import unittest from netapp.santricity.models.symbol.iscsi_negotiation_defaults import IscsiNegotiationDefaults class IscsiNegotiationDefaultsTest(unittest.TestCase): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ # Try instantiating the model def test_iscsi_negotiation_defaults(self): iscsi_negotiation_defaults_obj = IscsiNegotiationDefaults() self.assertNotEqual(iscsi_negotiation_defaults_obj, None)
59.289474
845
0.780737
import unittest from netapp.santricity.models.symbol.iscsi_negotiation_defaults import IscsiNegotiationDefaults class IscsiNegotiationDefaultsTest(unittest.TestCase): def test_iscsi_negotiation_defaults(self): iscsi_negotiation_defaults_obj = IscsiNegotiationDefaults() self.assertNotEqual(iscsi_negotiation_defaults_obj, None)
true
true
1c3c2736c10a8be6fba2336f8ba8f09bf734aabf
7,051
py
Python
ctfcli/__main__.py
mister-hai/sandboxy
861fc4eb37bb37db10e0123150f587c997b146e3
[ "MIT" ]
3
2021-09-14T04:35:42.000Z
2021-10-13T20:43:55.000Z
ctfcli/__main__.py
mister-hai/sandboxy
861fc4eb37bb37db10e0123150f587c997b146e3
[ "MIT" ]
null
null
null
ctfcli/__main__.py
mister-hai/sandboxy
861fc4eb37bb37db10e0123150f587c997b146e3
[ "MIT" ]
null
null
null
import os,sys,fire sys.path.insert(0, os.path.abspath('.')) #from ctfcli.utils.config import Config from pathlib import Path from ctfcli.utils.utils import errorlogger, yellowboldprint,greenprint,redprint from ctfcli.utils.config import Config from ctfcli.linkage import SandBoxyCTFdLinkage from ctfcli.core.gitrepo import SandboxyGitRepository ############################################################################### from ctfcli.utils.utils import DEBUG ############################################################################### class Ctfcli(): ''' Proper Usage is as follows THIS TOOL SHOULD BE ALONGSIDE the challenges repository folder folder subfolder_challenges masterlist.yaml subfolder_category subfolder_ctfcli __main__.py FIRST RUN, If you have not modified the repository this is not necessary! This will generate a Masterlist.yaml file that contains the contents of the repository for loading into the program >>> host@server$> python ./ctfcli/ ctfcli ctfdrepo init you should provide token and url when running the tool, it will store token only for a limited time. This is intentional and will not be changed This tool is capable of getting its own tokens given an administrative username and password for SINGLE operations, with NO authentication persistance: Replace <URL> with your CTFd website url Replace <TOKEN> with your CTFd website token >>> host@server$> python ./ctfcli/ ctfcli --ctfdurl <URL> --ctfdtoken <TOKEN> for multiple operations, WITH authentication persistance: This configuration will be able to obtain tokens via CLI >>> host@server$> python ./ctfcli/ ctfcli --ctfdurl <URL> --adminusername moop --adminpassword password To sync repository contents to CTFd Server, >>> host@server$> python ./ctfcli/ ctfcli syncrepository Not supplying a password/username, or token, will attempt to read auth information already in the config./cfg file You can obtain a auth token from the "settings" page in the "admin panel" This will initialize the repository, from there, you can either: Pull a remote repository you have to create a new masterlist after this That will be covered further down. >>> host@server$> ctfd.py gitops createremoterepo https://REMOTE_REPO_URL.git Generating a completion script and adding it to ~/.bashrc >>> host@server$>python ./ctfcli/ ctfcli -- --completion > ~/.ctfcli-completion >>> host@server$> echo "source ~/.ctfcli-completion" >> ~/.bashrc To generate a completion script for the Fish shell. (fish is nice but incompatible with bash scripts so far as I know so start.sh wont work) >>> -- --completion fish If the commands available in the Fire CLI change, you'll have to regenerate the completion script and source it again. / NOT IMPLEMENTED YET / IF YOU ARE MOVING YOUR INSTALLATION AFTER USING THE PACKER/UNPACKER IN START.SH, PERFORM THE FOLLOWING ACTIONS/COMMANDS >>> host@server$>python ./ctfcli/ ctfcli check_install / NOT IMPLEMENTED YET / ''' def __init__(self): # modify the structure of the program here by reassigning classes self._setenv() # process config file # bring in config functions self.config = Config(self.configfile) ctfdrepo = SandBoxyCTFdLinkage(self._challengesfolder, self.masterlist) # load config file ctfdrepo._initconfig(self.config) # challenge templates, change this to use your own with a randomizer self.TEMPLATESDIR = Path(self._toolfolder , "ctfcli", "templates") self.ctfdrepo = ctfdrepo # create git repository try: # we do this last so we can add all the created files to the git repo # this is the git backend, operate this seperately self.gitops = SandboxyGitRepository(self._reporoot) #self.gitops.createprojectrepo() except Exception: errorlogger("[-] Git Repository Creation Failed, check the logfile") def _setenv(self): """ Handles environment switching from being a standlone module to being a submodule """ PWD = Path(os.path.realpath(".")) #PWD_LIST = os.listdir(PWD) # if whatever not in PWD_LIST: # dosomethingdrastic(fuckitup) # # this must be alongside the challenges folder if being used by itself # Master values # alter these accordingly self._toolfolder = Path(os.path.dirname(__file__)) greenprint(f"[+] Tool folder Located at {self._toolfolder}") if DEBUG == True: # set project root to simulate ctfcli being one conteXt higher os.environ["PROJECT_ROOT"] = str(self._toolfolder.parent) PROJECT_ROOT = os.getenv('PROJECT_ROOT') self.root = PROJECT_ROOT if __name__ == "__main__": # TODO: make function to check if they put it next to # an actual repository fitting the spec try: # check if alongside challenges folder, # i.e. individual tool usage onelevelup = self._toolfolder.parent oneleveluplistdir = os.listdir(onelevelup) if ('challenges' in oneleveluplistdir): if os.path.isdir(oneleveluplistdir.get('challenges')): yellowboldprint("[+] Challenge Folder Found, presuming to be repository location") self._challengesfolder = os.path.join(onelevelup, "challenges") self._reporoot = onelevelup else: yellowboldprint("[!] Challenge folder not found!") if PROJECT_ROOT != None: yellowboldprint(f"[+] Project root env var set as {PROJECT_ROOT}") self._reporoot = Path(PROJECT_ROOT,"data","CTFd") except Exception: errorlogger("[-] Error, cannot find repository! ") else: from __main__ import PROJECT_ROOT self._reporoot = Path(PROJECT_ROOT,"data","CTFd") os.environ["REPOROOT"] = str(self._reporoot) self._challengesfolder = Path(self._reporoot, "challenges") self.masterlist = Path(self._reporoot, "masterlist.yaml") self.configfile = Path(PROJECT_ROOT, "config.cfg") yellowboldprint(f'[+] Repository root ENV variable is {os.getenv("REPOROOT")}') yellowboldprint(f'[+] Challenge root is {self._challengesfolder}') # this code is inactive currently def main(): fire.Fire(Ctfcli) if __name__ == "__main__": main() #fire.Fire(Ctfcli)
44.910828
111
0.621756
import os,sys,fire sys.path.insert(0, os.path.abspath('.')) from pathlib import Path from ctfcli.utils.utils import errorlogger, yellowboldprint,greenprint,redprint from ctfcli.utils.config import Config from ctfcli.linkage import SandBoxyCTFdLinkage from ctfcli.core.gitrepo import SandboxyGitRepository
true
true
1c3c27aa684ac4e9f43471853a9978214cef8589
5,259
py
Python
examples/ssd_mobilenet2/train.py
dodler/torchcv
10fd69bbb9180e399d93ee5c70abd5072401ea84
[ "MIT" ]
null
null
null
examples/ssd_mobilenet2/train.py
dodler/torchcv
10fd69bbb9180e399d93ee5c70abd5072401ea84
[ "MIT" ]
null
null
null
examples/ssd_mobilenet2/train.py
dodler/torchcv
10fd69bbb9180e399d93ee5c70abd5072401ea84
[ "MIT" ]
null
null
null
from __future__ import print_function import argparse import os import random import torch import torch.backends.cudnn as cudnn import torch.optim as optim import torchvision.transforms as transforms from torchcv.datasets import ListDataset from torchcv.loss import SSDLoss from torchcv.models.mobilenetv2.net import SSD300MobNet2 from torchcv.models.ssd import SSDBoxCoder from torchcv.transforms import resize, random_flip, random_paste, random_crop, random_distort LIST_FILE = '/home/lyan/Documents/torchcv/torchcv/datasets/uvb/uvb_train.txt' IMGS_ROOT = '/home/lyan/Documents/sample_uvb/all_imgs' NUM_CLASSES = 6 + 1 # ex 6+1, +1 is for background DEVICE='cpu' BATCH_SIZE = 1 NUM_WORKERS = 2 parser = argparse.ArgumentParser(description='PyTorch SSD Training') parser.add_argument('--lr', default=1e-4, type=float, help='learning rate') parser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint') parser.add_argument('--model', default='/home/lyan/Documents/torchcv/weights/fpnssd512_20_trained.pth', type=str, help='initialized model path') # parser.add_argument('--model', default='./examples/ssd/model/ssd512_vgg16.pth', type=str, help='initialized model path') parser.add_argument('--checkpoint', default='checkpoint/mobilenet2.pth', type=str, help='checkpoint path') args = parser.parse_args() # Model print('==> Building model..') net = SSD300MobNet2(num_classes=NUM_CLASSES) net.to(DEVICE) best_loss = float('inf') # best test loss start_epoch = 0 # start from epoch 0 or last epoch if args.resume: print('==> Resuming from checkpoint..') checkpoint = torch.load(args.checkpoint) net.load_state_dict(checkpoint['net']) best_loss = checkpoint['loss'] start_epoch = checkpoint['epoch'] # Dataset print('==> Preparing dataset..') box_coder = SSDBoxCoder(net) img_size = 300 def transform_train(img, boxes, labels): img = random_distort(img) if random.random() < 0.5: img, boxes = random_paste(img, boxes, max_ratio=4, fill=(123, 116, 103)) img, boxes, labels = random_crop(img, boxes, labels) img, boxes = resize(img, boxes, size=(img_size, img_size), random_interpolation=True) img, boxes = random_flip(img, boxes) img = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) ])(img) boxes, labels = box_coder.encode(boxes, labels) return img, boxes, labels trainset = ListDataset(root=IMGS_ROOT, list_file=[LIST_FILE], transform=transform_train) def transform_test(img, boxes, labels): img, boxes = resize(img, boxes, size=(img_size, img_size)) img = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) ])(img) boxes, labels = box_coder.encode(boxes, labels) return img, boxes, labels testset = ListDataset(root=IMGS_ROOT, list_file=LIST_FILE, transform=transform_test) trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=NUM_WORKERS) testloader = torch.utils.data.DataLoader(testset, batch_size=BATCH_SIZE, shuffle=False, num_workers=NUM_WORKERS) cudnn.benchmark = True criterion = SSDLoss(num_classes=NUM_CLASSES) optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=1e-4) # Training def train(epoch): print('\nEpoch: %d' % epoch) net.train() train_loss = 0 for batch_idx, (inputs, loc_targets, cls_targets) in enumerate(trainloader): inputs = inputs.to(DEVICE) loc_targets = loc_targets.to(DEVICE) cls_targets = cls_targets.to(DEVICE) optimizer.zero_grad() loc_preds, cls_preds = net(inputs) loss = criterion(loc_preds, loc_targets, cls_preds, cls_targets) loss.backward() optimizer.step() train_loss += loss.item() print('train_loss: %.3f | avg_loss: %.3f [%d/%d]' % (loss.item(), train_loss / (batch_idx + 1), batch_idx + 1, len(trainloader))) # Test def test(epoch): print('\nTest') net.eval() test_loss = 0 for batch_idx, (inputs, loc_targets, cls_targets) in enumerate(testloader): inputs = inputs.to(DEVICE) loc_targets = loc_targets.to(DEVICE) cls_targets = cls_targets.to(DEVICE) loc_preds, cls_preds = net(inputs) loss = criterion(loc_preds, loc_targets, cls_preds, cls_targets) test_loss += loss.item() print('test_loss: %.3f | avg_loss: %.3f [%d/%d]' % (loss.item(), test_loss / (batch_idx + 1), batch_idx + 1, len(testloader))) # Save checkpoint global best_loss test_loss /= len(testloader) if test_loss < best_loss: print('Saving..') state = { 'net': net.state_dict(), 'loss': test_loss, 'epoch': epoch, } if not os.path.isdir(os.path.dirname(args.checkpoint)): os.mkdir(os.path.dirname(args.checkpoint)) torch.save(state, args.checkpoint) best_loss = test_loss for epoch in range(start_epoch, start_epoch + 200): train(epoch) test(epoch)
34.598684
122
0.678076
from __future__ import print_function import argparse import os import random import torch import torch.backends.cudnn as cudnn import torch.optim as optim import torchvision.transforms as transforms from torchcv.datasets import ListDataset from torchcv.loss import SSDLoss from torchcv.models.mobilenetv2.net import SSD300MobNet2 from torchcv.models.ssd import SSDBoxCoder from torchcv.transforms import resize, random_flip, random_paste, random_crop, random_distort LIST_FILE = '/home/lyan/Documents/torchcv/torchcv/datasets/uvb/uvb_train.txt' IMGS_ROOT = '/home/lyan/Documents/sample_uvb/all_imgs' NUM_CLASSES = 6 + 1 DEVICE='cpu' BATCH_SIZE = 1 NUM_WORKERS = 2 parser = argparse.ArgumentParser(description='PyTorch SSD Training') parser.add_argument('--lr', default=1e-4, type=float, help='learning rate') parser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint') parser.add_argument('--model', default='/home/lyan/Documents/torchcv/weights/fpnssd512_20_trained.pth', type=str, help='initialized model path') parser.add_argument('--checkpoint', default='checkpoint/mobilenet2.pth', type=str, help='checkpoint path') args = parser.parse_args() print('==> Building model..') net = SSD300MobNet2(num_classes=NUM_CLASSES) net.to(DEVICE) best_loss = float('inf') start_epoch = 0 if args.resume: print('==> Resuming from checkpoint..') checkpoint = torch.load(args.checkpoint) net.load_state_dict(checkpoint['net']) best_loss = checkpoint['loss'] start_epoch = checkpoint['epoch'] print('==> Preparing dataset..') box_coder = SSDBoxCoder(net) img_size = 300 def transform_train(img, boxes, labels): img = random_distort(img) if random.random() < 0.5: img, boxes = random_paste(img, boxes, max_ratio=4, fill=(123, 116, 103)) img, boxes, labels = random_crop(img, boxes, labels) img, boxes = resize(img, boxes, size=(img_size, img_size), random_interpolation=True) img, boxes = random_flip(img, boxes) img = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) ])(img) boxes, labels = box_coder.encode(boxes, labels) return img, boxes, labels trainset = ListDataset(root=IMGS_ROOT, list_file=[LIST_FILE], transform=transform_train) def transform_test(img, boxes, labels): img, boxes = resize(img, boxes, size=(img_size, img_size)) img = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) ])(img) boxes, labels = box_coder.encode(boxes, labels) return img, boxes, labels testset = ListDataset(root=IMGS_ROOT, list_file=LIST_FILE, transform=transform_test) trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=NUM_WORKERS) testloader = torch.utils.data.DataLoader(testset, batch_size=BATCH_SIZE, shuffle=False, num_workers=NUM_WORKERS) cudnn.benchmark = True criterion = SSDLoss(num_classes=NUM_CLASSES) optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=1e-4) def train(epoch): print('\nEpoch: %d' % epoch) net.train() train_loss = 0 for batch_idx, (inputs, loc_targets, cls_targets) in enumerate(trainloader): inputs = inputs.to(DEVICE) loc_targets = loc_targets.to(DEVICE) cls_targets = cls_targets.to(DEVICE) optimizer.zero_grad() loc_preds, cls_preds = net(inputs) loss = criterion(loc_preds, loc_targets, cls_preds, cls_targets) loss.backward() optimizer.step() train_loss += loss.item() print('train_loss: %.3f | avg_loss: %.3f [%d/%d]' % (loss.item(), train_loss / (batch_idx + 1), batch_idx + 1, len(trainloader))) def test(epoch): print('\nTest') net.eval() test_loss = 0 for batch_idx, (inputs, loc_targets, cls_targets) in enumerate(testloader): inputs = inputs.to(DEVICE) loc_targets = loc_targets.to(DEVICE) cls_targets = cls_targets.to(DEVICE) loc_preds, cls_preds = net(inputs) loss = criterion(loc_preds, loc_targets, cls_preds, cls_targets) test_loss += loss.item() print('test_loss: %.3f | avg_loss: %.3f [%d/%d]' % (loss.item(), test_loss / (batch_idx + 1), batch_idx + 1, len(testloader))) global best_loss test_loss /= len(testloader) if test_loss < best_loss: print('Saving..') state = { 'net': net.state_dict(), 'loss': test_loss, 'epoch': epoch, } if not os.path.isdir(os.path.dirname(args.checkpoint)): os.mkdir(os.path.dirname(args.checkpoint)) torch.save(state, args.checkpoint) best_loss = test_loss for epoch in range(start_epoch, start_epoch + 200): train(epoch) test(epoch)
true
true
1c3c286951a9a0c7728cd4978c2d0791a490927a
1,402
py
Python
examples/applications/clustering/kmeans.py
shelleyyyyu/sentence-transformers
f004fba1dc23bbbe3caebd044748cbea3b2257e2
[ "Apache-2.0" ]
1
2021-09-20T14:12:36.000Z
2021-09-20T14:12:36.000Z
examples/applications/clustering/kmeans.py
shelleyyyyu/sentence-transformers
f004fba1dc23bbbe3caebd044748cbea3b2257e2
[ "Apache-2.0" ]
null
null
null
examples/applications/clustering/kmeans.py
shelleyyyyu/sentence-transformers
f004fba1dc23bbbe3caebd044748cbea3b2257e2
[ "Apache-2.0" ]
null
null
null
""" This is a simple application for sentence embeddings: clustering Sentences are mapped to sentence embeddings and then k-mean clustering is applied. """ from sentence_transformers import SentenceTransformer from sklearn.cluster import KMeans embedder = SentenceTransformer('distilroberta-base-paraphrase-v1') # Corpus with example sentences corpus = ['A man is eating food.', 'A man is eating a piece of bread.', 'A man is eating pasta.', 'The girl is carrying a baby.', 'The baby is carried by the woman', 'A man is riding a horse.', 'A man is riding a white horse on an enclosed ground.', 'A monkey is playing drums.', 'Someone in a gorilla costume is playing a set of drums.', 'A cheetah is running behind its prey.', 'A cheetah chases prey on across a field.' ] corpus_embeddings = embedder.encode(corpus) # Perform kmean clustering num_clusters = 5 clustering_model = KMeans(n_clusters=num_clusters) clustering_model.fit(corpus_embeddings) cluster_assignment = clustering_model.labels_ clustered_sentences = [[] for i in range(num_clusters)] for sentence_id, cluster_id in enumerate(cluster_assignment): clustered_sentences[cluster_id].append(corpus[sentence_id]) for i, cluster in enumerate(clustered_sentences): print("Cluster ", i+1) print(cluster) print("")
35.05
82
0.710414
from sentence_transformers import SentenceTransformer from sklearn.cluster import KMeans embedder = SentenceTransformer('distilroberta-base-paraphrase-v1') corpus = ['A man is eating food.', 'A man is eating a piece of bread.', 'A man is eating pasta.', 'The girl is carrying a baby.', 'The baby is carried by the woman', 'A man is riding a horse.', 'A man is riding a white horse on an enclosed ground.', 'A monkey is playing drums.', 'Someone in a gorilla costume is playing a set of drums.', 'A cheetah is running behind its prey.', 'A cheetah chases prey on across a field.' ] corpus_embeddings = embedder.encode(corpus) num_clusters = 5 clustering_model = KMeans(n_clusters=num_clusters) clustering_model.fit(corpus_embeddings) cluster_assignment = clustering_model.labels_ clustered_sentences = [[] for i in range(num_clusters)] for sentence_id, cluster_id in enumerate(cluster_assignment): clustered_sentences[cluster_id].append(corpus[sentence_id]) for i, cluster in enumerate(clustered_sentences): print("Cluster ", i+1) print(cluster) print("")
true
true
1c3c294e57e6f958d38ee04d5b0c84c2fe60f121
835
py
Python
tests/conftest.py
Leoberti/thesaurus
07de6d9d29e71a565c84cc49a248d4e3ca8f4426
[ "Unlicense" ]
null
null
null
tests/conftest.py
Leoberti/thesaurus
07de6d9d29e71a565c84cc49a248d4e3ca8f4426
[ "Unlicense" ]
null
null
null
tests/conftest.py
Leoberti/thesaurus
07de6d9d29e71a565c84cc49a248d4e3ca8f4426
[ "Unlicense" ]
null
null
null
import sys import pytest from thesaurus import create_app from thesaurus.ext.commands import populate_db from thesaurus.ext.database import db @pytest.fixture(scope="session") def app(): app = create_app(FORCE_ENV_FOR_DYNACONF="testing") with app.app_context(): db.create_all(app=app) yield app db.drop_all(app=app) @pytest.fixture(scope="session") def products(app): with app.app_context(): return populate_db() # each test runs on cwd to its temp dir @pytest.fixture(autouse=True) def go_to_tmpdir(request): # Get the fixture dynamically by its name. tmpdir = request.getfixturevalue("tmpdir") # ensure local test created packages can be imported sys.path.insert(0, str(tmpdir)) # Chdir only for the duration of the test. with tmpdir.as_cwd(): yield
24.558824
56
0.707784
import sys import pytest from thesaurus import create_app from thesaurus.ext.commands import populate_db from thesaurus.ext.database import db @pytest.fixture(scope="session") def app(): app = create_app(FORCE_ENV_FOR_DYNACONF="testing") with app.app_context(): db.create_all(app=app) yield app db.drop_all(app=app) @pytest.fixture(scope="session") def products(app): with app.app_context(): return populate_db() @pytest.fixture(autouse=True) def go_to_tmpdir(request): tmpdir = request.getfixturevalue("tmpdir") sys.path.insert(0, str(tmpdir)) with tmpdir.as_cwd(): yield
true
true
1c3c295dc7c39ccb0c3a4384a5235d3a11b23c3d
7,554
py
Python
config/settings/production.py
skaaldig/borrowing
70a19a1f3db3719247e42814176ed6b69afe081c
[ "MIT" ]
null
null
null
config/settings/production.py
skaaldig/borrowing
70a19a1f3db3719247e42814176ed6b69afe081c
[ "MIT" ]
null
null
null
config/settings/production.py
skaaldig/borrowing
70a19a1f3db3719247e42814176ed6b69afe081c
[ "MIT" ]
null
null
null
from .base import * # noqa from .base import env # GENERAL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = env("DJANGO_SECRET_KEY") # https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["example.com"]) # DATABASES # ------------------------------------------------------------------------------ DATABASES["default"] = env.db("DATABASE_URL") # noqa F405 DATABASES["default"]["ATOMIC_REQUESTS"] = True # noqa F405 DATABASES["default"]["CONN_MAX_AGE"] = env.int("CONN_MAX_AGE", default=60) # noqa F405 # CACHES # ------------------------------------------------------------------------------ CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": env("REDIS_URL"), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", # Mimicing memcache behavior. # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior "IGNORE_EXCEPTIONS": True, }, } } # SECURITY # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # https://docs.djangoproject.com/en/dev/ref/settings/#secure-ssl-redirect SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) # https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-secure SESSION_COOKIE_SECURE = True # https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-secure CSRF_COOKIE_SECURE = True # https://docs.djangoproject.com/en/dev/topics/security/#ssl-https # https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-seconds # TODO: set this to 60 seconds first and then to 518400 once you prove the former works SECURE_HSTS_SECONDS = 60 # https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-include-subdomains SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool( "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True ) # https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-preload SECURE_HSTS_PRELOAD = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True) # https://docs.djangoproject.com/en/dev/ref/middleware/#x-content-type-options-nosniff SECURE_CONTENT_TYPE_NOSNIFF = env.bool( "DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True ) # STORAGES # ------------------------------------------------------------------------------ # https://django-storages.readthedocs.io/en/latest/#installation INSTALLED_APPS += ["storages"] # noqa F405 # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_ACCESS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID") # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_SECRET_ACCESS_KEY = env("DJANGO_AWS_SECRET_ACCESS_KEY") # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_STORAGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME") # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_QUERYSTRING_AUTH = False # DO NOT change these unless you know what you're doing. _AWS_EXPIRY = 60 * 60 * 24 * 7 # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_S3_OBJECT_PARAMETERS = { "CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate" } # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_DEFAULT_ACL = None # STATIC # ------------------------ STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" # MEDIA # ------------------------------------------------------------------------------ DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/" # TEMPLATES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#templates TEMPLATES[0]["OPTIONS"]["loaders"] = [ # noqa F405 ( "django.template.loaders.cached.Loader", [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ], ) ] # EMAIL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email DEFAULT_FROM_EMAIL = env( "DJANGO_DEFAULT_FROM_EMAIL", default="prokeepr <noreply@example.com>" ) # https://docs.djangoproject.com/en/dev/ref/settings/#server-email SERVER_EMAIL = env("DJANGO_SERVER_EMAIL", default=DEFAULT_FROM_EMAIL) # https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix EMAIL_SUBJECT_PREFIX = env( "DJANGO_EMAIL_SUBJECT_PREFIX", default="[prokeepr]" ) # ADMIN # ------------------------------------------------------------------------------ # Django Admin URL regex. ADMIN_URL = env("DJANGO_ADMIN_URL") # Anymail (Mailgun) # ------------------------------------------------------------------------------ # https://anymail.readthedocs.io/en/stable/installation/#installing-anymail INSTALLED_APPS += ["anymail"] # noqa F405 EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" # https://anymail.readthedocs.io/en/stable/installation/#anymail-settings-reference ANYMAIL = { "MAILGUN_API_KEY": env("MAILGUN_API_KEY"), "MAILGUN_SENDER_DOMAIN": env("MAILGUN_DOMAIN"), } # Gunicorn # ------------------------------------------------------------------------------ INSTALLED_APPS += ["gunicorn"] # noqa F405 # WhiteNoise # ------------------------------------------------------------------------------ # http://whitenoise.evans.io/en/latest/django.html#enable-whitenoise MIDDLEWARE.insert(1, "whitenoise.middleware.WhiteNoiseMiddleware") # noqa F405 # LOGGING # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#logging # See https://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}}, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "mail_admins": { "level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log.AdminEmailHandler", }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", }, }, "loggers": { "django.request": { "handlers": ["mail_admins"], "level": "ERROR", "propagate": True, }, "django.security.DisallowedHost": { "level": "ERROR", "handlers": ["console", "mail_admins"], "propagate": True, }, }, } # Your stuff... # ------------------------------------------------------------------------------
40.832432
89
0.601006
from .base import * from .base import env = env("DJANGO_SECRET_KEY") = env.list("DJANGO_ALLOWED_HOSTS", default=["example.com"]) DATABASES["default"] = env.db("DATABASE_URL") DATABASES["default"]["ATOMIC_REQUESTS"] = True DATABASES["default"]["CONN_MAX_AGE"] = env.int("CONN_MAX_AGE", default=60) CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": env("REDIS_URL"), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", ": True, }, } } = ("HTTP_X_FORWARDED_PROTO", "https") = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) = True = True env.bool( "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True ) = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True) env.bool( "DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True ) PS += ["storages"] SS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID") ET_ACCESS_KEY = env("DJANGO_AWS_SECRET_ACCESS_KEY") AGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME") YSTRING_AUTH = False _AWS_EXPIRY = 60 * 60 * 24 * 7 # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_S3_OBJECT_PARAMETERS = { "CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate" } # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_DEFAULT_ACL = None # STATIC # ------------------------ STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" # MEDIA # ------------------------------------------------------------------------------ DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/" # TEMPLATES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#templates TEMPLATES[0]["OPTIONS"]["loaders"] = [ # noqa F405 ( "django.template.loaders.cached.Loader", [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ], ) ] # EMAIL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email DEFAULT_FROM_EMAIL = env( "DJANGO_DEFAULT_FROM_EMAIL", default="prokeepr <noreply@example.com>" ) # https://docs.djangoproject.com/en/dev/ref/settings/#server-email SERVER_EMAIL = env("DJANGO_SERVER_EMAIL", default=DEFAULT_FROM_EMAIL) # https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix EMAIL_SUBJECT_PREFIX = env( "DJANGO_EMAIL_SUBJECT_PREFIX", default="[prokeepr]" ) # ADMIN # ------------------------------------------------------------------------------ # Django Admin URL regex. ADMIN_URL = env("DJANGO_ADMIN_URL") # Anymail (Mailgun) # ------------------------------------------------------------------------------ # https://anymail.readthedocs.io/en/stable/installation/#installing-anymail INSTALLED_APPS += ["anymail"] # noqa F405 EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" # https://anymail.readthedocs.io/en/stable/installation/#anymail-settings-reference ANYMAIL = { "MAILGUN_API_KEY": env("MAILGUN_API_KEY"), "MAILGUN_SENDER_DOMAIN": env("MAILGUN_DOMAIN"), } # Gunicorn # ------------------------------------------------------------------------------ INSTALLED_APPS += ["gunicorn"] # noqa F405 # WhiteNoise # ------------------------------------------------------------------------------ # http://whitenoise.evans.io/en/latest/django.html#enable-whitenoise MIDDLEWARE.insert(1, "whitenoise.middleware.WhiteNoiseMiddleware") # noqa F405 # LOGGING # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#logging # See https://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}}, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "mail_admins": { "level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log.AdminEmailHandler", }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", }, }, "loggers": { "django.request": { "handlers": ["mail_admins"], "level": "ERROR", "propagate": True, }, "django.security.DisallowedHost": { "level": "ERROR", "handlers": ["console", "mail_admins"], "propagate": True, }, }, } # Your stuff... # ------------------------------------------------------------------------------
true
true
1c3c2a3cd8795d8dc828dbd50e17d361211a931d
2,757
py
Python
core/actionProxy/owplatform/__init__.py
IISAS/openwhisk-runtime-docker
a23dcfd4276399b5aa90a55520345307632dfbb4
[ "Apache-2.0" ]
11
2017-10-18T19:16:43.000Z
2019-05-20T21:54:32.000Z
core/actionProxy/owplatform/__init__.py
IISAS/openwhisk-runtime-docker
a23dcfd4276399b5aa90a55520345307632dfbb4
[ "Apache-2.0" ]
30
2018-01-24T17:30:14.000Z
2019-05-06T13:58:17.000Z
core/actionProxy/owplatform/__init__.py
IISAS/openwhisk-runtime-docker
a23dcfd4276399b5aa90a55520345307632dfbb4
[ "Apache-2.0" ]
26
2017-10-06T13:23:28.000Z
2019-07-08T00:47:45.000Z
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # class PlatformFactory: _SUPPORTED_PLATFORMS = set() _PLATFORM_IMPLEMENTATIONS = {} def __init__(self): pass @classmethod def supportedPlatforms(cls): return cls._SUPPORTED_PLATFORMS @classmethod def isSupportedPlatform(cls, id): return id.lower() in cls._SUPPORTED_PLATFORMS @classmethod def addPlatform(cls, platform, platformImp): if platform.lower not in cls._SUPPORTED_PLATFORMS: cls._SUPPORTED_PLATFORMS.add(platform.lower()) cls._PLATFORM_IMPLEMENTATIONS[platform.lower()] = platformImp else: raise DuplicatePlatform() getterName = "PLATFORM_" + platform.upper() setattr(cls, getterName, platform) @classmethod def createPlatformImpl(cls, id, proxy): if cls.isSupportedPlatform(id): return cls._PLATFORM_IMPLEMENTATIONS[id.lower()](proxy) else: raise InvalidPlatformError(id, self.supportedPlatforms()) @property def app(self): return self._app @app.setter def app(self, value): raise ConstantError("app cannot be set outside of initialization") @property def config(self): return self._config @config.setter def config(self, value): raise ConstantError("config cannot be set outside of initialization") @property def service(self): return self._service @service.setter def service(self, value): raise ConstantError("service cannot be set outside of initialization") class ConstantError(Exception): pass class DuplicatePlatformError(Exception): pass class InvalidPlatformError(Exception): def __init__(self, platform, supportedPlatforms): self.platform = platform.lower() self.supportedPlatforms = supportedPlatforms def __str__(self): return f"Invalid Platform: {self.platform} is not in supported platforms {self.supportedPlatforms}."
31.329545
108
0.704389
class PlatformFactory: _SUPPORTED_PLATFORMS = set() _PLATFORM_IMPLEMENTATIONS = {} def __init__(self): pass @classmethod def supportedPlatforms(cls): return cls._SUPPORTED_PLATFORMS @classmethod def isSupportedPlatform(cls, id): return id.lower() in cls._SUPPORTED_PLATFORMS @classmethod def addPlatform(cls, platform, platformImp): if platform.lower not in cls._SUPPORTED_PLATFORMS: cls._SUPPORTED_PLATFORMS.add(platform.lower()) cls._PLATFORM_IMPLEMENTATIONS[platform.lower()] = platformImp else: raise DuplicatePlatform() getterName = "PLATFORM_" + platform.upper() setattr(cls, getterName, platform) @classmethod def createPlatformImpl(cls, id, proxy): if cls.isSupportedPlatform(id): return cls._PLATFORM_IMPLEMENTATIONS[id.lower()](proxy) else: raise InvalidPlatformError(id, self.supportedPlatforms()) @property def app(self): return self._app @app.setter def app(self, value): raise ConstantError("app cannot be set outside of initialization") @property def config(self): return self._config @config.setter def config(self, value): raise ConstantError("config cannot be set outside of initialization") @property def service(self): return self._service @service.setter def service(self, value): raise ConstantError("service cannot be set outside of initialization") class ConstantError(Exception): pass class DuplicatePlatformError(Exception): pass class InvalidPlatformError(Exception): def __init__(self, platform, supportedPlatforms): self.platform = platform.lower() self.supportedPlatforms = supportedPlatforms def __str__(self): return f"Invalid Platform: {self.platform} is not in supported platforms {self.supportedPlatforms}."
true
true
1c3c2aad137d4fbf23ed920a2adf9041a0b2b0ef
571
py
Python
stockquant/util/stringhelper.py
dabuc/StockQuant
d9de6409b421aa2bf859cb93d46f4344cdb47bc1
[ "MIT" ]
null
null
null
stockquant/util/stringhelper.py
dabuc/StockQuant
d9de6409b421aa2bf859cb93d46f4344cdb47bc1
[ "MIT" ]
null
null
null
stockquant/util/stringhelper.py
dabuc/StockQuant
d9de6409b421aa2bf859cb93d46f4344cdb47bc1
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from enum import Enum, unique @unique class TaskEnum(Enum): """ 任务枚举 """ 季频盈利能力 = "profit" BS日线历史A股K线后复权数据 = "bs_daily_hfq" BS周线历史A股K线后复权数据 = "bs_weekly_hfq" BS日线历史A股K线数据 = "bs_daily" BS计算指定日期往后N日涨跌幅 = "bs_calc_later_n_pctChg" BS60分钟K线后复权数据 = "BS_m60_hfq" TS更新每日指标 = "ts_daily_basic" TS日线行情 = "ts_daily" TS复权因子 = "ts_adj_factor" TS每日涨跌停价格 = "ts_stk_limit" TS指数日线行情 = "ts_index_daily" TS指数成分和权重 = "TS_Index_Weight" # -----------回测任务--------- BS均线应用_两线法 = "two-EMA-win-rate"
20.392857
46
0.625219
from enum import Enum, unique @unique class TaskEnum(Enum): 季频盈利能力 = "profit" BS日线历史A股K线后复权数据 = "bs_daily_hfq" BS周线历史A股K线后复权数据 = "bs_weekly_hfq" BS日线历史A股K线数据 = "bs_daily" BS计算指定日期往后N日涨跌幅 = "bs_calc_later_n_pctChg" BS60分钟K线后复权数据 = "BS_m60_hfq" TS更新每日指标 = "ts_daily_basic" TS日线行情 = "ts_daily" TS复权因子 = "ts_adj_factor" TS每日涨跌停价格 = "ts_stk_limit" TS指数日线行情 = "ts_index_daily" TS指数成分和权重 = "TS_Index_Weight" BS均线应用_两线法 = "two-EMA-win-rate"
true
true
1c3c2b0ef02ab6428b5ad87044165abfa69acf04
1,041
py
Python
nas_big_data/attn/problem_ae.py
deephyper/NASBigData
18f083a402b80b1d006eada00db7287ff1802592
[ "BSD-2-Clause" ]
3
2020-08-07T12:05:12.000Z
2021-04-05T19:38:37.000Z
nas_big_data/attn/problem_ae.py
deephyper/NASBigData
18f083a402b80b1d006eada00db7287ff1802592
[ "BSD-2-Clause" ]
2
2020-07-17T14:44:12.000Z
2021-04-04T14:52:11.000Z
nas_big_data/attn/problem_ae.py
deephyper/NASBigData
18f083a402b80b1d006eada00db7287ff1802592
[ "BSD-2-Clause" ]
1
2021-03-28T01:49:21.000Z
2021-03-28T01:49:21.000Z
from deephyper.problem import NaProblem from nas_big_data.attn.search_space import create_search_space from nas_big_data.attn.load_data import load_data_cache Problem = NaProblem(seed=2019) Problem.load_data(load_data_cache) Problem.search_space(create_search_space, num_layers=5) Problem.hyperparameters( lsr_batch_size=True, lsr_learning_rate=True, batch_size=32, learning_rate=0.001, optimizer="adam", num_epochs=100, verbose=0, callbacks=dict( ReduceLROnPlateau=dict(monitor="val_aucpr", mode="max", verbose=0, patience=5), EarlyStopping=dict( monitor="val_aucpr", min_delta=0, mode="max", verbose=0, patience=10 ), ) ) Problem.loss( "categorical_crossentropy", class_weights={0: 0.5186881480859765, 1: 13.877462488516892} ) Problem.metrics(["acc", "auroc", "aucpr"]) Problem.objective("val_aucpr") # Just to print your problem, to test its definition and imports in the current python environment. if __name__ == "__main__": print(Problem)
26.692308
99
0.728146
from deephyper.problem import NaProblem from nas_big_data.attn.search_space import create_search_space from nas_big_data.attn.load_data import load_data_cache Problem = NaProblem(seed=2019) Problem.load_data(load_data_cache) Problem.search_space(create_search_space, num_layers=5) Problem.hyperparameters( lsr_batch_size=True, lsr_learning_rate=True, batch_size=32, learning_rate=0.001, optimizer="adam", num_epochs=100, verbose=0, callbacks=dict( ReduceLROnPlateau=dict(monitor="val_aucpr", mode="max", verbose=0, patience=5), EarlyStopping=dict( monitor="val_aucpr", min_delta=0, mode="max", verbose=0, patience=10 ), ) ) Problem.loss( "categorical_crossentropy", class_weights={0: 0.5186881480859765, 1: 13.877462488516892} ) Problem.metrics(["acc", "auroc", "aucpr"]) Problem.objective("val_aucpr") if __name__ == "__main__": print(Problem)
true
true