hexsha
stringlengths
40
40
size
int64
3
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
972
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
972
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
972
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
3
1.03M
avg_line_length
float64
1.13
941k
max_line_length
int64
2
941k
alphanum_fraction
float64
0
1
2e56a21ee0064aad8337abb9489cfc89eeb27322
4,955
py
Python
docs/conf.py
spewil/RTGraph
0e3f4502988a36866ac2aaa27e232ade2128d7ea
[ "MIT" ]
43
2015-06-10T23:26:03.000Z
2021-12-16T11:40:40.000Z
docs/conf.py
spewil/RTGraph
0e3f4502988a36866ac2aaa27e232ade2128d7ea
[ "MIT" ]
3
2017-06-16T13:29:02.000Z
2019-03-12T22:33:26.000Z
docs/conf.py
spewil/RTGraph
0e3f4502988a36866ac2aaa27e232ade2128d7ea
[ "MIT" ]
31
2015-03-19T11:59:53.000Z
2021-10-10T13:15:55.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # RTGraph documentation build configuration file, created by # sphinx-quickstart on Tue Dec 20 22:19:34 2016. # # 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. # import os import sys sys.path.insert(0, os.path.abspath('..')) from rtgraph.core.constants import Constants # -- 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 = ['sphinx.ext.autodoc', 'sphinx.ext.doctest'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = 'RTGraph' copyright = '2016, Sebastian Sepulveda' author = 'Sebastian Sepulveda' # 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. [major, minor, release] = Constants.app_version.split(".") version = "{}.{}".format(major, minor) # The full version, including alpha/beta/rc tags. release = "{}".format(release) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- 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 = 'sphinx_rtd_theme' html_theme = 'alabaster' # 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 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'] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'RTGraphdoc' # -- 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': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'RTGraph.tex', 'RTGraph Documentation', 'Sebastian Sepulveda', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'rtgraph', 'RTGraph Documentation', [author], 1) ] # -- 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 = [ (master_doc, 'RTGraph', 'RTGraph Documentation', author, 'RTGraph', 'One line description of project.', 'Miscellaneous'), ]
30.58642
79
0.683552
4e18ca2164579871a64ba9bda93e7d956f7fa595
395
py
Python
beautifultable/compat.py
digitronik/beautifultable
23ce72f1d2491f3015e6419e828e2ea499404ecd
[ "MIT" ]
null
null
null
beautifultable/compat.py
digitronik/beautifultable
23ce72f1d2491f3015e6419e828e2ea499404ecd
[ "MIT" ]
null
null
null
beautifultable/compat.py
digitronik/beautifultable
23ce72f1d2491f3015e6419e828e2ea499404ecd
[ "MIT" ]
null
null
null
import sys PY3 = sys.version_info[0] == 3 if PY3: to_unicode = str basestring = (str, bytes) from itertools import zip_longest from collections.abc import Iterable else: # pragma: no cover basestring = basestring to_unicode = unicode # noqa: F821 from itertools import izip_longest as zip_longest # noqa: F401 from collections import Iterable # noqa: F401
24.6875
67
0.703797
da3c93f3300d62ee4bf391d38d9382f29dd0e9db
2,955
py
Python
fridrich/server/WStationFuncs.py
Nilusink/Fridrich
73fb361207af9984ea5d9413c28c90d8fc56d33c
[ "MIT" ]
null
null
null
fridrich/server/WStationFuncs.py
Nilusink/Fridrich
73fb361207af9984ea5d9413c28c90d8fc56d33c
[ "MIT" ]
null
null
null
fridrich/server/WStationFuncs.py
Nilusink/Fridrich
73fb361207af9984ea5d9413c28c90d8fc56d33c
[ "MIT" ]
null
null
null
""" for weather-stations to commit data to the pool Author: Nilusink """ from fridrich.server.server_funcs import send_success from fridrich.classes import User from fridrich.server import Const import json def register(message: dict, user: User, *_args) -> None: """ register a new weather-station """ tmp: list try: tmp = json.load(open(Const.WeatherDir+"all.json", "r")) except json.JSONDecodeError: tmp = [] for element in tmp: if message["station_name"] == element["station_name"]: mes = { 'Error': 'RegistryError', "info": "weather-station is already registered" } user.send(mes, message_type="Error") return tmp.append({ "station_name": message["station_name"], "location": message["location"] }) with open(Const.WeatherDir+"all.json", "w") as out_file: json.dump(tmp, out_file, indent=4) with open(Const.WeatherDir+message["station_name"], "w") as out_file: out_file.write("[]") send_success(user) def commit_data(message: dict, user: User, *_args) -> None: """ commit data for already registered stations """ now_data: dict station_data: dict if not check_if_registered(message, user, *_args): mes = { 'Error': 'RegistryError', "info": "weather-station is not registered yet" } user.send(mes, message_type="Error") return try: now_data = json.load(open(Const.WeatherDir+"now.json", "r")) except json.JSONDecodeError: now_data = {} now_data[message["station_name"]] = { "time": message["time"], "temp": message["temp"], "hum": message["hum"], "press": message["press"] } with open(Const.WeatherDir+"now.json", "w") as out_file: json.dump(now_data, out_file, indent=4) try: station_data = json.load(open(Const.WeatherDir+message["station_name"], "r")) except json.JSONEncoder: station_data = {} station_data[message["time"]] = { "temp": message["temp"], "hum": message["hum"], "press": message["press"] } with open(Const.WeatherDir + message["station_name"], "w") as out_file: json.dump(station_data, out_file, indent=4) send_success(user) def check_if_registered(message: dict, _user: User, *_args) -> bool: """ check if a weather-station is already registered """ return message["station_name"] in json.load(open(Const.WeatherDir+"all.json", "r")) def get_all(_message: dict, user: User, *_args) -> None: """ send a dict of all weather-stations with their current measurement """ now_data: dict try: now_data = json.load(open(Const.WeatherDir+"now.json", "r")) except json.JSONDecodeError: now_data = {} user.send(now_data)
26.150442
87
0.598646
8cf3285fc2c30bca6f21b1ac3717714afd942dff
11,561
py
Python
widget_team_block/views.py
chr0nu5/core
aa80ccb3ae30dd12a5c848079d1184a830fcb83b
[ "MIT" ]
null
null
null
widget_team_block/views.py
chr0nu5/core
aa80ccb3ae30dd12a5c848079d1184a830fcb83b
[ "MIT" ]
null
null
null
widget_team_block/views.py
chr0nu5/core
aa80ccb3ae30dd12a5c848079d1184a830fcb83b
[ "MIT" ]
null
null
null
from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def get_widget(request): return HttpResponse('<div class="container webrock-object ui-sortable" data-atts="{&quot;margin&quot;:&quot;&quot;,&quot;padding&quot;:&quot;&quot;,&quot;classes&quot;:&quot;&quot;,&quot;id&quot;:&quot;&quot;}" data-shortcode="container" data-filter="*" data-filter-exclude="*"><div class="webrock-content"><div class="row margin-top-2x margin-bottom-2x webrock-object ui-sortable" data-atts="{&quot;margin&quot;:&quot;&quot;,&quot;padding&quot;:&quot;&quot;,&quot;classes&quot;:&quot;margin-top-2x margin-bottom-2x&quot;}" data-shortcode="row" data-filter="*" data-filter-exclude="*" style="position: relative;"><div class="webrock-content"><div class="col col-md-12 webrock-object ui-sortable" data-atts="{&quot;xs&quot;:&quot;&quot;,&quot;sm&quot;:&quot;&quot;,&quot;md&quot;:&quot;col-md-12&quot;,&quot;lg&quot;:&quot;&quot;,&quot;classes&quot;:&quot;&quot;}" data-shortcode="column"><div class="webrock-content"><div class="text-center webrock-object" data-atts="{&quot;text&quot;:&quot;OUR TEAM&quot;,&quot;type&quot;:&quot;h1&quot;,&quot;responsive&quot;:&quot;&quot;,&quot;font&quot;:&quot;text-heading-bold&quot;,&quot;style&quot;:&quot;&quot;,&quot;classes&quot;:&quot;text-center&quot;,&quot;animation&quot;:&quot;&quot;}" data-shortcode="heading" data-filter="*" data-filter-exclude="*"><h1 class="heading text-heading-bold">OUR TEAM</h1></div><div class="textbox text-gray-dark webrock-object" data-atts="{&quot;text&quot;:&quot;&amp;lt;p style=&amp;quot;text-align: center;&amp;quot;&amp;gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam&amp;lt;/p&amp;gt;&quot;,&quot;classes&quot;:&quot;&quot;,&quot;color&quot;:&quot;#000000&quot;,&quot;animation&quot;:&quot;&quot;}" data-shortcode="textbox" data-filter="*" data-filter-exclude="*"><p style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</p></div></div></div></div></div><div class="row margin-top-2x margin-bottom-2x webrock-object ui-sortable" data-atts="{&quot;margin&quot;:&quot;&quot;,&quot;padding&quot;:&quot;&quot;,&quot;classes&quot;:&quot;margin-top-2x margin-bottom-2x&quot;}" data-shortcode="row" data-filter="*" data-filter-exclude="*" style="position: relative;"><div class="webrock-content"><div class="col col-sm-6 col-md-3 webrock-object ui-sortable" data-atts="{&quot;xs&quot;:&quot;&quot;,&quot;sm&quot;:&quot;col-sm-6&quot;,&quot;md&quot;:&quot;col-md-3&quot;,&quot;lg&quot;:&quot;&quot;,&quot;classes&quot;:&quot;&quot;}" data-shortcode="column" data-filter="*" data-filter-exclude="*"><div class="webrock-content"><div class="team-member team-member-1 team-member-inverse text-center webrock-object" data-atts="{&quot;style&quot;:&quot;team-member-1&quot;,&quot;image&quot;:&quot;img/default/teammember.jpg&quot;,&quot;name&quot;:&quot;John Doe&quot;,&quot;profession&quot;:&quot;Manager&quot;,&quot;description&quot;:&quot;&amp;lt;p&amp;gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.&amp;lt;/p&amp;gt;&quot;,&quot;theme&quot;:&quot;team-member-inverse&quot;,&quot;social&quot;:&quot;{&amp;quot;fa fa-twitter&amp;quot;:&amp;quot;http://twitter.com/grozavcom&amp;quot;,&amp;quot;fa fa-facebook&amp;quot;:&amp;quot;http://facebook.com/grozavcom&amp;quot;,&amp;quot;fa fa-google-plus&amp;quot;:&amp;quot;http;//plus.google.com/#&amp;quot;,&amp;quot;fa fa-linkedin&amp;quot;:&amp;quot;http://linkedin.com/pub/alex-grozav/48/4b3/127&amp;quot;}&quot;,&quot;animation&quot;:&quot;&quot;,&quot;classes&quot;:&quot;&quot;}" data-shortcode="teammember" data-filter="*" data-filter-exclude="*"><div class="team-member-img-wrapper"><img src="img/default/teammember.jpg" class="img-fullwidth team-member-image"></div><div class="team-member-details"><h2 class="team-member-name">John Doe</h2><h4 class="team-member-profession">Manager</h4><div class="team-member-description text-sm"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p></div><ul class="team-member-social list-inline"><li><a href="http://twitter.com/grozavcom"><i class="fa fa-twitter"></i></a></li><li><a href="http://facebook.com/grozavcom"><i class="fa fa-facebook"></i></a></li><li><a href="http;//plus.google.com/#"><i class="fa fa-google-plus"></i></a></li><li><a href="http://linkedin.com/pub/alex-grozav/48/4b3/127"><i class="fa fa-linkedin"></i></a></li></ul></div></div></div></div><div class="col col-sm-6 col-md-3 webrock-object ui-sortable" data-atts="{&quot;xs&quot;:&quot;&quot;,&quot;sm&quot;:&quot;col-sm-6&quot;,&quot;md&quot;:&quot;col-md-3&quot;,&quot;lg&quot;:&quot;&quot;,&quot;classes&quot;:&quot;&quot;}" data-shortcode="column" data-filter="*" data-filter-exclude="*"><div class="webrock-content"><div class="team-member team-member-1 team-member-inverse text-center webrock-object" data-atts="{&quot;style&quot;:&quot;team-member-1&quot;,&quot;image&quot;:&quot;img/default/teammember-2.jpg&quot;,&quot;name&quot;:&quot;Lisa Kramer&quot;,&quot;profession&quot;:&quot;Web Developer&quot;,&quot;description&quot;:&quot;&amp;lt;p&amp;gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.&amp;lt;/p&amp;gt;&quot;,&quot;theme&quot;:&quot;team-member-inverse&quot;,&quot;social&quot;:&quot;{&amp;quot;fa fa-twitter&amp;quot;:&amp;quot;http://twitter.com/grozavcom&amp;quot;,&amp;quot;fa fa-facebook&amp;quot;:&amp;quot;http://facebook.com/grozavcom&amp;quot;,&amp;quot;fa fa-google-plus&amp;quot;:&amp;quot;http;//plus.google.com/#&amp;quot;,&amp;quot;fa fa-linkedin&amp;quot;:&amp;quot;http://linkedin.com/pub/alex-grozav/48/4b3/127&amp;quot;}&quot;,&quot;animation&quot;:&quot;&quot;,&quot;classes&quot;:&quot;&quot;}" data-shortcode="teammember" data-filter="*" data-filter-exclude="*"><div class="team-member-img-wrapper"><img src="img/default/teammember-2.jpg" class="img-fullwidth team-member-image"></div><div class="team-member-details"><h2 class="team-member-name">Lisa Kramer</h2><h4 class="team-member-profession">Web Developer</h4><div class="team-member-description text-sm"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p></div><ul class="team-member-social list-inline"><li><a href="http://twitter.com/grozavcom"><i class="fa fa-twitter"></i></a></li><li><a href="http://facebook.com/grozavcom"><i class="fa fa-facebook"></i></a></li><li><a href="http;//plus.google.com/#"><i class="fa fa-google-plus"></i></a></li><li><a href="http://linkedin.com/pub/alex-grozav/48/4b3/127"><i class="fa fa-linkedin"></i></a></li></ul></div></div></div></div><div class="col col-sm-6 col-md-3 webrock-object ui-sortable" data-atts="{&quot;xs&quot;:&quot;&quot;,&quot;sm&quot;:&quot;col-sm-6&quot;,&quot;md&quot;:&quot;col-md-3&quot;,&quot;lg&quot;:&quot;&quot;,&quot;classes&quot;:&quot;&quot;}" data-shortcode="column" data-filter="*" data-filter-exclude="*"><div class="webrock-content"><div class="team-member team-member-1 team-member-inverse text-center webrock-object" data-atts="{&quot;style&quot;:&quot;team-member-1&quot;,&quot;image&quot;:&quot;img/default/teammember-3.jpg&quot;,&quot;name&quot;:&quot;Daniel Ray&quot;,&quot;profession&quot;:&quot;Web Developer&quot;,&quot;description&quot;:&quot;&amp;lt;p&amp;gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.&amp;lt;/p&amp;gt;&quot;,&quot;theme&quot;:&quot;team-member-inverse&quot;,&quot;social&quot;:&quot;{&amp;quot;fa fa-twitter&amp;quot;:&amp;quot;http://twitter.com/grozavcom&amp;quot;,&amp;quot;fa fa-facebook&amp;quot;:&amp;quot;http://facebook.com/grozavcom&amp;quot;,&amp;quot;fa fa-google-plus&amp;quot;:&amp;quot;http;//plus.google.com/#&amp;quot;,&amp;quot;fa fa-linkedin&amp;quot;:&amp;quot;http://linkedin.com/pub/alex-grozav/48/4b3/127&amp;quot;}&quot;,&quot;animation&quot;:&quot;&quot;,&quot;classes&quot;:&quot;&quot;}" data-shortcode="teammember" data-filter="*" data-filter-exclude="*"><div class="team-member-img-wrapper"><img src="img/default/teammember-3.jpg" class="img-fullwidth team-member-image"></div><div class="team-member-details"><h2 class="team-member-name">Daniel Ray</h2><h4 class="team-member-profession">Web Developer</h4><div class="team-member-description text-sm"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p></div><ul class="team-member-social list-inline"><li><a href="http://twitter.com/grozavcom"><i class="fa fa-twitter"></i></a></li><li><a href="http://facebook.com/grozavcom"><i class="fa fa-facebook"></i></a></li><li><a href="http;//plus.google.com/#"><i class="fa fa-google-plus"></i></a></li><li><a href="http://linkedin.com/pub/alex-grozav/48/4b3/127"><i class="fa fa-linkedin"></i></a></li></ul></div></div></div></div><div class="col col-sm-6 col-md-3 webrock-object ui-sortable" data-atts="{&quot;xs&quot;:&quot;&quot;,&quot;sm&quot;:&quot;col-sm-6&quot;,&quot;md&quot;:&quot;col-md-3&quot;,&quot;lg&quot;:&quot;&quot;,&quot;classes&quot;:&quot;&quot;}" data-shortcode="column" data-filter="*" data-filter-exclude="*"><div class="webrock-content"><div class="team-member team-member-1 team-member-inverse text-center webrock-object" data-atts="{&quot;style&quot;:&quot;team-member-1&quot;,&quot;image&quot;:&quot;img/default/teammember-4.jpg&quot;,&quot;name&quot;:&quot;Alice Lane&quot;,&quot;profession&quot;:&quot;Web Designer&quot;,&quot;description&quot;:&quot;&amp;lt;p&amp;gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.&amp;lt;/p&amp;gt;&quot;,&quot;theme&quot;:&quot;team-member-inverse&quot;,&quot;social&quot;:&quot;{&amp;quot;fa fa-twitter&amp;quot;:&amp;quot;http://twitter.com/grozavcom&amp;quot;,&amp;quot;fa fa-facebook&amp;quot;:&amp;quot;http://facebook.com/grozavcom&amp;quot;,&amp;quot;fa fa-google-plus&amp;quot;:&amp;quot;http;//plus.google.com/#&amp;quot;,&amp;quot;fa fa-linkedin&amp;quot;:&amp;quot;http://linkedin.com/pub/alex-grozav/48/4b3/127&amp;quot;}&quot;,&quot;animation&quot;:&quot;&quot;,&quot;classes&quot;:&quot;&quot;}" data-shortcode="teammember" data-filter="*" data-filter-exclude="*"><div class="team-member-img-wrapper"><img src="img/default/teammember-4.jpg" class="img-fullwidth team-member-image"></div><div class="team-member-details"><h2 class="team-member-name">Alice Lane</h2><h4 class="team-member-profession">Web Designer</h4><div class="team-member-description text-sm"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p></div><ul class="team-member-social list-inline"><li><a href="http://twitter.com/grozavcom"><i class="fa fa-twitter"></i></a></li><li><a href="http://facebook.com/grozavcom"><i class="fa fa-facebook"></i></a></li><li><a href="http;//plus.google.com/#"><i class="fa fa-google-plus"></i></a></li><li><a href="http://linkedin.com/pub/alex-grozav/48/4b3/127"><i class="fa fa-linkedin"></i></a></li></ul></div></div></div></div></div></div></div></div>')
1,445.125
11,395
0.723121
04ca7da1043045a1b5703433113c9a65a4a85c9e
146,983
py
Python
python/paddle/tensor/math.py
xiaoyangyang2/Paddle
b1a4668c5ff39e44efcfea46d567a5c398fdf3dc
[ "Apache-2.0" ]
null
null
null
python/paddle/tensor/math.py
xiaoyangyang2/Paddle
b1a4668c5ff39e44efcfea46d567a5c398fdf3dc
[ "Apache-2.0" ]
null
null
null
python/paddle/tensor/math.py
xiaoyangyang2/Paddle
b1a4668c5ff39e44efcfea46d567a5c398fdf3dc
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ math functions """ from __future__ import print_function import numpy as np from paddle.common_ops_import import VarDesc from paddle.common_ops_import import dygraph_only from paddle.common_ops_import import OpProtoHolder from paddle.common_ops_import import templatedoc from paddle.common_ops_import import dygraph_utils from paddle.tensor import cast from paddle.tensor.attribute import _complex_to_real_dtype import paddle from paddle.static import Variable from ..framework import core, _in_eager_mode from ..framework import _varbase_creator, convert_np_dtype_to_dtype_ from ..fluid.layer_helper import LayerHelper from ..fluid.data_feeder import check_variable_and_dtype, check_type, check_dtype, convert_dtype from ..fluid.layers.layer_function_generator import _generate_doc_string_, generate_activation_fn, generate_layer_fn from ..fluid.dygraph.inplace_utils import inplace_apis_in_dygraph_only # TODO: define math functions # yapf: disable from ..fluid.layers import abs # noqa: F401 from ..fluid.layers import acos # noqa: F401 from ..fluid.layers import asin # noqa: F401 from ..fluid.layers import ceil # noqa: F401 from ..fluid.layers import ceil_ # noqa: F401 from ..fluid.layers import cos # noqa: F401 from ..fluid.layers import tan # noqa: F401 from ..fluid.layers import sinh # noqa: F401 from ..fluid.layers import cosh # noqa: F401 from ..fluid.layers import exp # noqa: F401 from ..fluid.layers import exp_ # noqa: F401 from ..fluid.layers import expm1 # noqa: F401 from ..fluid.layers import floor # noqa: F401 from ..fluid.layers import floor_ # noqa: F401 from ..fluid.layers import log # noqa: F401 from ..fluid.layers import reciprocal # noqa: F401 from ..fluid.layers import reciprocal_ # noqa: F401 from ..fluid.layers import round # noqa: F401 from ..fluid.layers import round_ # noqa: F401 from ..fluid.layers import rsqrt # noqa: F401 from ..fluid.layers import rsqrt_ # noqa: F401 from ..fluid.layers import scale # noqa: F401 from ..fluid.layers import square # noqa: F401 from ..fluid.layers import stanh # noqa: F401 from ..fluid.layers import atan # noqa: F401 from ..fluid.layers import erf # noqa: F401 from ..fluid.layers import sqrt # noqa: F401 from ..fluid.layers import sqrt_ # noqa: F401 from ..fluid.layers import sin # noqa: F401 from ..fluid.layers import lgamma # noqa: F401 from ..fluid.layers import asinh # noqa: F401 from ..fluid.layers import acosh # noqa: F401 from ..fluid.layers import atanh # noqa: F401 from ..fluid.layers import multiplex # noqa: F401 from ..fluid.layers import reduce_prod from ..fluid.layers import elementwise_sub from paddle import _C_ops __all__ = [] _supported_int_dtype_ = [ VarDesc.VarType.UINT8, VarDesc.VarType.INT8, VarDesc.VarType.INT16, VarDesc.VarType.INT32, VarDesc.VarType.INT64, ] _supported_float_dtype_ = [ VarDesc.VarType.FP32, VarDesc.VarType.FP64, ] @inplace_apis_in_dygraph_only def scale_(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None): """ Inplace version of ``scale`` API, the output Tensor will be inplaced with input ``x``. Please refer to :ref:`api_tensor_scale`. """ _scale = scale.numpy().item(0) if isinstance(scale, Variable) else scale return _C_ops.scale_(x, 'scale', float(_scale), 'bias', float(bias), 'bias_after_scale', bias_after_scale) def pow(x, y, name=None): """ Compute the power of tensor elements. The equation is: .. math:: out = x^{y} **Note**: ``paddle.pow`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . Args: x (Tensor): An N-D Tensor, the data type is float32, float64, int32 or int64. y (float|int|Tensor): If it is an N-D Tensor, its data type should be the same as `x`. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. Its dimension and data type are the same as `x`. Examples: .. code-block:: python import paddle x = paddle.to_tensor([1, 2, 3], dtype='float32') # example 1: y is a float or int res = paddle.pow(x, 2) print(res) # Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [1., 4., 9.]) res = paddle.pow(x, 2.5) print(res) # Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [1. , 5.65685415 , 15.58845711]) # example 2: y is a Tensor y = paddle.to_tensor([2], dtype='float32') res = paddle.pow(x, y) print(res) # Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [1., 4., 9.]) """ # in dynamic graph mode if paddle.in_dynamic_mode(): if isinstance(y, (int, float)): return _C_ops.pow(x, 'factor', y) elif isinstance(y, (paddle.Tensor, Variable)): return _elementwise_op_in_dygraph( x, y, axis=-1, act=None, op_name='elementwise_pow') else: raise TypeError('y must be scalar or tensor type, but received: %s '% (y.dtype)) # in static graph mode else: if isinstance(y, (int, float)): helper = LayerHelper('pow', **locals()) inputs = {'X': x} attrs = {'factor': y} out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='pow', inputs=inputs, outputs={'Out': out}, attrs=attrs) return out elif isinstance(y, (paddle.Tensor, Variable)): # TODO A potential speed improvement is supporting different types in C++ and removing the cast ops here helper = LayerHelper('elementwise_pow', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) return _elementwise_op(LayerHelper('elementwise_pow', **locals())) else: raise TypeError('y must be scalar or tensor type, but received: %s '% (type(y))) @dygraph_only def _elementwise_op_in_dygraph(x, y, axis=-1, act=None, use_mkldnn=False, op_name=None): op = getattr(_C_ops, op_name) out = op(x, y, 'axis', axis, 'use_mkldnn', use_mkldnn) return dygraph_utils._append_activation_in_dygraph( out, act, use_mkldnn=use_mkldnn) def _elementwise_op(helper): op_type = helper.layer_type original_op_type = helper.kwargs.get('original_op_type', op_type) x = helper.kwargs.get('x', None) y = helper.kwargs.get('y', None) out = helper.kwargs.get('out', None) assert x is not None, 'x cannot be None in {}'.format(original_op_type) assert y is not None, 'y cannot be None in {}'.format(original_op_type) check_variable_and_dtype( x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64', 'bool'], original_op_type) check_variable_and_dtype( y, 'y', ['float16', 'float32', 'float64', 'int32', 'int64', 'bool'], original_op_type) axis = helper.kwargs.get('axis', -1) use_mkldnn = helper.kwargs.get('use_mkldnn', False) name = helper.kwargs.get('name', None) if out is None: if name is None: out = helper.create_variable_for_type_inference(dtype=x.dtype) else: out = helper.create_variable(name=name, dtype=x.dtype, persistable=False) helper.append_op( type=op_type, inputs={'X': x, 'Y': y}, outputs={'Out': out}, attrs={'axis': axis, 'use_mkldnn': use_mkldnn}) return helper.append_activation(out) def add(x, y, name=None): """ Examples: .. code-block:: python import paddle x = paddle.to_tensor([2, 3, 4], 'float64') y = paddle.to_tensor([1, 5, 2], 'float64') z = paddle.add(x, y) print(z) # [3., 8., 6. ] """ if paddle.in_dynamic_mode(): if _in_eager_mode(): return _C_ops.final_state_add( x, y) return _C_ops.elementwise_add(x, y) return _elementwise_op(LayerHelper('elementwise_add', **locals())) @inplace_apis_in_dygraph_only def add_(x, y, name=None): """ Inplace version of ``add`` API, the output Tensor will be inplaced with input ``x``. Please refer to :ref:`api_tensor_add`. """ op_type = 'elementwise_add_' axis = -1 out_shape = broadcast_shape(x.shape, y.shape) if out_shape != x.shape: raise ValueError("The shape of broadcast output {} is different from that of inplace tensor {} in the Inplace operation.".format(out_shape, x.shape)) out = _elementwise_op_in_dygraph( x, y, axis=axis, op_name=op_type) return out def subtract(x, y, name=None): """ Substract two tensors element-wise. The equation is: .. math:: out = x - y **Note**: ``paddle.subtract`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . Args: x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. Examples: .. code-block:: python import numpy as np import paddle x = paddle.to_tensor([[1, 2], [7, 8]]) y = paddle.to_tensor([[5, 6], [3, 4]]) res = paddle.subtract(x, y) print(res) # [[-4, -4], # [4, 4]] x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]]) y = paddle.to_tensor([1, 0, 4]) res = paddle.subtract(x, y) print(res) # [[[ 0, 2, -1], # [ 0, 2, -1]]] x = paddle.to_tensor([2, np.nan, 5], dtype='float32') y = paddle.to_tensor([1, 4, np.nan], dtype='float32') res = paddle.subtract(x, y) print(res) # [ 1., nan, nan] x = paddle.to_tensor([5, np.inf, -np.inf], dtype='float64') y = paddle.to_tensor([1, 4, 5], dtype='float64') res = paddle.subtract(x, y) print(res) # [ 4., inf., -inf.] """ op_type = 'elementwise_sub' axis = -1 act = None if paddle.in_dynamic_mode(): if _in_eager_mode(): return _C_ops.final_state_subtract(x, y) return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name=op_type) return _elementwise_op(LayerHelper(op_type, **locals())) @inplace_apis_in_dygraph_only def subtract_(x, y, name=None): """ Inplace version of ``subtract`` API, the output Tensor will be inplaced with input ``x``. Please refer to :ref:`api_tensor_subtract`. """ axis = -1 act = None out_shape = broadcast_shape(x.shape, y.shape) if out_shape != x.shape: raise ValueError("The shape of broadcast output {} is different from that of inplace tensor {} in the Inplace operation.".format(out_shape, x.shape)) out = _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name='elementwise_sub_') return out def divide(x, y, name=None): """ Divide two tensors element-wise. The equation is: .. math:: out = x / y **Note**: ``paddle.divide`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . Args: x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. Examples: .. code-block:: python import paddle x = paddle.to_tensor([2, 3, 4], dtype='float64') y = paddle.to_tensor([1, 5, 2], dtype='float64') z = paddle.divide(x, y) print(z) # [2., 0.6, 2.] """ op_type = 'elementwise_div' axis = -1 act = None if paddle.in_dynamic_mode(): if _in_eager_mode(): return _C_ops.final_state_divide( x, y) return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name=op_type) return _elementwise_op(LayerHelper(op_type, **locals())) def floor_divide(x, y, name=None): """ Floor divide two tensors element-wise. The equation is: .. math:: out = x // y **Note**: ``paddle.floor_divide`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . Args: x (Tensor): the input tensor, it's data type should be int32, int64. y (Tensor): the input tensor, it's data type should be int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. It's dimension equals with $x$. Examples: .. code-block:: python import paddle x = paddle.to_tensor([2, 3, 8, 7]) y = paddle.to_tensor([1, 5, 3, 3]) z = paddle.floor_divide(x, y) print(z) # [2, 0, 2, 2] """ op_type = 'elementwise_floordiv' axis = -1 if paddle.in_dynamic_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, op_name=op_type) return _elementwise_op(LayerHelper(op_type, **locals())) def remainder(x, y, name=None): r""" Mod two tensors element-wise. The equation is: .. math:: out = x \% y **Note**: ``paddle.remainder`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . Args: x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. Examples: .. code-block:: python import paddle x = paddle.to_tensor([2, 3, 8, 7]) y = paddle.to_tensor([1, 5, 3, 3]) z = paddle.remainder(x, y) print(z) # [0, 3, 2, 1] """ op_type = 'elementwise_mod' axis = -1 if paddle.in_dynamic_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, op_name=op_type) return _elementwise_op(LayerHelper(op_type, **locals())) mod = remainder # noqa: F841 floor_mod = remainder # noqa: F841 def multiply(x, y, name=None): """ multiply two tensors element-wise. The equation is: .. math:: out = x * y **Note**: ``paddle.multiply`` supports broadcasting. If you would like to know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . Args: x (Tensor): the input tensor, its data type should be one of float32, float64, int32, int64, bool. y (Tensor): the input tensor, its data type should be one of float32, float64, int32, int64, bool. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. Examples: .. code-block:: python import paddle x = paddle.to_tensor([[1, 2], [3, 4]]) y = paddle.to_tensor([[5, 6], [7, 8]]) res = paddle.multiply(x, y) print(res) # [[5, 12], [21, 32]] x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]]) y = paddle.to_tensor([2]) res = paddle.multiply(x, y) print(res) # [[[2, 4, 6], [2, 4, 6]]] """ op_type = 'elementwise_mul' act = None axis = -1 if paddle.in_dynamic_mode(): if _in_eager_mode(): return _C_ops.final_state_multiply(x, y) return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name=op_type) if x.dtype != y.dtype: raise TypeError( 'Input tensors must be same type, but received type of x: %s, type of y: %s ' % (x.dtype, y.dtype)) return _elementwise_op(LayerHelper(op_type, **locals())) def maximum(x, y, name=None): """ Compare two tensors and returns a new tensor containing the element-wise maxima. The equation is: .. math:: out = max(x, y) **Note**: ``paddle.maximum`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . Args: x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. Examples: .. code-block:: python import numpy as np import paddle x = paddle.to_tensor([[1, 2], [7, 8]]) y = paddle.to_tensor([[3, 4], [5, 6]]) res = paddle.maximum(x, y) print(res) # [[3, 4], # [7, 8]] x = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) y = paddle.to_tensor([3, 0, 4]) res = paddle.maximum(x, y) print(res) # [[3, 2, 4], # [3, 2, 4]] x = paddle.to_tensor([2, 3, 5], dtype='float32') y = paddle.to_tensor([1, np.nan, np.nan], dtype='float32') res = paddle.maximum(x, y) print(res) # [ 2., nan, nan] x = paddle.to_tensor([5, 3, np.inf], dtype='float32') y = paddle.to_tensor([1, -np.inf, 5], dtype='float32') res = paddle.maximum(x, y) print(res) # [ 5., 3., inf.] """ op_type = 'elementwise_max' axis = -1 act = None if paddle.in_dynamic_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name=op_type) return _elementwise_op(LayerHelper(op_type, **locals())) def minimum(x, y, name=None): """ Compare two tensors and returns a new tensor containing the element-wise minima. The equation is: .. math:: out = min(x, y) **Note**: ``paddle.minimum`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . Args: x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. Examples: .. code-block:: python import numpy as np import paddle x = paddle.to_tensor([[1, 2], [7, 8]]) y = paddle.to_tensor([[3, 4], [5, 6]]) res = paddle.minimum(x, y) print(res) # [[1, 2], # [5, 6]] x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]]) y = paddle.to_tensor([3, 0, 4]) res = paddle.minimum(x, y) print(res) # [[[1, 0, 3], # [1, 0, 3]]] x = paddle.to_tensor([2, 3, 5], dtype='float32') y = paddle.to_tensor([1, np.nan, np.nan], dtype='float32') res = paddle.minimum(x, y) print(res) # [ 1., nan, nan] x = paddle.to_tensor([5, 3, np.inf], dtype='float64') y = paddle.to_tensor([1, -np.inf, 5], dtype='float64') res = paddle.minimum(x, y) print(res) # [ 1., -inf., 5.] """ op_type = 'elementwise_min' axis = -1 act = None if paddle.in_dynamic_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name=op_type) return _elementwise_op(LayerHelper(op_type, **locals())) def fmax(x, y, name=None): """ Compares the elements at the corresponding positions of the two tensors and returns a new tensor containing the maximum value of the element. If one of them is a nan value, the other value is directly returned, if both are nan values, then the first nan value is returned. The equation is: .. math:: out = fmax(x, y) **Note**: ``paddle.fmax`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . Args: x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. Examples: .. code-block:: python import numpy as np import paddle x = paddle.to_tensor([[1, 2], [7, 8]]) y = paddle.to_tensor([[3, 4], [5, 6]]) res = paddle.fmax(x, y) print(res) # [[3, 4], # [7, 8]] x = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) y = paddle.to_tensor([3, 0, 4]) res = paddle.fmax(x, y) print(res) # [[3, 2, 4], # [3, 2, 4]] x = paddle.to_tensor([2, 3, 5], dtype='float32') y = paddle.to_tensor([1, np.nan, np.nan], dtype='float32') res = paddle.fmax(x, y) print(res) # [ 2., 3., 5.] x = paddle.to_tensor([5, 3, np.inf], dtype='float32') y = paddle.to_tensor([1, -np.inf, 5], dtype='float32') res = paddle.fmax(x, y) print(res) # [ 5., 3., inf.] """ op_type = 'elementwise_fmax' axis = -1 act = None if paddle.in_dynamic_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name=op_type) return _elementwise_op(LayerHelper(op_type, **locals())) def fmin(x, y, name=None): """ Compares the elements at the corresponding positions of the two tensors and returns a new tensor containing the minimum value of the element. If one of them is a nan value, the other value is directly returned, if both are nan values, then the first nan value is returned. The equation is: .. math:: out = fmin(x, y) **Note**: ``paddle.fmin`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . Args: x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. Examples: .. code-block:: python import numpy as np import paddle x = paddle.to_tensor([[1, 2], [7, 8]]) y = paddle.to_tensor([[3, 4], [5, 6]]) res = paddle.fmin(x, y) print(res) # [[1, 2], # [5, 6]] x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]]) y = paddle.to_tensor([3, 0, 4]) res = paddle.fmin(x, y) print(res) # [[[1, 0, 3], # [1, 0, 3]]] x = paddle.to_tensor([2, 3, 5], dtype='float32') y = paddle.to_tensor([1, np.nan, np.nan], dtype='float32') res = paddle.fmin(x, y) print(res) # [ 1., 3., 5.] x = paddle.to_tensor([5, 3, np.inf], dtype='float64') y = paddle.to_tensor([1, -np.inf, 5], dtype='float64') res = paddle.fmin(x, y) print(res) # [ 1., -inf., 5.] """ op_type = 'elementwise_fmin' axis = -1 act = None if paddle.in_dynamic_mode(): return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name=op_type) return _elementwise_op(LayerHelper(op_type, **locals())) for func in [ add, multiply ]: proto_dict = {'add': 'elementwise_add', 'multiply': 'elementwise_mul'} op_proto = OpProtoHolder.instance().get_op_proto(proto_dict[func.__name__]) additional_args_lines = [ "name (string, optional): Name of the output. \ Default is None. It's used to print debug info for developers. Details: \ :ref:`api_guide_Name` " ] func.__doc__ = _generate_doc_string_( op_proto, additional_args_lines=additional_args_lines, skip_attrs_set={"x_data_format", "y_data_format", "axis", "use_quantizer", "mkldnn_data_type", "Scale_x", "Scale_y", "Scale_out" }) + """\n""" + str(func.__doc__) def sum(x, axis=None, dtype=None, keepdim=False, name=None): """ Computes the sum of tensor elements over the given dimension. Args: x (Tensor): An N-D Tensor, the data type is bool, float16, float32, float64, int32 or int64. axis (int|list|tuple, optional): The dimensions along which the sum is performed. If :attr:`None`, sum all elements of :attr:`x` and return a Tensor with a single element, otherwise must be in the range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`, the dimension to reduce is :math:`rank + axis[i]`. dtype (str, optional): The dtype of output Tensor. The default value is None, the dtype of output is the same as input Tensor `x`. keepdim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result Tensor will have one fewer dimension than the :attr:`x` unless :attr:`keepdim` is true, default value is False. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: Results of summation operation on the specified axis of input Tensor `x`, if `x.dtype='bool'`, `x.dtype='int32'`, it's data type is `'int64'`, otherwise it's data type is the same as `x`. Raises: TypeError: The type of :attr:`axis` must be int, list or tuple. Examples: .. code-block:: python import paddle # x is a Tensor with following elements: # [[0.2, 0.3, 0.5, 0.9] # [0.1, 0.2, 0.6, 0.7]] # Each example is followed by the corresponding output tensor. x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], [0.1, 0.2, 0.6, 0.7]]) out1 = paddle.sum(x) # [3.5] out2 = paddle.sum(x, axis=0) # [0.3, 0.5, 1.1, 1.6] out3 = paddle.sum(x, axis=-1) # [1.9, 1.6] out4 = paddle.sum(x, axis=1, keepdim=True) # [[1.9], [1.6]] # y is a Tensor with shape [2, 2, 2] and elements as below: # [[[1, 2], [3, 4]], # [[5, 6], [7, 8]]] # Each example is followed by the corresponding output tensor. y = paddle.to_tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) out5 = paddle.sum(y, axis=[1, 2]) # [10, 26] out6 = paddle.sum(y, axis=[0, 1]) # [16, 20] # x is a Tensor with following elements: # [[True, True, True, True] # [False, False, False, False]] # Each example is followed by the corresponding output tensor. x = paddle.to_tensor([[True, True, True, True], [False, False, False, False]]) out7 = paddle.sum(x) # [4] out8 = paddle.sum(x, axis=0) # [1, 1, 1, 1] out9 = paddle.sum(x, axis=1) # [4, 0] """ if axis is not None and not isinstance(axis, (list, tuple)): axis = [axis] if not axis: reduce_all_flag = True else: if len(axis) == len(x.shape): reduce_all_flag = True else: reduce_all_flag = False def get_dtype(x, dtype): if dtype is not None: return (True, dtype) src_type = convert_dtype(x.dtype) if src_type in ['bool','int32', 'int64']: return (True, 'int64') return (False, src_type) dtype_flag, dtype = get_dtype(x, dtype) if paddle.in_dynamic_mode(): axis = axis if axis != None and axis != [] else [0] if dtype_flag: return _C_ops.reduce_sum(x, 'dim', axis, 'keep_dim', keepdim, 'reduce_all', reduce_all_flag, 'in_dtype', x.dtype, 'out_dtype', convert_np_dtype_to_dtype_(dtype)) else: return _C_ops.reduce_sum(x, 'dim', axis, 'keep_dim', keepdim, 'reduce_all', reduce_all_flag) attrs = { 'dim': axis if axis != None and axis != [] and axis != () else [0], 'keep_dim': keepdim, 'reduce_all': reduce_all_flag } if dtype_flag: attrs.update({ 'in_dtype': x.dtype, 'out_dtype': convert_np_dtype_to_dtype_(dtype) }) check_variable_and_dtype( x, 'x', ['bool', 'float16', 'float32', 'float64', 'int16', 'int32', 'int64', 'complex64', 'complex128', u'bool', u'float16', u'float32', u'float64', u'int32', u'int64', u'complex64', u'complex128'], 'sum') check_type(axis, 'axis', (int, list, tuple, type(None)), 'sum') helper = LayerHelper('sum', **locals()) if dtype_flag: out = helper.create_variable_for_type_inference( dtype=convert_np_dtype_to_dtype_(dtype)) else: out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='reduce_sum', inputs={'X': x}, outputs={'Out': out}, attrs=attrs) return out def nansum(x, axis=None, dtype=None, keepdim=False, name=None): """ Computes the sum of tensor elements over the given axis, treating Not a Numbers (NaNs) as zero. Args: x (Tensor): An N-D Tensor, the data type is float32, float64, int32 or int64. axis (int|list|tuple, optional): The dimensions along which the nansum is performed. If :attr:`None`, nansum all elements of :attr:`x` and return a Tensor with a single element, otherwise must be in the range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`, the dimension to reduce is :math:`rank + axis[i]`. dtype (str, optional): The dtype of output Tensor. The default value is None, the dtype of output is the same as input Tensor `x`. keepdim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result Tensor will have one fewer dimension than the :attr:`x` unless :attr:`keepdim` is true, default value is False. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: Results of summation operation on the specified axis of input Tensor `x`, Examples: .. code-block:: python import paddle import numpy as np # x is a Tensor with following elements: # [[nan, 0.3, 0.5, 0.9] # [0.1, 0.2, -nan, 0.7]] # Each example is followed by the corresponding output tensor. x = np.array([[float('nan'), 0.3, 0.5, 0.9], [0.1, 0.2, float('-nan'), 0.7]]).astype(np.float32) x = paddle.to_tensor(x) out1 = paddle.nansum(x) # [2.7] out2 = paddle.nansum(x, axis=0) # [0.1, 0.5, 0.5, 1.6] out3 = paddle.nansum(x, axis=-1) # [1.7, 1.0] out4 = paddle.nansum(x, axis=1, keepdim=True) # [[1.7], [1.0]] # y is a Tensor with shape [2, 2, 2] and elements as below: # [[[1, nan], [3, 4]], # [[5, 6], [-nan, 8]]] # Each example is followed by the corresponding output tensor. y = np.array([[[1, float('nan')], [3, 4]], [[5, 6], [float('-nan'), 8]]]) y = paddle.to_tensor(y) out5 = paddle.nansum(y, axis=[1, 2]) # [8, 19] out6 = paddle.nansum(y, axis=[0, 1]) # [9, 18] """ check_variable_and_dtype( x, 'x', ['float32', 'float64', 'int32', 'int64'], 'nansum') check_type(axis, 'axis', (int, list, tuple, type(None)), 'nansum') zero_tensor = paddle.zeros_like(x) tmp_tensor = paddle.where(isnan(x), zero_tensor, x) return sum(tmp_tensor, axis, dtype, keepdim, name) @templatedoc(op_type="sum") def add_n(inputs, name=None): """ This OP is used to sum one or more Tensor of the input. For example: .. code-block:: text Case 1: Input: input.shape = [2, 3] input = [[1, 2, 3], [4, 5, 6]] Output: output.shape = [2, 3] output = [[1, 2, 3], [4, 5, 6]] Case 2: Input: First input: input1.shape = [2, 3] Input1 = [[1, 2, 3], [4, 5, 6]] The second input: input2.shape = [2, 3] input2 = [[7, 8, 9], [10, 11, 12]] Output: output.shape = [2, 3] output = [[8, 10, 12], [14, 16, 18]] Args: inputs (Tensor|list[Tensor]|tuple[Tensor]): A Tensor or a list/tuple of Tensors. The shape and data type of the list/tuple elements should be consistent. Input can be multi-dimensional Tensor, and data types can be: float32, float64, int32, int64. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor, the sum of input :math:`inputs` , its shape and data types are consistent with :math:`inputs`. Examples: .. code-block:: python import paddle input0 = paddle.to_tensor([[1, 2, 3], [4, 5, 6]], dtype='float32') input1 = paddle.to_tensor([[7, 8, 9], [10, 11, 12]], dtype='float32') output = paddle.add_n([input0, input1]) # [[8., 10., 12.], # [14., 16., 18.]] """ if paddle.in_dynamic_mode(): if isinstance(inputs, Variable): inputs = [inputs] return _C_ops.sum(inputs, 'use_mkldnn', False) helper = LayerHelper('add_n', **locals()) check_type(inputs, 'inputs', (Variable, tuple, list), 'add_n') if isinstance(inputs, list) or isinstance(inputs, tuple): if len(inputs) > 0: for input in inputs: check_variable_and_dtype(input, "inputs", \ ['float32', 'float64', 'int32', 'int64'], 'add_n') else: check_variable_and_dtype(inputs, "inputs", \ ['float32', 'float64', 'int32', 'int64'], 'add_n') out = helper.create_variable_for_type_inference( dtype=helper.input_dtype('inputs')) helper.append_op( type='sum', inputs={'X': inputs}, outputs={'Out': out}, attrs={'use_mkldnn': False}) return out def trunc(input, name=None): ''' This API is used to returns a new tensor with the truncated integer values of input. Args: input (Tensor): The input tensor, it's data type should be int32, int64, float32, float64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor: The output Tensor of trunc. Examples: .. code-block:: python import paddle input = paddle.rand([2,2],'float32') print(input) # Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [[0.02331470, 0.42374918], # [0.79647720, 0.74970269]]) output = paddle.trunc(input) print(output) # Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [[0., 0.], # [0., 0.]])) ''' if paddle.in_dynamic_mode(): if _in_eager_mode(): return _C_ops.final_state_trunc(input) return _C_ops.trunc(input) else: inputs = {"X": input} attrs = {} helper = LayerHelper("trunc", **locals()) check_variable_and_dtype(input, 'X', ['int32', 'int64', 'float32', 'float64'], 'trunc') out = helper.create_variable_for_type_inference(dtype=input.dtype) helper.append_op( type="trunc", inputs=inputs, attrs=attrs, outputs={"Out": out}) return out def mm(input, mat2, name=None): """ Applies matrix multiplication to two tensors. Currently, the input tensors' rank can be any, but when the rank of any inputs is bigger than 3, this two inputs' rank should be equal. Also note that if the raw tensor :math:`x` or :math:`mat2` is rank-1 and nontransposed, the prepended or appended dimension :math:`1` will be removed after matrix multiplication. Args: input (Tensor): The input tensor which is a Tensor. mat2 (Tensor): The input tensor which is a Tensor. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: The product Tensor. :: * example 1: input: [B, ..., M, K], mat2: [B, ..., K, N] out: [B, ..., M, N] * example 2: input: [B, M, K], mat2: [B, K, N] out: [B, M, N] * example 3: input: [B, M, K], mat2: [K, N] out: [B, M, N] * example 4: input: [M, K], mat2: [K, N] out: [M, N] * example 5: input: [B, M, K], mat2: [K] out: [B, M] * example 6: input: [K], mat2: [K] out: [1] Examples: .. code-block:: python import paddle input = paddle.arange(1, 7).reshape((3, 2)).astype('float32') mat2 = paddle.arange(1, 9).reshape((2, 4)).astype('float32') out = paddle.mm(input, mat2) print(out) # [[11., 14., 17., 20.], # [23., 30., 37., 44.], # [35., 46., 57., 68.]]) """ if paddle.in_dynamic_mode(): return _C_ops.matmul_v2(input, mat2) def __check_input(x, y): var_names = {'x': x, 'y': y} for name, val in var_names.items(): check_variable_and_dtype(val, name, ['float16', 'float32', 'float64'], 'mm') x_shape = list(x.shape) y_shape = list(y.shape) if len(x_shape) == 1: x_shape = [1] + x_shape if len(y_shape) == 1: y_shape = y_shape + [1] # check the inner 2 dimensions if x_shape[-1] != y_shape[-2]: if not ((x_shape[-1] == -1) or (y_shape[-2] == -1)): raise ValueError( "After performing an optional transpose, Input X's width should be " "equal to Y's width for multiplication " "prerequisites. But received X's shape: %s, Y's shape: %s\n" % (x_shape, y_shape)) if len(y_shape) > 2 and len(x_shape) > 2: for i, dim_x in enumerate(x_shape[:-2]): # don't check neg shape if dim_x < 0 or y_shape[i] < 0: continue if dim_x != y_shape[i]: raise ValueError( "When the matrix is larger than 2 dimensions, the higher " "dimensional values of the two matrices need to be equal. " "But received x_shape[%d] != y_shape[%d]. X's shape: %s, " "Y's shape: %s.\n" % (i, i, x_shape, y_shape)) __check_input(input, mat2) helper = LayerHelper('mm', **locals()) out = helper.create_variable_for_type_inference(dtype=input.dtype) helper.append_op( type='matmul_v2', inputs={'X': input, 'Y': mat2}, outputs={'Out': out}) return out def addmm(input, x, y, beta=1.0, alpha=1.0, name=None): """ **addmm** This operator is used to perform matrix multiplication for input $x$ and $y$. $input$ is added to the final result. The equation is: .. math:: Out = alpha * x * y + beta * input $Input$, $x$ and $y$ can carry the LoD (Level of Details) information, or not. But the output only shares the LoD information with input $input$. Args: input (Tensor): The input Tensor to be added to the final result. x (Tensor): The first input Tensor for matrix multiplication. y (Tensor): The second input Tensor for matrix multiplication. beta (float): Coefficient of $input$. alpha (float): Coefficient of $x*y$. name (str, optional): Name of the output. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Default is None. Returns: Tensor: The output Tensor of addmm op. Examples: .. code-block:: python import paddle x = paddle.ones([2,2]) y = paddle.ones([2,2]) input = paddle.ones([2,2]) out = paddle.addmm( input=input, x=x, y=y, beta=0.5, alpha=5.0 ) print(out) # [[10.5 10.5] # [10.5 10.5]] """ input_shape = input.shape x_shape = x.shape y_shape = y.shape if not len(input_shape) == len(x_shape) == len(y_shape) == 2: raise ValueError("The dimention of input, x, y should be 2 but receive input's shape: {}, x's shape: {}, y's shape: {}".format(input_shape, x_shape, y_shape)) if input_shape[0] != x_shape[0]: if input_shape[0] != 1: raise ValueError( "When x's dimension[0] is not equal with input's dimension[0], input's dimension[0] must be 1 but got {}".format(input_shape[0])) if input_shape[1] != y_shape[1] and input_shape[1] != 1: raise ValueError( "When y's dimension[1] is not equal with input's dimension[1], input's dimension[1] must be 1 but got {}".format(input_shape[1])) if input_shape[1] != y_shape[1]: if input_shape[1] != 1: raise ValueError( "When y's dimension[1] is not equal with input's dimension[1], input's dimension[1] must be 1 but got {}".format(input_shape[1])) if input_shape[0] != x_shape[0] and input_shape[0] != 1: raise ValueError( "When x's dimension[0] is not equal with input's dimension[0], input's dimension[0] must be 1 but got {}".format(input_shape[0])) if x_shape[1] != y_shape[0]: raise ValueError("The input Variable x's width must be equal with Variable y' height. But received x's shape = {}, y's shape = {}.".format(x_shape, y_shape)) if paddle.in_dynamic_mode(): if _in_eager_mode(): return _C_ops.final_state_addmm( input, x, y, alpha, beta) out = _C_ops.addmm(input, x, y, "Alpha", alpha, "Beta", beta) return out inputs = {'Input': input, "X": x, "Y": y} attrs = {'Alpha': alpha, 'Beta': beta} helper = LayerHelper("addmm", **locals()) check_variable_and_dtype(input, 'Input', ['float32', 'float64'], 'addmm') check_variable_and_dtype(x, 'X', ['float32', 'float64'], 'addmm') check_variable_and_dtype(y, 'Y', ['float32', 'float64'], 'addmm') out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type="addmm", inputs=inputs, attrs=attrs, outputs={"Out": out}) return out def renorm(x, p, axis, max_norm): """ **renorm** This operator is used to calculate the p-norm along the axis, suppose the input-shape on axis dimension has the value of T, then the tensor is split into T parts, the p-norm should be calculated for each part, if the p-norm for part i is larger than max-norm, then each element in part i should be re-normalized at the same scale so that part-i' p-norm equals max-norm exactly, otherwise part-i stays unchanged. Args: x (Tensor): The input Tensor p (float): The power of the norm operation. axis (int): the dimension to slice the tensor. max-norm (float): the maximal norm limit. Returns: Tensor: the renorm Tensor. Examples: .. code-block:: python import paddle input = [[[2.0,2,-2],[3,0.3,3]],[[2,-8,2],[3.1,3.7,3]]] x = paddle.to_tensor(input,dtype='float32') y = paddle.renorm(x, 1.0, 2, 2.05) print(y) # [[[ 0.40594056, 0.29285714, -0.41000000], # [ 0.60891086, 0.04392857, 0.61500001]], # [[ 0.40594056, -1.17142856, 0.41000000], # [ 0.62920785, 0.54178572, 0.61500001]]]) """ input_shape = x.shape check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'renorm') if not axis < len(input_shape): raise ValueError("the axis:{} should be less then the shape's size {}:{}".format(axis,len(input_shape),input_shape)) if not axis >=0: if not axis >= -1 * len(input_shape): raise ValueError("the axis:{} should not be less than -1 * length of input_shape:{}".format(axis,-1 * len(input_shape))) axis = axis + len(input_shape) if paddle.in_dynamic_mode(): out = _C_ops.renorm(x, 'p',p, 'axis',axis, 'max_norm', max_norm) return out inputs = {'X': x} attrs = {'p': p, 'axis': axis, 'max_norm':max_norm} helper = LayerHelper("renorm", **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type="renorm", inputs=inputs, attrs=attrs, outputs={"Out": out}) return out def inner(x, y, name=None): """ Inner product of two input Tensor. Ordinary inner product for 1-D Tensors, in higher dimensions a sum product over the last axes. Args: x (Tensor): An N-D Tensor or a Scalar Tensor. If its not a scalar Tensor, its last dimensions must match y's. y (Tensor): An N-D Tensor or a Scalar Tensor. If its not a scalar Tensor, its last dimensions must match x's. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: The inner-product Tensor, the output shape is x.shape[:-1] + y.shape[:-1]. Examples: .. code-block:: python import paddle x = paddle.arange(1, 7).reshape((2, 3)).astype('float32') y = paddle.arange(1, 10).reshape((3, 3)).astype('float32') out = paddle.inner(x, y) print(out) # ([[14, 32, 50], # [32, 77, 122]]) """ if x.size == 1 or y.size == 1: return multiply(x, y) else: xshape = x.shape yshape = y.shape dstshape = list(xshape[:-1])+list(yshape[:-1]) if len(dstshape)==0: dstshape = [1] nx = x.reshape((-1, xshape[-1])) ny = y.reshape((-1, yshape[-1])) if paddle.in_dynamic_mode(): return _C_ops.matmul_v2(nx, ny.T).reshape(dstshape) def __check_input(x, y): var_names = {'x': x, 'y': y} for name, val in var_names.items(): check_variable_and_dtype(val, name, ['float16', 'float32', 'float64'], 'inner') x_shape = list(xshape) y_shape = list(yshape) # check the inner 2 dimensions if x_shape[-1] != y_shape[-1]: if not ((x_shape[-1] == -1) or (y_shape[-1] == -1)): raise ValueError( "After performing an optional transpose, Input X's last dim should be " "equal to Y's last dim for multiplication " "prerequisites. But received X's shape: %s, Y's shape: %s\n" % (x_shape, y_shape)) __check_input(nx, ny) helper = LayerHelper('inner', **locals()) out = helper.create_variable_for_type_inference(dtype=nx.dtype) helper.append_op( type='matmul_v2', inputs={'X': nx, 'Y': ny.T}, outputs={'Out': out}) return out.reshape(dstshape) def outer(x, y, name=None): """ Outer product of two Tensors. Input is flattened if not already 1-dimensional. Args: x (Tensor): An N-D Tensor or a Scalar Tensor. y (Tensor): An N-D Tensor or a Scalar Tensor. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: The outer-product Tensor. Examples: .. code-block:: python import paddle x = paddle.arange(1, 4).astype('float32') y = paddle.arange(1, 6).astype('float32') out = paddle.outer(x, y) print(out) # ([[1, 2, 3, 4, 5], # [2, 4, 6, 8, 10], # [3, 6, 9, 12, 15]]) """ nx = x.reshape((-1, 1)) ny = y.reshape((1, -1)) if paddle.in_dynamic_mode(): return _C_ops.matmul_v2(nx, ny) def __check_input(x, y): var_names = {'x': x, 'y': y} for name, val in var_names.items(): check_variable_and_dtype(val, name, ['float16', 'float32', 'float64'], 'inner') __check_input(nx, ny) helper = LayerHelper('outer', **locals()) out = helper.create_variable_for_type_inference(dtype=nx.dtype) helper.append_op( type='matmul_v2', inputs={'X': nx, 'Y': ny}, outputs={'Out': out}) return out def logsumexp(x, axis=None, keepdim=False, name=None): r""" This OP calculates the log of the sum of exponentials of ``x`` along ``axis`` . .. math:: logsumexp(x) = \\log\\sum exp(x) Args: x (Tensor): The input Tensor with data type float32 or float64, which have no more than 4 dimensions. axis (int|list|tuple, optional): The axis along which to perform logsumexp calculations. ``axis`` should be int, list(int) or tuple(int). If ``axis`` is a list/tuple of dimension(s), logsumexp is calculated along all element(s) of ``axis`` . ``axis`` or element(s) of ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` . If ``axis`` or element(s) of ``axis`` is less than 0, it works the same way as :math:`axis + D` . If ``axis`` is None, logsumexp is calculated along all elements of ``x``. Default is None. keepdim (bool, optional): Whether to reserve the reduced dimension(s) in the output Tensor. If ``keep_dim`` is True, the dimensions of the output Tensor is the same as ``x`` except in the reduced dimensions(it is of size 1 in this case). Otherwise, the shape of the output Tensor is squeezed in ``axis`` . Default is False. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor, results of logsumexp along ``axis`` of ``x``, with the same data type as ``x``. Examples: .. code-block:: python import paddle x = paddle.to_tensor([[-1.5, 0., 2.], [3., 1.2, -2.4]]) out1 = paddle.logsumexp(x) # [3.4691226] out2 = paddle.logsumexp(x, 1) # [2.15317821, 3.15684602] """ if isinstance(axis, int): axis = [axis] reduce_all = True if axis is None \ or len(axis)==0 \ or len(axis) == len(x.shape) else False if axis is None or len(axis) == 0: axis = [0] if paddle.in_dynamic_mode(): return _C_ops.logsumexp(x, 'axis', axis, 'keepdim', keepdim, 'reduce_all', reduce_all) check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'logsumexp') helper = LayerHelper('logsumexp', **locals()) attrs = {'axis': axis, 'keepdim': keepdim, 'reduce_all':reduce_all} out = helper.create_variable_for_type_inference(x.dtype) helper.append_op( type='logsumexp', inputs={'X': x}, outputs={'Out': out}, attrs=attrs) return out def inverse(x, name=None): """ Takes the inverse of the square matrix. A square matrix is a matrix with the same number of rows and columns. The input can be a square matrix (2-D Tensor) or batches of square matrices. Args: x (Tensor): The input tensor. The last two dimensions should be equal. When the number of dimensions is greater than 2, it is treated as batches of square matrix. The data type can be float32 and float64. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: A Tensor holds the inverse of x. The shape and data type is the same as x. Examples: .. code-block:: python import paddle mat = paddle.to_tensor([[2, 0], [0, 2]], dtype='float32') inv = paddle.inverse(mat) print(inv) # [[0.5, 0], [0, 0.5]] """ if paddle.in_dynamic_mode(): return _C_ops.inverse(x) def _check_input(x): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'inverse') if len(x.shape) < 2: raise ValueError( "The input of inverse is expected to be a Tensor whose number " "of dimensions is no less than 2. But reviced: %d, " "x's shape: %s." % (len(x.shape), x.shape)) _check_input(x) helper = LayerHelper('inverse', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='inverse', inputs={'Input': [x] }, outputs={'Output': [out]}) return out def _get_reduce_all_value(axis): """ Internal function for max, min, amax and amin. It computes the attribute reduce_all value based on axis. """ if axis is not None and not isinstance(axis, list): if isinstance(axis, tuple): axis = list(axis) elif isinstance(axis, int): axis= [axis] else: raise TypeError( "The type of axis must be int, list or tuple, but received {}".format(type(axis))) reduce_all = True if axis == None or axis == [] else False axis = axis if axis != None and axis != [] else [0] return reduce_all, axis def max(x, axis=None, keepdim=False, name=None): """ Computes the maximum of tensor elements over the given axis. Note: The difference between max and amax is: If there are multiple maximum elements, amax evenly distributes gradient between these equal values, while max propagates gradient to all of them. Args: x(Tensor): A tensor, the data type is float32, float64, int32, int64. axis(int|list|tuple, optional): The axis along which the maximum is computed. If :attr:`None`, compute the maximum over all elements of `x` and return a Tensor with a single element, otherwise must be in the range :math:`[-x.ndim(x), x.ndim(x))`. If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`. keepdim(bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the `x` unless :attr:`keepdim` is true, default value is False. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor, results of maximum on the specified axis of input tensor, it's data type is the same as `x`. Examples: .. code-block:: python import paddle # data_x is a Tensor with shape [2, 4] # the axis is a int element x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], [0.1, 0.2, 0.6, 0.7]], dtype='float64', stop_gradient=False) result1 = paddle.max(x) result1.backward() print(result1, x.grad) #[0.9], [[0., 0., 0., 1.], [0., 0., 0., 0.]] x.clear_grad() result2 = paddle.max(x, axis=0) result2.backward() print(result2, x.grad) #[0.2, 0.3, 0.6, 0.9], [[1., 1., 0., 1.], [0., 0., 1., 0.]] x.clear_grad() result3 = paddle.max(x, axis=-1) result3.backward() print(result3, x.grad) #[0.9, 0.7], [[0., 0., 0., 1.], [0., 0., 0., 1.]] x.clear_grad() result4 = paddle.max(x, axis=1, keepdim=True) result4.backward() print(result4, x.grad) #[[0.9], [0.7]], [[0., 0., 0., 1.], [0., 0., 0., 1.]] # data_y is a Tensor with shape [2, 2, 2] # the axis is list y = paddle.to_tensor([[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]], dtype='float64', stop_gradient=False) result5 = paddle.max(y, axis=[1, 2]) result5.backward() print(result5, y.grad) #[4., 8.], [[[0., 0.], [0., 1.]], [[0., 0.], [0., 1.]]] y.clear_grad() result6 = paddle.max(y, axis=[0, 1]) result6.backward() print(result6, y.grad) #[7., 8.], [[[0., 0.], [0., 0.]], [[0., 0.], [1., 1.]]] """ reduce_all, axis = _get_reduce_all_value(axis) if paddle.in_dynamic_mode(): return _C_ops.reduce_max(x, 'dim', axis, 'keep_dim', keepdim, 'reduce_all', reduce_all) helper = LayerHelper('max', **locals()) check_variable_and_dtype( x, 'x', ['float32', 'float64', 'int32', 'int64'], 'max') out = helper.create_variable_for_type_inference( dtype=x.dtype) helper.append_op( type='reduce_max', inputs={'X': x}, outputs={'Out': out}, attrs={ 'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all }) return out def min(x, axis=None, keepdim=False, name=None): """ Computes the minimum of tensor elements over the given axis Note: The difference between min and amin is: If there are multiple minimum elements, amin evenly distributes gradient between these equal values, while min propagates gradient to all of them. Args: x(Tensor): A tensor, the data type is float32, float64, int32, int64. axis(int|list|tuple, optional): The axis along which the minimum is computed. If :attr:`None`, compute the minimum over all elements of `x` and return a Tensor with a single element, otherwise must be in the range :math:`[-x.ndim, x.ndim)`. If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`. keepdim(bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the `x` unless :attr:`keepdim` is true, default value is False. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor, results of minimum on the specified axis of input tensor, it's data type is the same as input's Tensor. Examples: .. code-block:: python import paddle # data_x is a Tensor with shape [2, 4] # the axis is a int element x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], [0.1, 0.2, 0.6, 0.7]], dtype='float64', stop_gradient=False) result1 = paddle.min(x) result1.backward() print(result1, x.grad) #[0.1], [[0., 0., 0., 0.], [1., 0., 0., 0.]] x.clear_grad() result2 = paddle.min(x, axis=0) result2.backward() print(result2, x.grad) #[0.1, 0.2, 0.5, 0.7], [[0., 0., 1., 0.], [1., 1., 0., 1.]] x.clear_grad() result3 = paddle.min(x, axis=-1) result3.backward() print(result3, x.grad) #[0.2, 0.1], [[1., 0., 0., 0.], [1., 0., 0., 0.]] x.clear_grad() result4 = paddle.min(x, axis=1, keepdim=True) result4.backward() print(result4, x.grad) #[[0.2], [0.1]], [[1., 0., 0., 0.], [1., 0., 0., 0.]] # data_y is a Tensor with shape [2, 2, 2] # the axis is list y = paddle.to_tensor([[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]], dtype='float64', stop_gradient=False) result5 = paddle.min(y, axis=[1, 2]) result5.backward() print(result5, y.grad) #[1., 5.], [[[1., 0.], [0., 0.]], [[1., 0.], [0., 0.]]] y.clear_grad() result6 = paddle.min(y, axis=[0, 1]) result6.backward() print(result6, y.grad) #[1., 2.], [[[1., 1.], [0., 0.]], [[0., 0.], [0., 0.]]] """ reduce_all, axis = _get_reduce_all_value(axis) if paddle.in_dynamic_mode(): return _C_ops.reduce_min(x, 'dim', axis, 'keep_dim', keepdim, 'reduce_all', reduce_all) helper = LayerHelper('min', **locals()) check_variable_and_dtype( x, 'x', ['float32', 'float64', 'int32', 'int64'], 'min') out = helper.create_variable_for_type_inference( dtype=x.dtype) helper.append_op( type='reduce_min', inputs={'X': x}, outputs={'Out': out}, attrs={ 'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all }) return out def amax(x, axis=None, keepdim=False, name=None): """ Computes the maximum of tensor elements over the given axis. Note: The difference between max and amax is: If there are multiple maximum elements, amax evenly distributes gradient between these equal values, while max propagates gradient to all of them. Args: x(Tensor): A tensor, the data type is float32, float64, int32, int64, the dimension is no more than 4. axis(int|list|tuple, optional): The axis along which the maximum is computed. If :attr:`None`, compute the maximum over all elements of `x` and return a Tensor with a single element, otherwise must be in the range :math:`[-x.ndim(x), x.ndim(x))`. If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`. keepdim(bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the `x` unless :attr:`keepdim` is true, default value is False. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor, results of maximum on the specified axis of input tensor, it's data type is the same as `x`. Examples: .. code-block:: python import paddle # data_x is a Tensor with shape [2, 4] with multiple maximum elements # the axis is a int element x = paddle.to_tensor([[0.1, 0.9, 0.9, 0.9], [0.9, 0.9, 0.6, 0.7]], dtype='float64', stop_gradient=False) # There are 5 maximum elements: # 1) amax evenly distributes gradient between these equal values, # thus the corresponding gradients are 1/5=0.2; # 2) while max propagates gradient to all of them, # thus the corresponding gradient are 1. result1 = paddle.amax(x) result1.backward() print(result1, x.grad) #[0.9], [[0., 0.2, 0.2, 0.2], [0.2, 0.2, 0., 0.]] x.clear_grad() result1_max = paddle.max(x) result1_max.backward() print(result1_max, x.grad) #[0.9], [[0., 1.0, 1.0, 1.0], [1.0, 1.0, 0., 0.]] ############################### x.clear_grad() result2 = paddle.amax(x, axis=0) result2.backward() print(result2, x.grad) #[0.9, 0.9, 0.9, 0.9], [[0., 0.5, 1., 1.], [1., 0.5, 0., 0.]] x.clear_grad() result3 = paddle.amax(x, axis=-1) result3.backward() print(result3, x.grad) #[0.9, 0.9], [[0., 0.3333, 0.3333, 0.3333], [0.5, 0.5, 0., 0.]] x.clear_grad() result4 = paddle.amax(x, axis=1, keepdim=True) result4.backward() print(result4, x.grad) #[[0.9], [0.9]], [[0., 0.3333, 0.3333, 0.3333.], [0.5, 0.5, 0., 0.]] # data_y is a Tensor with shape [2, 2, 2] # the axis is list y = paddle.to_tensor([[[0.1, 0.9], [0.9, 0.9]], [[0.9, 0.9], [0.6, 0.7]]], dtype='float64', stop_gradient=False) result5 = paddle.amax(y, axis=[1, 2]) result5.backward() print(result5, y.grad) #[0.9., 0.9], [[[0., 0.3333], [0.3333, 0.3333]], [[0.5, 0.5], [0., 1.]]] y.clear_grad() result6 = paddle.amax(y, axis=[0, 1]) result6.backward() print(result6, y.grad) #[0.9., 0.9], [[[0., 0.3333], [0.5, 0.3333]], [[0.5, 0.3333], [1., 1.]]] """ reduce_all, axis = _get_reduce_all_value(axis) if paddle.in_dynamic_mode(): return _C_ops.reduce_amax(x, 'dim', axis, 'keep_dim', keepdim, 'reduce_all', reduce_all) helper = LayerHelper('amax', **locals()) check_variable_and_dtype( x, 'x', ['float32', 'float64', 'int32', 'int64'], 'amax') out = helper.create_variable_for_type_inference( dtype=x.dtype) helper.append_op( type='reduce_amax', inputs={'X': x}, outputs={'Out': out}, attrs={ 'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all }) return out def amin(x, axis=None, keepdim=False, name=None): """ Computes the minimum of tensor elements over the given axis Note: The difference between min and amin is: If there are multiple minimum elements, amin evenly distributes gradient between these equal values, while min propagates gradient to all of them. Args: x(Tensor): A tensor, the data type is float32, float64, int32, int64, the dimension is no more than 4. axis(int|list|tuple, optional): The axis along which the minimum is computed. If :attr:`None`, compute the minimum over all elements of `x` and return a Tensor with a single element, otherwise must be in the range :math:`[-x.ndim, x.ndim)`. If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`. keepdim(bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the `x` unless :attr:`keepdim` is true, default value is False. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor, results of minimum on the specified axis of input tensor, it's data type is the same as input's Tensor. Examples: .. code-block:: python import paddle # data_x is a Tensor with shape [2, 4] with multiple minimum elements # the axis is a int element x = paddle.to_tensor([[0.2, 0.1, 0.1, 0.1], [0.1, 0.1, 0.6, 0.7]], dtype='float64', stop_gradient=False) # There are 5 minimum elements: # 1) amin evenly distributes gradient between these equal values, # thus the corresponding gradients are 1/5=0.2; # 2) while min propagates gradient to all of them, # thus the corresponding gradient are 1. result1 = paddle.amin(x) result1.backward() print(result1, x.grad) #[0.1], [[0., 0.2, 0.2, 0.2], [0.2, 0.2, 0., 0.]] x.clear_grad() result1_min = paddle.min(x) result1_min.backward() print(result1_min, x.grad) #[0.1], [[0., 1.0, 1.0, 1.0], [1.0, 1.0, 0., 0.]] ############################### x.clear_grad() result2 = paddle.amin(x, axis=0) result2.backward() print(result2, x.grad) #[0.1, 0.1, 0.1, 0.1], [[0., 0.5, 1., 1.], [1., 0.5, 0., 0.]] x.clear_grad() result3 = paddle.amin(x, axis=-1) result3.backward() print(result3, x.grad) #[0.1, 0.1], [[0., 0.3333, 0.3333, 0.3333], [0.5, 0.5, 0., 0.]] x.clear_grad() result4 = paddle.amin(x, axis=1, keepdim=True) result4.backward() print(result4, x.grad) #[[0.1], [0.1]], [[0., 0.3333, 0.3333, 0.3333.], [0.5, 0.5, 0., 0.]] # data_y is a Tensor with shape [2, 2, 2] # the axis is list y = paddle.to_tensor([[[0.2, 0.1], [0.1, 0.1]], [[0.1, 0.1], [0.6, 0.7]]], dtype='float64', stop_gradient=False) result5 = paddle.amin(y, axis=[1, 2]) result5.backward() print(result5, y.grad) #[0.1., 0.1], [[[0., 0.3333], [0.3333, 0.3333]], [[0.5, 0.5], [0., 1.]]] y.clear_grad() result6 = paddle.amin(y, axis=[0, 1]) result6.backward() print(result6, y.grad) #[0.1., 0.1], [[[0., 0.3333], [0.5, 0.3333]], [[0.5, 0.3333], [1., 1.]]] """ reduce_all, axis = _get_reduce_all_value(axis) if paddle.in_dynamic_mode(): return _C_ops.reduce_amin(x, 'dim', axis, 'keep_dim', keepdim, 'reduce_all', reduce_all) helper = LayerHelper('amin', **locals()) check_variable_and_dtype( x, 'x', ['float32', 'float64', 'int32', 'int64'], 'amin') out = helper.create_variable_for_type_inference( dtype=x.dtype) helper.append_op( type='reduce_amin', inputs={'X': x}, outputs={'Out': out}, attrs={ 'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all }) return out def log1p(x, name=None): r""" Calculates the natural log of the given input tensor, element-wise. .. math:: Out = \\ln(x+1) Args: x (Tensor): Input Tensor. Must be one of the following types: float32, float64. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor, the natural log of the input Tensor computed element-wise. Examples: .. code-block:: python import paddle data = paddle.to_tensor([[0], [1]], dtype='float32') res = paddle.log1p(data) # [[0.], [0.6931472]] """ if paddle.in_dynamic_mode(): return _C_ops.log1p(x) check_variable_and_dtype(x, 'x', ['float32', 'float64'], "log1p") inputs = {'X': [x]} helper = LayerHelper('log1p', **locals()) dtype = helper.input_dtype(input_param_name='x') out = helper.create_variable_for_type_inference(dtype) helper.append_op(type="log1p", inputs={"X": x}, outputs={"Out": out}) return out def log2(x, name=None): r""" Calculates the log to the base 2 of the given input tensor, element-wise. .. math:: Out = \\log_2x Args: x (Tensor): Input tensor must be one of the following types: float32, float64. name (str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: The log to the base 2 of the input Tensor computed element-wise. Examples: .. code-block:: python import paddle # example 1: x is a float x_i = paddle.to_tensor([[1.0], [2.0]]) res = paddle.log2(x_i) # [[0.], [1.0]] # example 2: x is float32 x_i = paddle.full(shape=[1], fill_value=2, dtype='float32') paddle.to_tensor(x_i) res = paddle.log2(x_i) print(res) # [1.0] # example 3: x is float64 x_i = paddle.full(shape=[1], fill_value=2, dtype='float64') paddle.to_tensor(x_i) res = paddle.log2(x_i) print(res) # [1.0] """ if paddle.in_dynamic_mode(): return _C_ops.log2(x) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], "log2") inputs = {'X': [x]} helper = LayerHelper('log2', **locals()) dtype = helper.input_dtype(input_param_name='x') out = helper.create_variable_for_type_inference(dtype) helper.append_op(type="log2", inputs={"X": x}, outputs={"Out": out}) return out def log10(x, name=None): r""" Calculates the log to the base 10 of the given input tensor, element-wise. .. math:: Out = \\log_10_x Args: x (Tensor): Input tensor must be one of the following types: float32, float64. name (str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: The log to the base 10 of the input Tensor computed element-wise. Examples: .. code-block:: python import paddle # example 1: x is a float x_i = paddle.to_tensor([[1.0], [10.0]]) res = paddle.log10(x_i) # [[0.], [1.0]] # example 2: x is float32 x_i = paddle.full(shape=[1], fill_value=10, dtype='float32') paddle.to_tensor(x_i) res = paddle.log10(x_i) print(res) # [1.0] # example 3: x is float64 x_i = paddle.full(shape=[1], fill_value=10, dtype='float64') paddle.to_tensor(x_i) res = paddle.log10(x_i) print(res) # [1.0] """ if paddle.in_dynamic_mode(): return _C_ops.log10(x) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], "log10") inputs = {'X': [x]} helper = LayerHelper('log10', **locals()) dtype = helper.input_dtype(input_param_name='x') out = helper.create_variable_for_type_inference(dtype) helper.append_op(type="log10", inputs={"X": x}, outputs={"Out": out}) return out def clip(x, min=None, max=None, name=None): """ This operator clip all elements in input into the range [ min, max ] and return a resulting tensor as the following equation: .. math:: Out = MIN(MAX(x, min), max) Args: x (Tensor): An N-D Tensor with data type float32, float64, int32 or int64. min (float|int|Tensor): The lower bound with type ``float`` , ``int`` or a ``Tensor`` with shape [1] and type ``int32``, ``float32``, ``float64``. max (float|int|Tensor): The upper bound with type ``float``, ``int`` or a ``Tensor`` with shape [1] and type ``int32``, ``float32``, ``float64``. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor: A Tensor with the same data type and data shape as input. Examples: .. code-block:: python import paddle x1 = paddle.to_tensor([[1.2, 3.5], [4.5, 6.4]], 'float32') out1 = paddle.clip(x1, min=3.5, max=5.0) out2 = paddle.clip(x1, min=2.5) print(out1) # [[3.5, 3.5] # [4.5, 5.0]] print(out2) # [[2.5, 3.5] # [[4.5, 6.4] """ x_dtype = str(x.dtype) if x_dtype == 'paddle.int32': min_ = np.iinfo(np.int32).min max_ = np.iinfo(np.int32).max - 2**7 elif x_dtype == 'paddle.int64': min_ = np.iinfo(np.int64).min max_ = np.iinfo(np.int64).max - 2**39 else: min_ = float(np.finfo(np.float32).min) max_ = float(np.finfo(np.float32).max) if paddle.in_dynamic_mode(): if isinstance(min, Variable): min = min.numpy().item(0) if isinstance(max, Variable): max = max.numpy().item(0) min = min_ if min is None else min max = max_ if max is None else max return _C_ops.clip(x, "min", min, "max", max) if min is not None: check_type(min, 'min', (float, int, Variable), 'clip') if isinstance(min, Variable): check_dtype(min.dtype, 'min', ['float32', 'float64', 'int32'], 'clip', '(When the type of min in clip is Variable.)') if max is not None: check_type(max, 'max', (float, int, Variable), 'clip') if isinstance(max, Variable): check_dtype(max.dtype, 'max', ['float32', 'float64', 'int32'], 'clip', '(When the type of max in clip is Variable.)') check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], 'clip') inputs = {'X': x} attrs = {'min': min_, 'max': max_} if isinstance(min, Variable): min.stop_gradient = True inputs['Min'] = min elif min is not None: attrs['min'] = min if isinstance(max, Variable): max.stop_gradient = True inputs['Max'] = max elif max is not None: attrs['max'] = max helper = LayerHelper('clip', **locals()) output = helper.create_variable_for_type_inference( dtype=helper.input_dtype('x')) helper.append_op( type='clip', inputs=inputs, outputs={'Out': [output]}, attrs=attrs) return output @inplace_apis_in_dygraph_only def clip_(x, min=None, max=None, name=None): """ Inplace version of ``clip`` API, the output Tensor will be inplaced with input ``x``. Please refer to :ref:`api_tensor_clip`. """ fmin = float(np.finfo(np.float32).min) fmax = float(np.finfo(np.float32).max) if isinstance(min, Variable): min = min.numpy().item(0) if isinstance(max, Variable): max = max.numpy().item(0) min = fmin if min is None else min max = fmax if max is None else max return _C_ops.clip_(x, "min", min, "max", max) def trace(x, offset=0, axis1=0, axis2=1, name=None): """ **trace** This OP computes the sum along diagonals of the input tensor x. If ``x`` is 2D, returns the sum of diagonal. If ``x`` has larger dimensions, then returns an tensor of diagonals sum, diagonals be taken from the 2D planes specified by axis1 and axis2. By default, the 2D planes formed by the first and second axes of the input tensor x. The argument ``offset`` determines where diagonals are taken from input tensor x: - If offset = 0, it is the main diagonal. - If offset > 0, it is above the main diagonal. - If offset < 0, it is below the main diagonal. - Note that if offset is out of input's shape indicated by axis1 and axis2, 0 will be returned. Args: x(Tensor): The input tensor x. Must be at least 2-dimensional. The input data type should be float32, float64, int32, int64. offset(int, optional): Which diagonals in input tensor x will be taken. Default: 0 (main diagonals). axis1(int, optional): The first axis with respect to take diagonal. Default: 0. axis2(int, optional): The second axis with respect to take diagonal. Default: 1. name (str, optional): Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Default: None. Returns: Tensor: the output data type is the same as input data type. Examples: .. code-block:: python import paddle case1 = paddle.randn([2, 3]) case2 = paddle.randn([3, 10, 10]) case3 = paddle.randn([3, 10, 5, 10]) data1 = paddle.trace(case1) # data1.shape = [1] data2 = paddle.trace(case2, offset=1, axis1=1, axis2=2) # data2.shape = [3] data3 = paddle.trace(case3, offset=-3, axis1=1, axis2=-1) # data2.shape = [3, 5] """ def __check_input(input, offset, dim1, dim2): check_dtype(x.dtype, 'Input', ['int32', 'int64', 'float16', 'float32', 'float64'], 'trace') input_shape = list(x.shape) assert len(input_shape) >= 2, \ "The x must be at least 2-dimensional, " \ "But received Input x's dimensional: %s.\n" % \ len(input_shape) axis1_ = axis1 if axis1 >= 0 else len(input_shape) + axis1 axis2_ = axis2 if axis2 >= 0 else len(input_shape) + axis2 assert ((0 <= axis1_) and (axis1_ < len(input_shape))), \ "The argument axis1 is out of range (expected to be in range of [%d, %d], but got %d).\n" \ % (-(len(input_shape)), len(input_shape) - 1, axis1) assert ((0 <= axis2_) and (axis2_ < len(input_shape))), \ "The argument axis2 is out of range (expected to be in range of [%d, %d], but got %d).\n" \ % (-(len(input_shape)), len(input_shape) - 1, axis2) assert axis1_ != axis2_, \ "axis1 and axis2 cannot be the same axis." \ "But received axis1 = %d, axis2 = %d\n"%(axis1, axis2) __check_input(input, offset, axis1, axis2) if paddle.in_dynamic_mode(): return _C_ops.trace(x, 'offset', offset, 'axis1', axis1, 'axis2', axis2) inputs = {'Input': [x]} attrs = {'offset': offset, 'axis1': axis1, 'axis2': axis2} helper = LayerHelper('trace', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='trace', inputs={'Input': [x]}, attrs={'offset': offset, 'axis1': axis1, 'axis2': axis2}, outputs={'Out': [out]}) return out def diagonal(x, offset=0, axis1=0, axis2=1, name=None): """ This OP computes the diagonals of the input tensor x. If ``x`` is 2D, returns the diagonal. If ``x`` has larger dimensions, diagonals be taken from the 2D planes specified by axis1 and axis2. By default, the 2D planes formed by the first and second axis of the input tensor x. The argument ``offset`` determines where diagonals are taken from input tensor x: - If offset = 0, it is the main diagonal. - If offset > 0, it is above the main diagonal. - If offset < 0, it is below the main diagonal. Args: x(Tensor): The input tensor x. Must be at least 2-dimensional. The input data type should be bool, int32, int64, float16, float32, float64. offset(int, optional): Which diagonals in input tensor x will be taken. Default: 0 (main diagonals). axis1(int, optional): The first axis with respect to take diagonal. Default: 0. axis2(int, optional): The second axis with respect to take diagonal. Default: 1. name (str, optional): Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Default: None. Returns: Tensor: a partial view of input tensor in specify two dimensions, the output data type is the same as input data type. Examples: .. code-block:: python import paddle x = paddle.rand([2,2,3],'float32') print(x) # Tensor(shape=[2, 2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [[[0.45661032, 0.03751532, 0.90191704], # [0.43760979, 0.86177313, 0.65221709]], # [[0.17020577, 0.00259554, 0.28954273], # [0.51795638, 0.27325270, 0.18117726]]]) out1 = paddle.diagonal(x) print(out1) #Tensor(shape=[3, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [[0.45661032, 0.51795638], # [0.03751532, 0.27325270], # [0.90191704, 0.18117726]]) out2 = paddle.diagonal(x, offset=0, axis1=2, axis2=1) print(out2) #Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [[0.45661032, 0.86177313], # [0.17020577, 0.27325270]]) out3 = paddle.diagonal(x, offset=1, axis1=0, axis2=1) print(out3) #Tensor(shape=[3, 1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [[0.43760979], # [0.86177313], # [0.65221709]]) out4 = paddle.diagonal(x, offset=0, axis1=1, axis2=2) print(out4) #Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [[0.45661032, 0.86177313], # [0.17020577, 0.27325270]]) """ if paddle.in_dynamic_mode(): if _in_eager_mode(): return _C_ops.final_state_diagonal(x, offset, axis1, axis2) return _C_ops.diagonal(x, 'offset', offset, 'axis1', axis1, 'axis2', axis2) def __check_input(input, offset, dim1, dim2): check_dtype(x.dtype, 'Input', ['bool', 'int32', 'int64', 'float16', 'float32', 'float64'], 'diagonal') input_shape = list(x.shape) assert len(input_shape) >= 2, \ "The x must be at least 2-dimensional, " \ "But received Input x's dimensional: %s.\n" % \ len(input_shape) axis1_ = axis1 if axis1 >= 0 else len(input_shape) + axis1 axis2_ = axis2 if axis2 >= 0 else len(input_shape) + axis2 assert axis1_ < len(input_shape), \ "The argument axis1 is out of range (expected to be in range of [%d, %d], but got %d).\n" \ % (-(len(input_shape)), len(input_shape) - 1, axis1) assert axis2_ < len(input_shape), \ "The argument axis2 is out of range (expected to be in range of [%d, %d], but got %d).\n" \ % (-(len(input_shape)), len(input_shape) - 1, axis2) assert axis1_ != axis2_, \ "axis1 and axis2 cannot be the same axis." \ "But received axis1 = %d, axis2 = %d\n"%(axis1, axis2) __check_input(input, offset, axis1, axis2) helper = LayerHelper('diagonal', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='diagonal', inputs={'Input': [x]}, attrs={'offset': offset, 'axis1': axis1, 'axis2': axis2}, outputs={'Out': [out]}) return out @templatedoc(op_type="kron") def kron(x, y, name=None): """ ${comment} Args: x (Tensor): the fist operand of kron op, data type: float16, float32, float64, int32 or int64. y (Tensor): the second operand of kron op, data type: float16, float32, float64, int32 or int64. Its data type should be the same with x. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor: The output of kron op, data type: float16, float32, float64, int32 or int64. Its data is the same with x. Examples: .. code-block:: python import paddle x = paddle.to_tensor([[1, 2], [3, 4]], dtype='int64') y = paddle.to_tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype='int64') out = paddle.kron(x, y) print(out) # [[1, 2, 3, 2, 4, 6], # [ 4, 5, 6, 8, 10, 12], # [ 7, 8, 9, 14, 16, 18], # [ 3, 6, 9, 4, 8, 12], # [12, 15, 18, 16, 20, 24], # [21, 24, 27, 28, 32, 36]]) """ if paddle.in_dynamic_mode(): return _C_ops.kron(x, y) helper = LayerHelper('kron', **locals()) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64'], 'kron') check_variable_and_dtype(y, 'y', ['float16', 'float32', 'float64', 'int32', 'int64'], 'kron') out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op(type="kron", inputs={"X": x, "Y": y}, outputs={"Out": out}) return out def cumsum(x, axis=None, dtype=None, name=None): """ The cumulative sum of the elements along a given axis. **Note**: The first element of the result is the same of the first element of the input. Args: x (Tensor): The input tensor needed to be cumsumed. axis (int, optional): The dimension to accumulate along. -1 means the last dimension. The default (None) is to compute the cumsum over the flattened array. dtype (str, optional): The data type of the output tensor, can be float32, float64, int32, int64. If specified, the input tensor is casted to dtype before the operation is performed. This is useful for preventing data type overflows. The default value is None. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor, the result of cumsum operator. Examples: .. code-block:: python import paddle data = paddle.arange(12) data = paddle.reshape(data, (3, 4)) y = paddle.cumsum(data) # [ 0 1 3 6 10 15 21 28 36 45 55 66] y = paddle.cumsum(data, axis=0) # [[ 0 1 2 3] # [ 4 6 8 10] # [12 15 18 21]] y = paddle.cumsum(data, axis=-1) # [[ 0 1 3 6] # [ 4 9 15 22] # [ 8 17 27 38]] y = paddle.cumsum(data, dtype='float64') print(y.dtype) # VarType.FP64 """ if axis is None: flatten = True else: flatten = False if dtype is not None and x.dtype != convert_np_dtype_to_dtype_(dtype): x = cast(x, dtype) if paddle.in_dynamic_mode(): if axis is None: return _C_ops.cumsum(x, 'flatten', flatten) else: return _C_ops.cumsum(x, 'axis', axis, 'flatten', flatten) check_type(x, 'x', (Variable), 'cumsum') locals_var = locals().copy() kwargs = dict() for name, val in locals_var.items(): if val is not None: kwargs[name] = val _cum_sum_ = generate_layer_fn('cumsum') return _cum_sum_(**kwargs) def cumprod(x, dim=None, dtype=None, name=None): """ Compute the cumulative product of the input tensor x along a given dimension dim. **Note**: The first element of the result is the same as the first element of the input. Args: x (Tensor): the input tensor need to be cumproded. dim (int): the dimension along which the input tensor will be accumulated. It need to be in the range of [-x.rank, x.rank), where x.rank means the dimensions of the input tensor x and -1 means the last dimension. dtype (str, optional): The data type of the output tensor, can be float32, float64, int32, int64, complex64, complex128. If specified, the input tensor is casted to dtype before the operation is performed. This is useful for preventing data type overflows. The default value is None. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor, the result of cumprod operator. Examples: .. code-block:: python import paddle data = paddle.arange(12) data = paddle.reshape(data, (3, 4)) # [[ 0 1 2 3 ] # [ 4 5 6 7 ] # [ 8 9 10 11]] y = paddle.cumprod(data, dim=0) # [[ 0 1 2 3] # [ 0 5 12 21] # [ 0 45 120 231]] y = paddle.cumprod(data, dim=-1) # [[ 0 0 0 0] # [ 4 20 120 840] # [ 8 72 720 7920]] y = paddle.cumprod(data, dim=1, dtype='float64') # [[ 0. 0. 0. 0.] # [ 4. 20. 120. 840.] # [ 8. 72. 720. 7920.]] print(y.dtype) # paddle.float64 """ if dtype is not None and x.dtype != convert_np_dtype_to_dtype_(dtype): x = cast(x, dtype) if paddle.in_dynamic_mode(): return _C_ops.cumprod(x, 'dim', dim) check_variable_and_dtype(x, "x", ['complex64', 'complex128', 'float32', 'float64', 'int32', 'int64'], 'cumprod') check_type(dim, 'dim', int, 'cumprod') helper = LayerHelper('cumprod', **locals()) out = helper.create_variable_for_type_inference(x.dtype) helper.append_op(type='cumprod', inputs={'X': x}, outputs={'Out': out}, attrs={'dim': dim}) return out def isfinite(x, name=None): """ Return whether every element of input tensor is finite number or not. Args: x (Tensor): The input tensor, it's data type should be float16, float32, float64, int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: `Tensor`, the bool result which shows every element of `x` whether it is finite number or not. Examples: .. code-block:: python import paddle x = paddle.to_tensor([float('-inf'), -2, 3.6, float('inf'), 0, float('-nan'), float('nan')]) out = paddle.tensor.isfinite(x) print(out) # [False True True False True False False] """ if paddle.in_dynamic_mode(): return _C_ops.isfinite_v2(x) helper = LayerHelper("isfinite_v2", **locals()) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64'], 'isfinite') out = helper.create_variable_for_type_inference('bool') helper.append_op(type="isfinite_v2", inputs={"X": x}, outputs={"Out": out}) return out def isinf(x, name=None): """ Return whether every element of input tensor is `+/-INF` or not. Args: x (Tensor): The input tensor, it's data type should be float16, float32, float64, int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: `Tensor`, the bool result which shows every element of `x` whether it is `+/-INF` or not. Examples: .. code-block:: python import paddle x = paddle.to_tensor([float('-inf'), -2, 3.6, float('inf'), 0, float('-nan'), float('nan')]) out = paddle.tensor.isinf(x) print(out) # [ True False False True False False False] """ if paddle.in_dynamic_mode(): return _C_ops.isinf_v2(x) helper = LayerHelper("isinf_v2", **locals()) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64'], 'isinf') out = helper.create_variable_for_type_inference(dtype='bool') helper.append_op(type="isinf_v2", inputs={"X": x}, outputs={"Out": out}) return out def isnan(x, name=None): """ Return whether every element of input tensor is `NaN` or not. Args: x (Tensor): The input tensor, it's data type should be float16, float32, float64, int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: `Tensor`, the bool result which shows every element of `x` whether it is `NaN` or not. Examples: .. code-block:: python import paddle x = paddle.to_tensor([float('-inf'), -2, 3.6, float('inf'), 0, float('-nan'), float('nan')]) out = paddle.tensor.isnan(x) print(out) # [False False False False False True True] """ if paddle.in_dynamic_mode(): return _C_ops.isnan_v2(x) helper = LayerHelper("isnan_v2", **locals()) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64'], 'isnan') out = helper.create_variable_for_type_inference(dtype='bool') helper.append_op(type="isnan_v2", inputs={"X": x}, outputs={"Out": out}) return out def prod(x, axis=None, keepdim=False, dtype=None, name=None): """ Compute the product of tensor elements over the given axis. Args: x(Tensor): The input tensor, its data type should be float32, float64, int32, int64. axis(int|list|tuple, optional): The axis along which the product is computed. If :attr:`None`, multiply all elements of `x` and return a Tensor with a single element, otherwise must be in the range :math:`[-x.ndim, x.ndim)`. If :math:`axis[i]<0`, the axis to reduce is :math:`x.ndim + axis[i]`. Default is None. dtype(str|np.dtype, optional): The desired date type of returned tensor, can be float32, float64, int32, int64. If specified, the input tensor is casted to dtype before operator performed. This is very useful for avoiding data type overflows. The default value is None, the dtype of output is the same as input Tensor `x`. keepdim(bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the input unless `keepdim` is true. Default is False. name(string, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Returns: Tensor, result of product on the specified dim of input tensor. Raises: ValueError: The :attr:`dtype` must be float32, float64, int32 or int64. TypeError: The type of :attr:`axis` must be int, list or tuple. Examples: .. code-block:: python import paddle # the axis is a int element x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], [0.1, 0.2, 0.6, 0.7]]) out1 = paddle.prod(x) # [0.0002268] out2 = paddle.prod(x, -1) # [0.027 0.0084] out3 = paddle.prod(x, 0) # [0.02 0.06 0.3 0.63] out4 = paddle.prod(x, 0, keepdim=True) # [[0.02 0.06 0.3 0.63]] out5 = paddle.prod(x, 0, dtype='int64') # [0 0 0 0] # the axis is list y = paddle.to_tensor([[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]]) out6 = paddle.prod(y, [0, 1]) # [105. 384.] out7 = paddle.prod(y, (1, 2)) # [ 24. 1680.] """ if dtype is not None: check_dtype(dtype, 'dtype', ['float32', 'float64', 'int32', 'int64'], 'prod') if x.dtype != convert_np_dtype_to_dtype_(dtype): x = cast(x, dtype) return reduce_prod(input=x, dim=axis, keep_dim=keepdim, name=name) def sign(x, name=None): """ This OP returns sign of every element in `x`: 1 for positive, -1 for negative and 0 for zero. Args: x(Tensor): The input tensor. The data type can be float16, float32 or float64. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: The output sign tensor with identical shape and data type to the input :attr:`x`. Examples: .. code-block:: python import paddle x = paddle.to_tensor([3.0, 0.0, -2.0, 1.7], dtype='float32') out = paddle.sign(x=x) print(out) # [1.0, 0.0, -1.0, 1.0] """ if paddle.in_dynamic_mode(): return _C_ops.sign(x) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'sign') helper = LayerHelper("sign", **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op(type='sign', inputs={'X': [x]}, outputs={'Out': [out]}) return out def tanh(x, name=None): r""" Tanh Activation Operator. .. math:: out = \\frac{e^{x} - e^{-x}}{e^{x} + e^{-x}} Args: x (Tensor): Input of Tanh operator, an N-D Tensor, with data type float32, float64 or float16. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: Output of Tanh operator, a Tensor with same data type and shape as input. Examples: .. code-block:: python import paddle x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) out = paddle.tanh(x) print(out) # [-0.37994896 -0.19737532 0.09966799 0.29131261] """ if paddle.in_dynamic_mode(): return _C_ops.tanh(x) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'tanh') check_type(x, 'x', (Variable), 'tanh') helper = LayerHelper('tanh', **locals()) out = helper.create_variable_for_type_inference(x.dtype) helper.append_op(type='tanh', inputs={'X': x}, outputs={'Out': out}) return out @inplace_apis_in_dygraph_only def tanh_(x, name=None): r""" Inplace version of ``tanh`` API, the output Tensor will be inplaced with input ``x``. Please refer to :ref:`api_tensor_tanh`. """ return _C_ops.tanh_(x) def increment(x, value=1.0, name=None): """ The OP is usually used for control flow to increment the data of :attr:`x` by an amount :attr:`value`. Notice that the number of elements in :attr:`x` must be equal to 1. Args: x (Tensor): A tensor that must always contain only one element, its data type supports float32, float64, int32 and int64. value(float, optional): The amount to increment the data of :attr:`x`. Default: 1.0. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor, the elementwise-incremented tensor with the same shape and data type as :attr:`x`. Examples: .. code-block:: python import paddle data = paddle.zeros(shape=[1], dtype='float32') counter = paddle.increment(data) # [1.] """ if paddle.in_dynamic_mode(): return _C_ops.increment(x, 'step', value) check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], 'increment') helper = LayerHelper("increment", **locals()) helper.append_op( type='increment', inputs={'X': [x]}, outputs={'Out': [x]}, attrs={'step': float(value)}) return x def all(x, axis=None, keepdim=False, name=None): """ Computes the the ``logical and`` of tensor elements over the given dimension. Args: x (Tensor): An N-D Tensor, the input data type should be `bool`. axis (int|list|tuple, optional): The dimensions along which the ``logical and`` is compute. If :attr:`None`, and all elements of :attr:`x` and return a Tensor with a single element, otherwise must be in the range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`, the dimension to reduce is :math:`rank + axis[i]`. keepdim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result Tensor will have one fewer dimension than the :attr:`x` unless :attr:`keepdim` is true, default value is False. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: Results the ``logical and`` on the specified axis of input Tensor `x`, it's data type is bool. Raises: ValueError: If the data type of `x` is not bool. TypeError: The type of :attr:`axis` must be int, list or tuple. Examples: .. code-block:: python import paddle import numpy as np # x is a bool Tensor with following elements: # [[True, False] # [True, True]] x = paddle.assign(np.array([[1, 0], [1, 1]], dtype='int32')) print(x) x = paddle.cast(x, 'bool') # out1 should be [False] out1 = paddle.all(x) # [False] print(out1) # out2 should be [True, False] out2 = paddle.all(x, axis=0) # [True, False] print(out2) # keep_dim=False, out3 should be [False, True], out.shape should be (2,) out3 = paddle.all(x, axis=-1) # [False, True] print(out3) # keep_dim=True, out4 should be [[False], [True]], out.shape should be (2,1) out4 = paddle.all(x, axis=1, keepdim=True) out4 = paddle.cast(out4, 'int32') # [[False], [True]] print(out4) """ if axis is not None and not isinstance(axis, (list, tuple)): axis = [axis] if not axis: reduce_all_flag = True else: if len(axis) == len(x.shape): reduce_all_flag = True else: reduce_all_flag = False if paddle.in_dynamic_mode(): axis = axis if axis != None and axis != [] else [0] return _C_ops.reduce_all(x, 'dim', axis, 'keep_dim', keepdim, 'reduce_all', reduce_all_flag) attrs = { 'dim': axis if axis != None and axis != [] and axis != () else [0], 'keep_dim': keepdim, 'reduce_all': reduce_all_flag } check_variable_and_dtype(x, 'x', ['bool'], 'all') check_type(axis, 'axis', (int, list, tuple, type(None)), 'all') helper = LayerHelper('all', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='reduce_all', inputs={'X': x}, outputs={'Out': out}, attrs=attrs) return out def any(x, axis=None, keepdim=False, name=None): """ Computes the the ``logical or`` of tensor elements over the given dimension. Args: x (Tensor): An N-D Tensor, the input data type should be `bool`. axis (int|list|tuple, optional): The dimensions along which the ``logical or`` is compute. If :attr:`None`, and all elements of :attr:`x` and return a Tensor with a single element, otherwise must be in the range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`, the dimension to reduce is :math:`rank + axis[i]`. keepdim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result Tensor will have one fewer dimension than the :attr:`x` unless :attr:`keepdim` is true, default value is False. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor: Results the ``logical or`` on the specified axis of input Tensor `x`, it's data type is bool. Raises: ValueError: If the data type of `x` is not bool. TypeError: The type of :attr:`axis` must be int, list or tuple. Examples: .. code-block:: python import paddle import numpy as np # x is a bool Tensor with following elements: # [[True, False] # [False, False]] x = paddle.assign(np.array([[1, 0], [1, 1]], dtype='int32')) print(x) x = paddle.cast(x, 'bool') # out1 should be [True] out1 = paddle.any(x) # [True] print(out1) # out2 should be [True, True] out2 = paddle.any(x, axis=0) # [True, True] print(out2) # keep_dim=False, out3 should be [True, True], out.shape should be (2,) out3 = paddle.any(x, axis=-1) # [True, True] print(out3) # keep_dim=True, result should be [[True], [True]], out.shape should be (2,1) out4 = paddle.any(x, axis=1, keepdim=True) out4 = paddle.cast(out4, 'int32') # [[True], [True]] print(out4) """ if axis is not None and not isinstance(axis, (list, tuple)): axis = [axis] if not axis: reduce_all_flag = True else: if len(axis) == len(x.shape): reduce_all_flag = True else: reduce_all_flag = False if paddle.in_dynamic_mode(): axis = axis if axis != None and axis != [] else [0] return _C_ops.reduce_any(x, 'dim', axis, 'keep_dim', keepdim, 'reduce_all', reduce_all_flag) attrs = { 'dim': axis if axis != None and axis != [] and axis != () else [0], 'keep_dim': keepdim, 'reduce_all': reduce_all_flag } check_variable_and_dtype(x, 'x', ['bool'], 'any') check_type(axis, 'axis', (int, list, tuple, type(None)), 'any') helper = LayerHelper('any', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='reduce_any', inputs={'X': x}, outputs={'Out': out}, attrs=attrs) return out def broadcast_shape(x_shape, y_shape): """ The function returns the shape of doing operation with broadcasting on tensors of x_shape and y_shape, please refer to :ref:`user_guide_broadcasting` for more details. Args: x_shape (list[int]|tuple[int]): A shape of tensor. y_shape (list[int]|tuple[int]): A shape of tensor. Returns: list[int], the result shape. Examples: .. code-block:: python import paddle shape = paddle.broadcast_shape([2, 1, 3], [1, 3, 1]) # [2, 3, 3] # shape = paddle.broadcast_shape([2, 1, 3], [3, 3, 1]) # ValueError (terminated with error message). """ return core.broadcast_shape(x_shape, y_shape) def conj(x, name=None): r""" This function computes the conjugate of the Tensor elementwisely. Args: x (Tensor): The input tensor which hold the complex numbers. Optional data types are: complex64, complex128, float32, float64, int32 or int64. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: out (Tensor): The conjugate of input. The shape and data type is the same with input. If the elements of tensor is real type such as float32, float64, int32 or int64, the out is the same with input. Examples: .. code-block:: python import paddle data=paddle.to_tensor([[1+1j, 2+2j, 3+3j], [4+4j, 5+5j, 6+6j]]) #Tensor(shape=[2, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True, # [[(1+1j), (2+2j), (3+3j)], # [(4+4j), (5+5j), (6+6j)]]) conj_data=paddle.conj(data) #Tensor(shape=[2, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True, # [[(1-1j), (2-2j), (3-3j)], # [(4-4j), (5-5j), (6-6j)]]) """ if paddle.in_dynamic_mode(): return _C_ops.conj(x) check_variable_and_dtype(x, "x", ['complex64', 'complex128', 'float32', 'float64', 'int32', 'int64'], 'conj') helper = LayerHelper('conj', **locals()) out = helper.create_variable_for_type_inference( dtype=helper.input_dtype()) helper.append_op(type='conj', inputs={'X': x}, outputs={'Out': [out]}) return out def digamma(x, name=None): r""" Calculates the digamma of the given input tensor, element-wise. .. math:: Out = \Psi(x) = \frac{ \Gamma^{'}(x) }{ \Gamma(x) } Args: x (Tensor): Input Tensor. Must be one of the following types: float32, float64. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` Returns: Tensor, the digamma of the input Tensor, the shape and data type is the same with input. Examples: .. code-block:: python import paddle data = paddle.to_tensor([[1, 1.5], [0, -2.2]], dtype='float32') res = paddle.digamma(data) print(res) # Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [[-0.57721591, 0.03648996], # [ nan , 5.32286835]]) """ if paddle.in_dynamic_mode(): if _in_eager_mode(): return _C_ops.final_state_digamma(x) return _C_ops.digamma(x) check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'digamma') helper = LayerHelper('digamma', **locals()) out = helper.create_variable_for_type_inference(x.dtype) helper.append_op(type='digamma', inputs={'X': x}, outputs={'Out': out}) return out def neg(x, name=None): """ This function computes the negative of the Tensor elementwisely. Args: x (Tensor): Input of neg operator, an N-D Tensor, with data type float32, float64, int8, int16, int32, or int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: out (Tensor): The negative of input Tensor. The shape and data type are the same with input Tensor. Examples: .. code-block:: python import paddle x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) out = paddle.neg(x) print(out) # [0.4 0.2 -0.1 -0.3] """ return scale(x, scale=-1.0, bias=0.0, bias_after_scale=True, act=None, name=name) def atan2(x, y, name=None): r""" Element-wise arctangent of x/y with consideration of the quadrant. Equation: .. math:: atan2(x,y)=\left\{\begin{matrix} & tan^{-1}(\frac{x}{y}) & y > 0 \\ & tan^{-1}(\frac{x}{y}) + \pi & x>=0, y < 0 \\ & tan^{-1}(\frac{x}{y}) - \pi & x<0, y < 0 \\ & +\frac{\pi}{2} & x>0, y = 0 \\ & -\frac{\pi}{2} & x<0, y = 0 \\ &\text{undefined} & x=0, y = 0 \end{matrix}\right. Args: x (Tensor): An N-D Tensor, the data type is int32, int64, float16, float32, float64. y (Tensor): An N-D Tensor, must have the same type as `x`. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: out (Tensor): An N-D Tensor, the shape and data type is the same with input (The output data type is float64 when the input data type is int). Examples: .. code-block:: python import paddle x = paddle.to_tensor([-1, +1, +1, -1]).astype('float32') #Tensor(shape=[4], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [-1, 1, 1, -1]) y = paddle.to_tensor([-1, -1, +1, +1]).astype('float32') #Tensor(shape=[4], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [-1, -1, 1, 1]) out = paddle.atan2(x, y) #Tensor(shape=[4], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [-2.35619450, 2.35619450, 0.78539819, -0.78539819]) """ if paddle.in_dynamic_mode(): if _in_eager_mode(): return _C_ops.final_state_atan2( x, y) return _C_ops.atan2(x, y) else: check_variable_and_dtype(x, 'x', ['int32', 'int64', 'float16', 'float32', 'float64'], 'atan2') check_variable_and_dtype(y, 'y', ['int32', 'int64', 'float16', 'float32', 'float64'], 'atan2') helper = LayerHelper('atan2', **locals()) inputs = {'X1' : x, 'X2' : y} out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='atan2', inputs=inputs, outputs={'Out': out}) return out def logit(x, eps=None, name=None): r""" This function generates a new tensor with the logit of the elements of input x. x is clamped to [eps, 1-eps] when eps is not zero. When eps is zero and x < 0 or x > 1, the function will yields NaN. .. math:: logit(x) = ln(\frac{x}{1 - x}) where .. math:: x_i= \left\{\begin{array}{rcl} x_i & &\text{if } eps == Default \\ eps & &\text{if } x_i < eps \\ x_i & &\text{if } eps <= x_i <= 1-eps \\ 1-eps & &\text{if } x_i > 1-eps \end{array}\right. Args: x (Tensor): The input Tensor with data type float32, float64. eps (float, optional): the epsilon for input clamp bound. Default is None. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: out(Tensor): A Tensor with the same data type and shape as ``x`` . Examples: .. code-block:: python import paddle x = paddle.to_tensor([0.2635, 0.0106, 0.2780, 0.2097, 0.8095]) out1 = paddle.logit(x) print(out1) # [-1.0277, -4.5365, -0.9544, -1.3269, 1.4468] """ if eps == None: eps = 0.0 if paddle.in_dynamic_mode(): return _C_ops.logit(x, 'eps', eps) check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'logit') helper = LayerHelper("logit", **locals()) out = helper.create_variable_for_type_inference(x.dtype) helper.append_op( type='logit', inputs={'X': x}, outputs={'Out': out}, attrs={'eps': eps}) return out def lerp(x, y, weight, name=None): r""" Does a linear interpolation between x and y based on weight. Equation: .. math:: lerp(x, y, weight) = x + weight * (y - x). Args: x (Tensor): An N-D Tensor with starting points, the data type is float32, float64. y (Tensor): An N-D Tensor with ending points, the data type is float32, float64. weight (float|Tensor): The weight for the interpolation formula. When weight is Tensor, the data type is float32, float64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: out (Tensor): An N-D Tensor, the shape and data type is the same with input. Example: .. code-block:: python import paddle x = paddle.arange(1., 5., dtype='float32') y = paddle.empty([4], dtype='float32') y.fill_(10.) out = paddle.lerp(start, end, 0.5) # out: [5.5., 6., 6.5, 7.] """ if paddle.in_dynamic_mode(): check_type(weight, 'weight', (float, paddle.Tensor, Variable), 'lerp') if isinstance(weight, float): weight = paddle.to_tensor(weight, dtype=x.dtype) return _C_ops.lerp(x, y, weight) if isinstance(weight, float): weight = paddle.full(shape=[1], fill_value=weight, dtype=x.dtype) check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'lerp') check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'lerp') check_variable_and_dtype(weight, 'weight', ['float32', 'float64'], 'lerp') helper = LayerHelper('lerp', **locals()) inputs = {'X': x, 'Y': y, 'Weight': weight} out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op(type='lerp', inputs=inputs, outputs={'Out': out}) return out @inplace_apis_in_dygraph_only def lerp_(x, y, weight, name=None): r""" Inplace version of ``lerp`` API, the output Tensor will be inplaced with input ``x``. Please refer to :ref:`api_tensor_lerp`. """ out_shape = broadcast_shape(x.shape, y.shape) check_type(weight, 'weight', (float, paddle.Tensor, Variable), 'lerp') if isinstance(weight, float): weight = paddle.to_tensor([weight], dtype=x.dtype) elif isinstance(weight, (paddle.Tensor, Variable)): out_shape = broadcast_shape(out_shape, weight.shape) if out_shape != x.shape: raise ValueError("The shape of broadcast output {} is different from that of inplace tensor {} in the Inplace operation.".format(out_shape, x.shape)) return _C_ops.lerp_(x, y, weight) def erfinv(x, name=None): r""" The inverse error function of x, . Equation: .. math:: erfinv(erf(x)) = x. Args: x (Tensor): An N-D Tensor, the data type is float32, float64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: out (Tensor): An N-D Tensor, the shape and data type is the same with input. Example: .. code-block:: python import paddle x = paddle.to_tensor([0, 0.5, -1.], dtype="float32") out = paddle.erfinv(x) # out: [0, 0.4769, -inf] """ check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'erfinv') if paddle.in_dynamic_mode(): return _C_ops.erfinv(x) helper = LayerHelper('erfinv', **locals()) out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op(type='erfinv', inputs={'X': x}, outputs={'Out': out}) return out @inplace_apis_in_dygraph_only def erfinv_(x, name=None): r""" Inplace version of ``erfinv`` API, the output Tensor will be inplaced with input ``x``. Please refer to :ref:`api_tensor_erfinv`. """ check_type(x, 'x', (paddle.Tensor, Variable), 'erfinv') return _C_ops.erfinv_(x) def rad2deg(x, name=None): r""" Convert each of the elements of input x from angles in radians to degrees. Equation: .. math:: rad2deg(x)=180/ \pi * x Args: x (Tensor): An N-D Tensor, the data type is float32, float64, int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: out (Tensor): An N-D Tensor, the shape and data type is the same with input (The output data type is float32 when the input data type is int). Examples: .. code-block:: python import paddle import numpy as np x1 = paddle.to_tensor([3.142, -3.142, 6.283, -6.283, 1.570, -1.570]) result1 = paddle.rad2deg(x1) print(result1) # Tensor(shape=[6], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [180.02334595, -180.02334595, 359.98937988, -359.98937988, # 9.95437622 , -89.95437622]) x2 = paddle.to_tensor(np.pi/2) result2 = paddle.rad2deg(x2) print(result2) # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [90.]) x3 = paddle.to_tensor(1) result3 = paddle.rad2deg(x3) print(result3) # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [57.29578018]) """ rad2deg_scale = 180 / np.pi if paddle.in_dynamic_mode(): if convert_dtype(x.dtype) in ['int32', 'int64']: x = cast(x, dtype="float32") return _C_ops.scale(x, 'scale', rad2deg_scale) else: check_variable_and_dtype(x, 'x', ['int32', 'int64', 'float32', 'float64'], 'rad2deg') helper = LayerHelper('rad2deg', **locals()) out_cast = x if convert_dtype(x.dtype) in ['int32', 'int64']: out_cast = helper.create_variable_for_type_inference(dtype=paddle.float32) helper.append_op( type='cast', inputs={'X':x}, outputs={'Out': out_cast}, attrs={'in_dtype': x.dtype,'out_dtype': paddle.float32}) out = helper.create_variable_for_type_inference(dtype=out_cast.dtype) helper.append_op( type='scale', inputs={'X':out_cast}, outputs={'Out': out}, attrs={'scale': rad2deg_scale}) return out def deg2rad(x, name=None): r""" Convert each of the elements of input x from degrees to angles in radians. Equation: .. math:: deg2rad(x)=\pi * x / 180 Args: x (Tensor): An N-D Tensor, the data type is float32, float64, int32, int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: out (Tensor): An N-D Tensor, the shape and data type is the same with input (The output data type is float32 when the input data type is int). Examples: .. code-block:: python import paddle import numpy as np x1 = paddle.to_tensor([180.0, -180.0, 360.0, -360.0, 90.0, -90.0]) result1 = paddle.deg2rad(x1) print(result1) # Tensor(shape=[6], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [3.14159274, -3.14159274, 6.28318548, -6.28318548, 1.57079637, # -1.57079637]) x2 = paddle.to_tensor(180) result2 = paddle.deg2rad(x2) print(result2) # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, # [3.14159274]) """ deg2rad_scale = np.pi / 180.0 if paddle.in_dynamic_mode(): if convert_dtype(x.dtype) in ['int32', 'int64']: x = cast(x, dtype="float32") return _C_ops.scale(x, 'scale', deg2rad_scale) else: check_variable_and_dtype(x, 'x', ['int32', 'int64', 'float32', 'float64'], 'deg2rad') helper = LayerHelper('deg2rad', **locals()) out_cast = x if convert_dtype(x.dtype) in ['int32', 'int64']: out_cast = helper.create_variable_for_type_inference(dtype=paddle.float32) helper.append_op( type='cast', inputs={'X':x}, outputs={'Out': out_cast}, attrs={'in_dtype': x.dtype,'out_dtype': paddle.float32}) out = helper.create_variable_for_type_inference(dtype=out_cast.dtype) helper.append_op( type='scale', inputs={'X':out_cast}, outputs={'Out': out}, attrs={'scale': deg2rad_scale}) return out def gcd(x, y, name=None): """ Computes the element-wise greatest common divisor (GCD) of input |x| and |y|. Both x and y must have integer types. Note: gcd(0,0)=0, gcd(0, y)=|y| If x.shape != y.shape, they must be broadcastable to a common shape (which becomes the shape of the output). Args: x (Tensor): An N-D Tensor, the data type is int32,int64. y (Tensor): An N-D Tensor, the data type is int32,int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: out (Tensor): An N-D Tensor, the data type is the same with input. Examples: .. code-block:: python import paddle x1 = paddle.to_tensor(12) x2 = paddle.to_tensor(20) paddle.gcd(x1, x2) # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [4]) x3 = paddle.arange(6) paddle.gcd(x3, x2) # Tensor(shape=[6], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [20, 1 , 2 , 1 , 4 , 5]) x4 = paddle.to_tensor(0) paddle.gcd(x4, x2) # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [20]) paddle.gcd(x4, x4) # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [0]) x5 = paddle.to_tensor(-20) paddle.gcd(x1, x5) # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [4]) """ shape = paddle.broadcast_shape(x.shape, y.shape) x = paddle.broadcast_to(x, shape) y = paddle.broadcast_to(y, shape) x = paddle.abs(x) y = paddle.abs(y) def _gcd_cond_fn(x, y): return paddle.any(y != 0) def _gcd_body_fn(x, y): # paddle.mod will raise an error when any element of y is 0. To avoid # that, we change those zeros to ones. Their values don't matter because # they won't be used. y_not_equal_0 = (y != 0) y_safe = paddle.where(y_not_equal_0, y, paddle.ones(y.shape, y.dtype)) x, y = (paddle.where(y_not_equal_0, y, x), paddle.where(y_not_equal_0, paddle.mod(x, y_safe),paddle.zeros(y.shape, y.dtype))) return (paddle.where(x < y, y, x), paddle.where(x < y, x, y)) if paddle.in_dynamic_mode(): while _gcd_cond_fn(x, y): x, y = _gcd_body_fn(x, y) return x else: check_variable_and_dtype(x, 'x', ['int32', 'int64'], 'gcd') check_variable_and_dtype(y, 'y', ['int32', 'int64'], 'gcd') out, _ = paddle.static.nn.while_loop(_gcd_cond_fn, _gcd_body_fn, [x, y]) return out def lcm(x, y, name=None): """ Computes the element-wise least common multiple (LCM) of input |x| and |y|. Both x and y must have integer types. Note: lcm(0,0)=0, lcm(0, y)=0 If x.shape != y.shape, they must be broadcastable to a common shape (which becomes the shape of the output). Args: x (Tensor): An N-D Tensor, the data type is int32,int64. y (Tensor): An N-D Tensor, the data type is int32,int64. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: out (Tensor): An N-D Tensor, the data type is the same with input. Examples: .. code-block:: python import paddle x1 = paddle.to_tensor(12) x2 = paddle.to_tensor(20) paddle.lcm(x1, x2) # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [60]) x3 = paddle.arange(6) paddle.lcm(x3, x2) # Tensor(shape=[6], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [0, 20, 20, 60, 20, 20]) x4 = paddle.to_tensor(0) paddle.lcm(x4, x2) # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [0]) paddle.lcm(x4, x4) # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [0]) x5 = paddle.to_tensor(-20) paddle.lcm(x1, x5) # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [60]) """ d = paddle.gcd(x, y) # paddle.mod will raise an error when any element of y is 0. To avoid # that, we change those zeros to ones. Their values don't matter because # they won't be used. d_equal_0 = paddle.equal(d, 0) d_safe = paddle.where(d_equal_0, paddle.ones(d.shape, d.dtype), d) out = paddle.where(d_equal_0, paddle.zeros(d.shape, d.dtype), paddle.abs(x * y) // d_safe) return out def diff(x, n=1, axis=-1, prepend=None, append=None, name=None): r""" Computes the n-th forward difference along the given axis. The first-order differences is computed by using the following formula: .. math:: out[i] = x[i+1] - x[i] Higher-order differences are computed by using paddle.diff() recursively. Only n=1 is currently supported. Args: x(Tensor): The input tensor to compute the forward difference on n(int, optional): The number of times to recursively compute the difference. Only support n=1. Default:1 axis(int, optional): The axis to compute the difference along. Default:-1 prepend(Tensor, optional): The tensor to prepend to input along axis before computing the difference. It's dimensions must be equivalent to that of x, and its shapes must match x's shape except on axis. append(Tensor, optional): The tensor to append to input along axis before computing the difference, It's dimensions must be equivalent to that of x, and its shapes must match x's shape except on axis. name(str|None): A name for this layer(optional). If set None, the layer will be named automatically. Returns: Tensor: The output tensor with same dtype with x. Examples: .. code-block:: python import paddle x = paddle.to_tensor([1, 4, 5, 2]) out = paddle.diff(x) print(out) # out: # [3, 1, -3] y = paddle.to_tensor([7, 9]) out = paddle.diff(x, append=y) print(out) # out: # [3, 1, -3, 5, 2] z = paddle.to_tensor([[1, 2, 3], [4, 5, 6]]) out = paddle.diff(z, axis=0) print(out) # out: # [[3, 3, 3]] out = paddle.diff(z, axis=1) print(out) # out: # [[1, 1], [1, 1]] """ if axis < 0: axis = axis + len(x.shape) if axis > len(x.shape): axis = len(x.shape) if axis < 0: axis = 0 dtype = x.dtype axes = [axis] infer_flags = list(1 for i in range(len(axes))) if paddle.in_dynamic_mode(): has_pend = False input_list = [] if prepend is not None and append is not None: input_list = [prepend, x, append] has_pend = True elif prepend is not None: input_list = [prepend, x] has_pend = True elif append is not None: input_list = [x, append] has_pend = True if has_pend: new_input = _C_ops.concat(input_list, 'axis', axis) else: new_input = x attrs_1 = () attrs_2 = () dim_len = new_input.shape[axis] starts_1 = [0] attrs_1 += ('starts', starts_1) ends_1 = [dim_len - 1] attrs_1 += ('ends', ends_1) input_front = _C_ops.slice(new_input, None, None, None, None, 'axes', axes, \ 'infer_flags', infer_flags, *attrs_1) starts_2 = [1] attrs_2 += ('starts', starts_2) ends_2 = [dim_len] attrs_2 += ('ends', ends_2) input_back = _C_ops.slice(new_input, None, None, None, None, 'axes', axes, \ 'infer_flags', infer_flags, *attrs_2) if x.dtype == paddle.bool: op = getattr(_C_ops, "logical_xor") out = op(input_back, input_front) else: out = elementwise_sub(input_back, input_front, axis=axis) return out else: check_variable_and_dtype(x, 'x', ['float32', 'float64', 'bool', 'int32', 'int64'], 'diff') check_type(axis, 'axis', (int), 'diff') helper = LayerHelper('diff', **locals()) has_pend = False input_list = [] if prepend is not None and append is not None: input_list = [prepend, x, append] has_pend = True elif prepend is not None: input_list = [prepend, x] has_pend = True elif append is not None: input_list = [x, append] has_pend = True if has_pend: new_input = helper.create_variable_for_type_inference(dtype) helper.append_op( type='concat', inputs={'X': input_list}, outputs={'Out': [new_input]}, attrs={'axis': axis} ) else: new_input = x dim_len = new_input.shape[axis] attrs_1 = {'axes': axes} starts_1 = [0] ends_1 = [dim_len - 1] attrs_1['starts'] = starts_1 attrs_1['ends'] = ends_1 input_front = helper.create_variable_for_type_inference(dtype) helper.append_op( type='slice', inputs={'Input': new_input}, attrs=attrs_1, outputs={'Out': input_front} ) attrs_2 = {'axes': axes} starts_2 = [1] ends_2 = [dim_len] attrs_2['starts'] = starts_2 attrs_2['ends'] = ends_2 input_back = helper.create_variable_for_type_inference(dtype) helper.append_op( type='slice', inputs={'Input': new_input}, attrs=attrs_2, outputs={'Out': input_back} ) if dtype == paddle.bool: out = helper.create_variable_for_type_inference(dtype) helper.append_op( type='logical_xor', inputs={"X": input_back, "Y": input_front}, outputs={"Out": out} ) else: out = elementwise_sub(input_back, input_front, axis=axis) return out def angle(x, name=None): r""" Element-wise angle of complex numbers. For non-negative real numbers, the angle is 0 while for negative real numbers, the angle is :math:`\pi`. Equation: .. math:: angle(x)=arctan2(x.imag, x.real) Args: x (Tensor): An N-D Tensor, the data type is complex64, complex128, or float32, float64 . name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor: An N-D Tensor of real data type with the same precision as that of x's data type. Examples: .. code-block:: python import paddle x = paddle.to_tensor([-2, -1, 0, 1]).unsqueeze(-1).astype('float32') y = paddle.to_tensor([-2, -1, 0, 1]).astype('float32') z = x + 1j * y print(z.numpy()) # [[-2.-2.j -2.-1.j -2.+0.j -2.+1.j] # [-1.-2.j -1.-1.j -1.+0.j -1.+1.j] # [ 0.-2.j 0.-1.j 0.+0.j 0.+1.j] # [ 1.-2.j 1.-1.j 1.+0.j 1.+1.j]] theta = paddle.angle(z) print(theta.numpy()) # [[-2.3561945 -2.6779451 3.1415927 2.6779451] # [-2.0344439 -2.3561945 3.1415927 2.3561945] # [-1.5707964 -1.5707964 0. 1.5707964] # [-1.1071488 -0.7853982 0. 0.7853982]] """ if paddle.in_dynamic_mode(): return _C_ops.angle(x) check_variable_and_dtype(x, 'x', ['float32', 'float64', 'complex64', 'complex128'], 'angle') op_type = "angle" helper = LayerHelper(op_type, **locals()) inputs = {"X": x} out = helper.create_variable_for_type_inference( dtype=_complex_to_real_dtype(x.dtype)) outputs = {"Out": out} helper.append_op(type=op_type, inputs=inputs, outputs=outputs) return out
37.505231
291
0.564467
54c87d3bb5eafbdda0c7721da76bda878f1f6103
17,893
py
Python
src/saltuser/saltuser.py
saltastro/saltuser
a5c97b15b5c2cbf732fb957c9dd91ac04ac23373
[ "MIT" ]
null
null
null
src/saltuser/saltuser.py
saltastro/saltuser
a5c97b15b5c2cbf732fb957c9dd91ac04ac23373
[ "MIT" ]
null
null
null
src/saltuser/saltuser.py
saltastro/saltuser
a5c97b15b5c2cbf732fb957c9dd91ac04ac23373
[ "MIT" ]
null
null
null
import pandas as pd class SALTUser: """ A user of the Southern African Large Telescope with roles and permissions. The user is identified by their username, as used for the Principal Investigator Proposal Tool (PIPT) or the Web Manager. The aim of this class is to allow checking roles and permissions. It includes no authentication. A new user should be created using either the constructor or the :meth:`find_by_username` method. You need to specify a database connection when creating the user. Any format allowed by the `con` parameter of pandas' `read_sql` function can be used. Parameters ---------- user_id : int The user id. db_connectable : SQLAlchemy connectable(engine/connection) or database string URI A connection to the database to use, or its URI. Raises ------ ValueError If the user does not exist. """ def __init__(self, user_id, db_connectable): # sanity check: does the user exist? sql = """ SELECT pu.PiptUser_Id, FirstName, Surname, Email FROM PiptUser AS pu JOIN Investigator AS i USING (Investigator_Id) WHERE pu.PiptUser_Id=%(user_id)s """ df = pd.read_sql(sql, con=db_connectable, params=dict(user_id=user_id)) if len(df) == 0: raise ValueError( "There is no user with id {user_id}.".format(user_id=user_id) ) self._db_connectable = db_connectable self._user_id = user_id self._given_name = df["FirstName"][0] self._family_name = df["Surname"][0] self._email = df["Email"][0] self._is_board_member = None self._tac_member_partners = self._find_tac_member_partners() self._tac_chair_partners = self._find_tac_chair_partners() self._viewable_proposals_cache = None @staticmethod def verify(username, password, db_connectable): """ Verify that a username-password combination is valid. Parameters ---------- username : str The username. password : str The password. db_connectable : SQLAlchemy connectable(engine/connection) or database string URI A connection to the database to use, or its URI. Raises ------ ValueError If the username or password are wrong. """ sql = """ SELECT PiptUser_Id AS UserCount FROM PiptUser WHERE Username=%(username)s AND Password=MD5(%(password)s) """ df = pd.read_sql( sql, con=db_connectable, params=dict(username=username, password=password) ) if len(df) == 0: raise ValueError("invlid username or password") @staticmethod def find_by_username(username, db_connectable): """ Get the user with a given username. Parameters ---------- username : str The username. db_connectable : SQLAlchemy connectable(engine/connection) or database string URI A connection to the database to use, or its URI. Returns ------- SALTUser The SALT user. Raises ------ ValueError If the user does not exist. """ user_id = SALTUser._find_user_id(username, db_connectable) return SALTUser(user_id, db_connectable) @property def given_name(self): """ Get the user's given name(s). Returns ------- str The given name(s). """ return self._given_name @property def family_name(self): """ Get the user's family name. Returns ------- str The family name. """ return self._family_name @property def email(self): """ Get the user's email address. Returns ------- str The email address. """ return self._email def is_admin(self): """ Check whether the user is an administrator. Returns ------- bool Whether the user is an administrator. """ sql = """ SELECT Value FROM PiptUserSetting as pus JOIN PiptSetting ps on pus.PiptSetting_Id = ps.PiptSetting_Id JOIN PiptUser AS pu ON pus.PiptUser_Id = pu.PiptUser_Id WHERE pu.PiptUser_Id=%(user_id)s AND PiptSetting_Name='RightAdmin' """ df = self._query(sql, params=dict(user_id=self._user_id)) return len(df) > 0 and int(df["Value"][0], 10) > 0 def is_investigator(self, proposal_code): """ Check whether the user is an investigator for a given proposal. Parameters ---------- proposal_code : str The proposal code. Returns ------- bool Whether the user is an investigator for the proposal. """ sql = """ SELECT COUNT(*) AS User_Count FROM ProposalCode AS pc JOIN ProposalInvestigator pi on pc.ProposalCode_Id = pi.ProposalCode_Id JOIN Investigator AS i ON pi.Investigator_Id = i.Investigator_Id WHERE Proposal_Code=%(proposal_code)s AND PiptUser_Id=%(user_id)s """ df = self._query( sql, params=dict(proposal_code=proposal_code, user_id=self._user_id) ) return df["User_Count"][0] > 0 def is_principal_investigator(self, proposal_code): """ Check whether user is the Principal Investigator of a given proposal. Parameters ---------- proposal_code : str The proposal code. Returns ------- bool Whether the user is the Principal Investigator of the proposal. """ sql = """ SELECT COUNT(*) AS User_Count FROM ProposalContact AS pco JOIN Investigator AS i ON pco.Leader_Id=i.Investigator_Id JOIN ProposalCode AS pc ON pco.ProposalCode_Id = pc.ProposalCode_Id WHERE Proposal_Code=%(proposal_code)s AND PiptUser_Id=%(user_id)s """ df = self._query( sql, params=dict(proposal_code=proposal_code, user_id=self._user_id) ) return df["User_Count"][0] > 0 def is_principal_contact(self, proposal_code): """ Check whether user is the Principal Contact of a given proposal. Parameters ---------- proposal_code : str The proposal code. Returns ------- bool Whether the user is the Principal Contact of the proposal. """ sql = """ SELECT COUNT(*) AS User_Count FROM ProposalContact AS pco JOIN Investigator AS i ON pco.Contact_Id=i.Investigator_Id JOIN ProposalCode AS pc ON pco.ProposalCode_Id = pc.ProposalCode_Id WHERE Proposal_Code=%(proposal_code)s AND PiptUser_Id=%(user_id)s """ df = self._query( sql, params=dict(proposal_code=proposal_code, user_id=self._user_id) ) return df["User_Count"][0] > 0 def is_board_member(self): """ Check whether the user is a Board member. Returns ------- bool Whether the user is a Board member. """ if self._is_board_member is None: sql = """ SELECT * FROM PiptUserSetting WHERE PiptUser_Id=%(user_id)s AND PiptSetting_Id= (SELECT PiptSetting_Id FROM PiptSetting WHERE PiptSetting_Name='RightBoard') AND Value>0 """ df = self._query(sql, dict(user_id=self._user_id)) self._is_board_member = len(df) > 0 return self._is_board_member def is_tac_member(self, partner_code=None): """ Check whether the user is member of a partner's TAC. If no partner code is given, this method checks whether the user is member of any TAC. Parameters ---------- partner_code : str The partner code of the partner. Returns ------- bool Whether the user is member of the partner's TAC. """ if not partner_code: return len(self._tac_member_partners) return partner_code in self._tac_member_partners def is_proposal_tac_member(self, proposal_code): """ Check whether the user is member of a TAC represented on a given proposal. Parameters ---------- proposal_code : str The proposal code. Returns ------- bool Whether the user is member of a TAC represented on the proposal. """ return ( len( set(self._tac_member_partners).intersection( self._proposal_partners(proposal_code) ) ) > 0 ) @property def tacs(self): """ The TACs (as a list of partner codes) on which the user serves. Returns ------- list of str The partner codes of the TACs. """ return self._tac_member_partners def is_tac_chair(self, partner_code=None): """ Check whether the user is chair of a partner's TAC. If no partner code is given, this method check whether the user is chair of any TAC. Parameters ---------- partner_code : str The partner code of the partner. Returns ------- bool Whether the user is TAC chair. """ if not partner_code: return len(self._tac_chair_partners) return partner_code in self._tac_chair_partners def may_view_proposal(self, proposal_code): """ Check whether the user may view a given proposal. Parameters ---------- proposal_code : str The proposal code. Returns ------- Whether the user may view the proposal. """ return proposal_code in self._viewable_proposals @property def _viewable_proposals(self): """ The proposals (as a list of proposal codes) the user may view. Returns ------- list of str The list of proposal codes. """ if self._viewable_proposals_cache is not None: return self._viewable_proposals_cache sql = """ SELECT DISTINCT Proposal_Code FROM ProposalCode AS pc JOIN ProposalInvestigator AS pi ON pc.ProposalCode_Id = pi.ProposalCode_Id JOIN Investigator AS i ON pi.Investigator_Id = i.Investigator_Id JOIN PiptUser AS pu ON i.PiptUser_Id=pu.PiptUser_Id JOIN Proposal AS p ON pc.ProposalCode_Id = p.ProposalCode_Id JOIN MultiPartner AS mp ON pc.ProposalCode_Id = mp.ProposalCode_Id AND p.Semester_Id = mp.Semester_Id JOIN Partner AS partner ON mp.Partner_Id = partner.Partner_Id WHERE pu.PiptUser_Id=%(user_id)s OR (partner.Partner_Code IN %(tacs)s AND mp.ReqTimeAmount>0) OR (1=%(is_admin)s) OR (1=%(is_board_member)s) """ df = self._query( sql, params=dict( user_id=self._user_id, tacs=self.tacs if self.tacs else ["IMPOSSIBLE_VALUE"], is_admin=1 if self.is_admin() else 0, is_board_member=1 if self.is_board_member() else 0, ), ) self._viewable_proposals_cache = set(df["Proposal_Code"].tolist()) return self._viewable_proposals_cache def may_edit_proposal(self, proposal_code): """ Check whether the user may edit a given proposal. Parameters ---------- proposal_code : str The proposal code. Returns ------- bool Whether the user may edit the proposal. """ return ( self.is_principal_investigator(proposal_code) or self.is_principal_contact(proposal_code) or self.is_admin() ) def may_view_block(self, block_id): """ Check whether the user may view a given block. Parameters ---------- block_id : int The block id. Returns ------- bool Whether the user may view the block. Raises ------ ValueError If there exists no block with the given block id. """ proposal_code = self._proposal_code_of_block(block_id=block_id) return self.may_view_proposal(proposal_code=proposal_code) def may_edit_block(self, block_id): """ Check whether the user may edit a given block. Parameters ---------- block_id : int The block id. Returns ------- bool Whether the user may edit the block. Raises ------ ValueError If there exists no block with the given block id. """ proposal_code = self._proposal_code_of_block(block_id=block_id) return self.may_edit_proposal(proposal_code=proposal_code) def _proposal_code_of_block(self, block_id): """ Get the proposal code of the proposal containing a given block. Parameters ---------- block_id : int The block id. Returns ------- str The proposal code. Raises ------ ValueError If there exists no block with the given block id. """ sql = """ SELECT Proposal_Code FROM ProposalCode AS pc JOIN Block AS b ON pc.ProposalCode_Id = b.ProposalCode_Id WHERE Block_Id=%(block_id)s """ df = self._query(sql, params=dict(block_id=block_id)) # sanity check: does the block exist? if len(df) == 0: raise ValueError( "There exists no block with id {block_id}".format(block_id=block_id) ) return df["Proposal_Code"][0] def _query(self, sql, params): """ Query the database. Depending on how they are referenced in the SQL query, the query parameters must be passed as an iterable or as a dict. Parameters ---------- sql : str The SQL query. params : iterable or dict The query parameters. Returns ------- DataFrame A pandas data frame with the query results. """ return pd.read_sql(sql, con=self._db_connectable, params=params) @staticmethod def _find_user_id(username, db_connectable): """ Find the user id corresponding to a username. Parameters ---------- username : str The username. db_connectable : SQLAlchemy connectable(engine/connection) or database string URI A connection to the database to use, or its URI. Returns ------- int The user id. Raises ------ ValueError If the username does not exist. """ sql = """ SELECT PiptUser_Id FROM PiptUser WHERE Username=%(username)s """ df = pd.read_sql(sql, con=db_connectable, params=dict(username=username)) # sanity check: does the user exist? if len(df) == 0: raise ValueError( "The username does not exist: {username}".format(username=username) ) return df["PiptUser_Id"][0].item() def _proposal_partners(self, proposal_code): """ Find the partners who are represented among a proposal's investigators. Parameters ---------- proposal_code : str The proposal code. Returns ------- list of str The list of partner codes. """ sql = """ SELECT DISTINCT Partner_Code FROM Partner AS p JOIN Institute AS ins ON p.Partner_Id = ins.Partner_Id JOIN Investigator AS i ON ins.Institute_Id = i.Institute_Id JOIN ProposalInvestigator pi on i.Investigator_Id = pi.Investigator_Id JOIN ProposalCode AS pc ON pi.ProposalCode_Id = pc.ProposalCode_Id WHERE Proposal_Code=%(proposal_code)s """ df = self._query(sql, params=dict(proposal_code=proposal_code)) return df["Partner_Code"].tolist() def _find_tac_member_partners(self): """ Find the partners of whose TACs the user is a member. Returns ------- list of str The partner codes. """ sql = """ SELECT Partner_Code FROM PiptUserTAC AS putac JOIN Partner AS p ON putac.Partner_Id = p.Partner_Id WHERE PiptUser_Id=%(user_id)s """ df = self._query(sql, params=dict(user_id=self._user_id)) return [pc for pc in df["Partner_Code"].tolist()] def _find_tac_chair_partners(self): """ Find the partners of whose TACs the user is chair. Returns ------- list of str The partner codes. """ sql = """ SELECT Partner_Code FROM PiptUserTAC AS putac JOIN Partner AS p ON putac.Partner_Id = p.Partner_Id WHERE PiptUser_Id=%(user_id)s AND Chair=1 """ df = self._query(sql, params=dict(user_id=self._user_id)) return [pc for pc in df["Partner_Code"].tolist()]
26.23607
88
0.565137
34b4b03703e9316af4fe90aded64acd1dff18b1d
40,714
py
Python
mmtbx/validation/molprobity/__init__.py
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
null
null
null
mmtbx/validation/molprobity/__init__.py
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
null
null
null
mmtbx/validation/molprobity/__init__.py
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
null
null
null
""" Classes for MolProbity validation, combining all other analyses in mmtbx.validation, which use the same APIs for storing and displaying results. """ # TODO combine with some parts of mmtbx.kinemage.validation from __future__ import division, print_function from iotbx.cli_parser import CCTBXParser from libtbx.program_template import ProgramTemplate from mmtbx.rotamer import rotamer_eval from mmtbx.validation import validation, residue from mmtbx.validation import model_properties from mmtbx.validation import experimental from mmtbx.validation import rna_validate from mmtbx.validation import clashscore from mmtbx.validation import restraints from mmtbx.validation import ramalyze from mmtbx.validation import omegalyze from mmtbx.validation import rotalyze from mmtbx.validation import cbetadev from mmtbx.validation import waters from mmtbx.validation import sequence from libtbx.str_utils import make_header, make_sub_header, format_value from libtbx import slots_getstate_setstate, \ slots_getstate_setstate_default_initializer from libtbx.utils import multi_out, null_out, show_times, to_str, Sorry import iotbx.pdb import libtbx.load_env import libtbx.phil import mmtbx.model import os.path import sys master_phil_str = """ clashscore = True .type = bool ramalyze = True .type = bool omegalyze = True .type = bool rotalyze = True .type = bool cbetadev = True .type = bool nqh = True .type = bool rna = True .type = bool model_stats = True .type = bool restraints = True .type = bool rfactors = True .type = bool real_space = True .type = bool waters = True .type = bool seq = True .type = bool xtriage = False .type = bool """ def molprobity_flags(): """ Default flags for analyses to perform (all True). """ return libtbx.phil.parse(master_phil_str).extract() class molprobity(slots_getstate_setstate): """ Comprehensive validation. At a minimum this performs the standard MolProbity analyses (ramalyze, rotalyze, cbetadev, clashscore). If a geometry restraints manager is available, the deviations from standard covalent geometry will also be displayed. Passing an fmodel object enables the re-calculation of R-factors and real-space correlation. :param model: model object (required) :param fmodel: mmtbx.f_model.manager object, after bulk solvent/scaling :param fmodel_neutron: separate Fmodel manager for neutron data (used in phenix.refine for join X/N refinement) :param sequences: parsed sequence objects (from iotbx.bioinformatics) :param flags: object containing boolean flags for analyses to perform :param header_info: extracted statistics from PDB file header :param raw_data: input data before French-Wilson treatment, etc. :param unmerged_data: separate unmerged intensities for merging statistics :param all_chain_proxies: object containing restraints information and \ advanced selections from mmtbx.monomer_library.pdb_interpretation :param keep_hydrogens: don't discard and replace existing hydrogens for \ clashscore calculation :param nuclear: use nuclear hydrogen distances (for neutron experiments) :param save_probe_unformatted_file: file name for Probe output suitable for \ display in Coot :param show_hydrogen_outliers: show geometry outliers for hydrogen atoms :param min_cc_two_fofc: Fo-Fc map cutoff for real-space outliers :param n_bins_data: Number of resolution bins for data statistics :param count_anomalous_pairs_separately: count F+ and F- as separate \ reflections (default=False) :param outliers_only: only display validation outliers :param use_pdb_header_resolution_cutoffs: use resolution cutoff(s) \ specified in PDB header for data statistics """ # XXX this is used to distinguish objects of this type from an older (and # now obsolete) class in the phenix tree. molprobity_version_number = (4,1) __slots__ = [ "ramalyze", "omegalyze", "rotalyze", "cbetadev", "clashes", "nqh_flips", "rna", "restraints", "missing_atoms", "data_stats", "neutron_stats", "real_space", "pdb_hierarchy", "crystal_symmetry", "model_stats", "waters", "header_info", "merging", "sequence", "xtriage", "_multi_criterion", "file_name", "kinemage_file", "model_statistics_geometry", "model_statistics_geometry_result", "polygon_stats", "wilson_b", "hydrogens", "model" ] # backwards compatibility with saved results def __setstate__(self, state): for name,value in state.items(): setattr(self, name, value) for name in self.__slots__ : if not hasattr(self, name) : setattr(self, name, None) def __init__(self, model, pdb_hierarchy=None, # keep for mmtbx.validation_summary (multiple models) fmodel=None, fmodel_neutron=None, sequences=None, flags=None, header_info=None, raw_data=None, unmerged_data=None, keep_hydrogens=True, nuclear=False, save_probe_unformatted_file=None, show_hydrogen_outliers=False, min_cc_two_fofc=0.8, n_bins_data=10, count_anomalous_pairs_separately=False, use_internal_variance=True, outliers_only=True, use_pdb_header_resolution_cutoffs=False, file_name=None, ligand_selection=None, rotamer_library="8000", map_params=None): assert rotamer_library == "8000", "data_version given to RotamerEval not recognized." for name in self.__slots__ : setattr(self, name, None) # use objects from model self.model = model if (self.model is not None): pdb_hierarchy = self.model.get_hierarchy() xray_structure = self.model.get_xray_structure() geometry_restraints_manager = self.model.get_restraints_manager().geometry crystal_symmetry = self.model.crystal_symmetry() all_chain_proxies = self.model.all_chain_proxies else: assert (pdb_hierarchy is not None) xray_structure = None geometry_restraints_manager = None crystal_symmetry = None all_chain_proxies = None # very important - the i_seq attributes may be extracted later pdb_hierarchy.atoms().reset_i_seq() self.pdb_hierarchy = pdb_hierarchy if (xray_structure is None): if (fmodel is not None): xray_structure = fmodel.xray_structure elif (crystal_symmetry is not None): xray_structure = pdb_hierarchy.extract_xray_structure( crystal_symmetry=crystal_symmetry) self.crystal_symmetry = crystal_symmetry if (crystal_symmetry is None) and (fmodel is not None): self.crystal_symmetry = fmodel.f_obs().crystal_symmetry() # use maps (fmodel is not used) # run earlier since pdb_hierarchy gets modified use_maps = False if (map_params is not None): use_maps = ( (map_params.input.maps.map_file_name) or ( (map_params.input.maps.map_coefficients_file_name) and (map_params.input.maps.map_coefficients_label) ) ) if (use_maps): if (flags.real_space): self.real_space = experimental.real_space( fmodel=None, model=self.model, cc_min=min_cc_two_fofc, molprobity_map_params=map_params.input.maps) if (flags.waters): self.waters = waters.waters( pdb_hierarchy=pdb_hierarchy, xray_structure=xray_structure, fmodel=None, collect_all=True, molprobity_map_params=map_params.input.maps) self.header_info = header_info if (flags is None): flags = molprobity_flags() import mmtbx.model.statistics self.model_statistics_geometry = mmtbx.model.statistics.geometry( pdb_hierarchy = pdb_hierarchy, geometry_restraints_manager = geometry_restraints_manager, use_hydrogens = keep_hydrogens, use_nuclear = nuclear) self.model_statistics_geometry_result = \ self.model_statistics_geometry.result() self.ramalyze = self.model_statistics_geometry_result.ramachandran.ramalyze self.omegalyze = self.model_statistics_geometry_result.omega.omegalyze self.rotalyze = self.model_statistics_geometry_result.rotamer.rotalyze self.cbetadev = self.model_statistics_geometry_result.c_beta.cbetadev self.clashes = self.model_statistics_geometry_result.clash.clashes if pdb_hierarchy.contains_protein(): self.find_missing_atoms(out=null_out()) if (flags.nqh): self.nqh_flips = clashscore.nqh_flips( pdb_hierarchy=pdb_hierarchy) if (pdb_hierarchy.contains_rna() and flags.rna and libtbx.env.has_module(name="suitename")): if (geometry_restraints_manager is not None): self.rna = rna_validate.rna_validation( pdb_hierarchy=pdb_hierarchy, geometry_restraints_manager=geometry_restraints_manager, outliers_only=outliers_only, params=None) if (flags.model_stats) and (xray_structure is not None): self.model_stats = model_properties.model_statistics( pdb_hierarchy=pdb_hierarchy, xray_structure=xray_structure, all_chain_proxies=all_chain_proxies, ignore_hd=(not nuclear), ligand_selection=ligand_selection) if (geometry_restraints_manager is not None) and (flags.restraints): assert (xray_structure is not None) self.restraints = restraints.combined( pdb_hierarchy=pdb_hierarchy, xray_structure=xray_structure, geometry_restraints_manager=geometry_restraints_manager, ignore_hd=(not nuclear), cdl=getattr(all_chain_proxies, "use_cdl", None)) if (sequences is not None) and (flags.seq): self.sequence = sequence.validation( pdb_hierarchy=pdb_hierarchy, sequences=sequences, log=null_out(), include_secondary_structure=True, extract_coordinates=True) if (fmodel is not None): if (use_pdb_header_resolution_cutoffs) and (header_info is not None): fmodel = fmodel.resolution_filter( d_min=header_info.d_min, d_max=header_info.d_max) if (flags.rfactors): self.data_stats = experimental.data_statistics(fmodel, raw_data=raw_data, n_bins=n_bins_data, count_anomalous_pairs_separately=count_anomalous_pairs_separately) if (not use_maps): # if maps are used, keep previous results if (flags.real_space): self.real_space = experimental.real_space( model=model, fmodel=fmodel, cc_min=min_cc_two_fofc) if (flags.waters): self.waters = waters.waters( pdb_hierarchy=pdb_hierarchy, xray_structure=xray_structure, fmodel=fmodel, collect_all=True) if (unmerged_data is not None): self.merging = experimental.merging_and_model_statistics( f_obs=fmodel.f_obs(), f_model=fmodel.f_model(), r_free_flags=fmodel.r_free_flags(), unmerged_i_obs=unmerged_data, anomalous=count_anomalous_pairs_separately, use_internal_variance=use_internal_variance, n_bins=n_bins_data) if (flags.xtriage): import mmtbx.scaling.xtriage f_model = abs(fmodel.f_model()).set_observation_type_xray_amplitude() if (raw_data is not None): f_model, obs = f_model.common_sets(other=raw_data) else : obs = fmodel.f_obs() self.xtriage = mmtbx.scaling.xtriage.xtriage_analyses( miller_obs=obs, miller_calc=f_model, unmerged_obs=unmerged_data, # XXX some redundancy here... text_out=null_out()) if (fmodel_neutron is not None) and (flags.rfactors): self.neutron_stats = experimental.data_statistics(fmodel_neutron, n_bins=n_bins_data, count_anomalous_pairs_separately=False) if (pdb_hierarchy.models_size() == 1): self._multi_criterion = multi_criterion_view(pdb_hierarchy) # wilson B self.wilson_b = None if (fmodel is not None): self.wilson_b = fmodel.wilson_b() elif (fmodel_neutron is not None): self.wilson_b = fmodel_neutron.wilson_b() # validate hydrogens self.hydrogens = None if self.model is not None and self.model.has_hd(): # import here to avoid circular import issues from mmtbx.hydrogens.validate_H import validate_H, validate_H_results hydrogens = validate_H(model, nuclear) hydrogens.validate_inputs() hydrogens.run() self.hydrogens = validate_H_results(hydrogens.get_results()) # write probe file if needed (CLI and GUI) if (save_probe_unformatted_file is not None): pcm = self.clashes.probe_clashscore_manager try: with open(save_probe_unformatted_file, 'w') as f: f.write(pcm.probe_unformatted) self.clashes.probe_file = save_probe_unformatted_file except IOError as err: raise Sorry('%s could not be written correctly.\n%s' % (save_probe_unformatted_file, err)) def show(self, out=sys.stdout, outliers_only=True, suppress_summary=False, show_percentiles=False): """ Comprehensive output with individual outlier lists, plus summary. """ if (self.xtriage is not None): self.xtriage.summarize_issues().show(out=out) if (self.data_stats is not None): make_header("Experimental data", out=out) self.data_stats.show(out=out, prefix=" ") if (self.real_space is not None): make_sub_header("Residues with poor real-space CC", out=out) self.real_space.show(out=out, prefix=" ") if (self.waters is not None): make_sub_header("Suspicious water molecules", out=out) self.waters.show(out=out, prefix=" ") if (self.model_stats is not None): make_header("Model properties", out=out) self.model_stats.show(prefix=" ", out=out) if (self.sequence is not None): make_header("Sequence validation", out=out) self.sequence.show(out=out) if (self.restraints is not None): make_header("Geometry restraints", out=out) self.restraints.show(out=out, prefix=" ") if (self.hydrogens is not None): make_header("Hydrogen validation", out=out) self.hydrogens.print_results(prefix=' ', log=out) make_header("Molprobity validation", out=out) self.model_statistics_geometry.show(log=out, prefix=" ", uppercase=False) if (self.nqh_flips is not None): make_sub_header("Asn/Gln/His flips", out=out) self.nqh_flips.show(out=out, prefix=" ") if (self.rna is not None): make_header("RNA validation", out=out) self.rna.show(out=out, prefix=" ", outliers_only=outliers_only) if (not suppress_summary): make_header("Summary", out=out) self.show_summary(out=out, prefix=" ", show_percentiles=show_percentiles) return self def summarize(self): """ Condense results into a compact object - for compatibility with (now obsolete) mmtbx.validation_summary, and use in high-throughput analyses """ r_work, r_free, d_min = [None,]*3 if(self.data_stats is not None): r_work, r_free = self.data_stats.r_work, self.data_stats.r_free d_min = self.data_stats.d_min elif (self.header_info is not None): r_work, r_free = self.header_info.r_work, self.header_info.r_free d_min = self.header_info.d_min if(self.restraints is None): rms_bonds = self.header_info.rms_bonds rms_angles = self.header_info.rms_angles return summary( rama_outliers = self.rama_outliers(), rama_favored = self.rama_favored(), rotamer_outliers = self.rota_outliers(), c_beta_deviations = self.cbeta_outliers(), clashscore = self.clashscore(), bond_rmsd = self.rms_bonds(), angle_rmsd = self.rms_angles(), mpscore = self.molprobity_score(), d_min = d_min, r_work = r_work, r_free = r_free, program = getattr(self.header_info, "refinement_program", None)) def show_summary(self, *args, **kwds): """ Print summary of outliers or scores for each analysis. """ return self.summarize().show(*args, **kwds) def find_missing_atoms(self, out=None): ''' Function for finding missing protein atoms Derived from run_find_missing function in phenix/validation/__init__.py ''' if out is None : out = sys.stdout self.missing_atoms = [] # make_header("Finding missing atoms", out=out) try : missing_list = rotamer_eval.eval_sidechain_completeness( pdb_hierarchy=self.pdb_hierarchy, ignore_hydrogens=True, report_whole_res=True, return_ca_pos=True) except Exception as e : print(to_str(e), file=out) else : for (res_info, missing_atoms, xyz) in missing_list : if len(missing_atoms) == 0 : continue chain_id = res_info[0:2].strip() try : resseq = int(res_info[2:6]) except ValueError : # FIXME use hybrid36? print(" warning: indecipherable residue number '%s'" % \ res_info[2:6], file=out) print(res_info) continue alt = res_info[-4] resname = res_info[-3:] # self.get_residue_info((chain_id, resseq, resname, alt), "missing") self.missing_atoms.append((chain_id, "%s %s" % (resname, str(resseq)), alt, ", ".join(missing_atoms), "chain '%s' and resseq %s" % (chain_id, str(resseq)), xyz)) def r_work(self, outer_shell=False): if (outer_shell): return getattr(self.data_stats, "r_work_outer", None) else : return getattr(self.data_stats, "r_work", getattr(self.header_info, "r_work", None)) def r_free(self, outer_shell=False): if (outer_shell): return getattr(self.data_stats, "r_free_outer", None) else : return getattr(self.data_stats, "r_free", getattr(self.header_info, "r_free", None)) def d_min(self): if (self.data_stats is not None): return self.data_stats.d_min elif (self.header_info is not None): return self.header_info.d_min def d_max_min(self, outer_shell=False): if (self.data_stats is not None): if (outer_shell): return self.data_stats.d_max_outer, self.data_stats.d_min_outer else : return self.data_stats.d_max, self.data_stats.d_min def rms_bonds(self): return self.model_statistics_geometry_result.bond.mean def rms_angles(self): return self.model_statistics_geometry_result.angle.mean def rama_favored(self): return self.model_statistics_geometry_result.ramachandran.favored def rama_outliers(self): return self.model_statistics_geometry_result.ramachandran.outliers def rama_allowed(self): return self.model_statistics_geometry_result.ramachandran.allowed def rota_outliers(self): return self.model_statistics_geometry_result.rotamer.outliers def cbeta_outliers(self): return self.model_statistics_geometry_result.c_beta.cbetadev.get_outlier_count() def clashscore(self): return self.model_statistics_geometry_result.clash.score def molprobity_score(self): return self.model_statistics_geometry_result.molprobity_score def b_iso_mean(self): overall_stats = getattr(self.model_stats, "all", None) return getattr(overall_stats, "b_mean", None) def space_group(self): return getattr(self.crystal_symmetry, "space_group", lambda: None)() def space_group_info(self): return getattr(self.crystal_symmetry, "space_group_info", lambda: None)() def unit_cell(self): return getattr(self.crystal_symmetry, "unit_cell", lambda: None)() def twin_law(self): return getattr(self.data_stats, "twin_law", None) def fmodel_statistics_by_resolution(self): """ Returns the resolution bins containing F(model) statistics; see mmtbx.f_model.f_model_info for details. """ fmodel_info = getattr(self.data_stats, "info", None) return getattr(fmodel_info, "bins", None) def fmodel_statistics_graph_data(self): """ Wrapper for fmodel_statistics_by_resolution(), returns object suitable for routines in wxtbx.plots. """ bins = self.fmodel_statistics_by_resolution() if (bins is not None): from mmtbx.f_model.f_model_info import export_bins_table_data return export_bins_table_data(bins) return None def atoms_to_observations_ratio(self, assume_riding_hydrogens=True): n_atoms = self.model_stats.n_atoms if (assume_riding_hydrogens): n_atoms -= self.model_stats.n_hydrogens n_refl = self.data_stats.n_refl assert (n_refl > 0) return n_atoms / n_refl def as_mmcif_records(self) : # TODO raise NotImplementedError() def as_multi_criterion_view(self): if (self._multi_criterion is None): return None if (not self._multi_criterion.is_populated): if (self.real_space is not None): self._multi_criterion.process_outliers(self.real_space.results) if (self.waters is not None): self._multi_criterion.process_outliers(self.waters.results) msr = self.model_statistics_geometry_result self._multi_criterion.process_outliers(msr.ramachandran.ramalyze.results) self._multi_criterion.process_outliers(msr.rotamer.rotalyze.results) self._multi_criterion.process_outliers(msr.c_beta.cbetadev.results) self._multi_criterion.process_outliers(msr.clash.clashes.results) return self._multi_criterion def display_wx_plots(self): if (self.ramalyze is not None): self.ramalyze.display_wx_plots() if (self.rotalyze is not None): self.rotalyze.display_wx_plots() mc = self.as_multi_criterion_view() mc.display_wx_plots() def write_coot_script(self, file_name): """ Write a Python script for displaying outlier lists with click-to-recenter enabled. """ coot_script = libtbx.env.find_in_repositories( relative_path="cctbx_project/cootbx/validation_lists.py", test=os.path.isfile) if (coot_script is None): raise Sorry("Can't find template Python script for Coot.") f = open(file_name, "w") f.write("# script auto-generated by phenix.molprobity\n") f.write("\n") f.write(open(coot_script).read()) f.write("\n") f.write("data = {}\n") msr = self.model_statistics_geometry_result f.write("data['rama'] = %s\n" % msr.ramachandran.ramalyze.as_coot_data()) f.write("data['omega'] = %s\n" % msr.omega.omegalyze.as_coot_data()) f.write("data['rota'] = %s\n" % msr.rotamer.rotalyze.as_coot_data()) f.write("data['cbeta'] = %s\n" % msr.c_beta.cbetadev.as_coot_data()) f.write("data['probe'] = %s\n" % msr.clash.clashes.as_coot_data()) if(msr.clash.clashes.probe_file is not None): f.write("handle_read_draw_probe_dots_unformatted(\"%s\", 0, 0)\n" % msr.clash.clashes.probe_file) f.write("show_probe_dots(True, True)\n") f.write("gui = coot_molprobity_todo_list_gui(data=data)\n") f.close() def get_polygon_statistics(self, stat_names): # missing keys from polygon.keys_to_show: # r_work_cutoffs, r_free_cutoffs # completeness_in_range, completeness_d_min_inf, completeness_6A_inf # solvent_content_via_mask stats = {} for name in stat_names : val = 0.0 if (name == "r_work") : val = self.r_work() elif (name == "r_free") : val = self.r_free() elif (name == "adp_mean_all") : val = self.b_iso_mean() elif (name == "adp_min_all"): val = self.model_stats.all.b_min elif (name == "adp_max_all"): val = self.model_stats.all.b_max elif (name == "wilson_b") : val = self.wilson_b elif (name == "bond_rmsd") : val = self.rms_bonds() elif (name == "bond_max_deviation"): val = self.model_statistics_geometry_result.bond.max elif (name == "angle_rmsd") : val = self.rms_angles() elif (name == "angle_max_deviation"): val = self.model_statistics_geometry_result.angle.max elif (name == "dihedral_rmsd"): val = self.model_statistics_geometry_result.dihedral.mean elif (name == "dihedral_max_deviation"): val = self.model_statistics_geometry_result.dihedral.max elif (name == "planarity_rmsd"): val = self.model_statistics_geometry_result.planarity.mean elif (name == "planarity_max_deviation"): val = self.model_statistics_geometry_result.planarity.max elif (name == "chirality_rmsd"): val = self.model_statistics_geometry_result.chirality.mean elif (name == "chirality_max_deviation"): val = self.model_statistics_geometry_result.chirality.max elif (name == "rama_favored") : val = self.rama_favored() elif (name == "rama_allowed") : val = self.rama_allowed() elif (name == "rama_outliers") : val = self.rama_outliers() elif (name == "rotamer_outliers") : val = self.rota_outliers() elif (name == "clashscore") : val = self.clashscore() stats[name] = val return stats def get_statistics_for_phenix_gui(self): mp = self stats = [ ("R-work", format_value("%.4f", mp.r_work())), ("R-free", format_value("%.4f", mp.r_free())), ("RMS(bonds)", format_value("%.3f", mp.rms_bonds())), ("RMS(angles)", format_value("%.4f", mp.rms_angles())), ("Clashscore", format_value("%.2f", mp.clashscore())), ("MolProbity score", format_value("%.3f", mp.molprobity_score())), ] if (self.neutron_stats is not None): stats.extend([ ("R-work (neutron)", format_value("%.4f", self.neutron_stats.r_work)), ("R-free (neutron)", format_value("%.4f", self.neutron_stats.r_free)), ]) return stats class summary(slots_getstate_setstate_default_initializer): """ Simplified container for overall statistics; replaces class of the same name in mmtbx.command_line.validation_summary. The more complete molprobity class is prefered when analyzing a single structure, but it is considerably larger. """ __slots__ = [ "rama_outliers", "rama_favored", "rotamer_outliers", "c_beta_deviations", "clashscore", "bond_rmsd", "angle_rmsd", "mpscore", "d_min", "r_work", "r_free", "program", ] labels = [ "Ramachandran outliers", " favored", "Rotamer outliers", "C-beta deviations", "Clashscore", "RMS(bonds)", "RMS(angles)", "MolProbity score", "Resolution", "R-work", "R-free", "Refinement program", ] formats = [ "%6.2f", "%6.2f", "%6.2f", "%5d", "%6.2f", "%8.4f", "%6.2f", "%6.2f", "%6.2f", "%8.4f", "%8.4f", "%s", ] def show(self, out=sys.stdout, prefix=" ", show_percentiles=False): def fs(format, value): return format_value(format, value, replace_none_with=("(none)")) maxlen = max([ len(label) for label in self.labels ]) percentiles = {} if (show_percentiles): perc_attr = ["clashscore", "mpscore", "r_work", "r_free"] stats = dict([ (name, getattr(self, name)) for name in perc_attr ]) from mmtbx.polygon import get_statistics_percentiles percentiles = get_statistics_percentiles(self.d_min, stats) for k, name in enumerate(self.__slots__): format = "%%s%%-%ds = %%s" % maxlen if (k < 3): format += " %%" percentile_info = "" if (show_percentiles): percentile = percentiles.get(name, None) if (percentile is not None): format += " (percentile: %s)" percentile_info = "%.1f" % percentile else : format += "%s" else : format += "%s" value = getattr(self, name) if (value is not None): print(format % (prefix, self.labels[k], fs(self.formats[k], value), percentile_info), file=out) return self def iter_molprobity_gui_fields(self): stats = [ ("Ramachandran outliers","%6.2f%%",self.rama_outliers,0.5,0.2,"< 0.2%"), ("Ramachandran favored", "%6.2f%%",self.rama_favored,95,98,"> 98%"), ("Rotamer outliers", "%6.2f%%", self.rotamer_outliers, 2, 1, "1%"), ("C-beta outliers", "%3d ", self.c_beta_deviations, 2, 0, "0"), ("Clashscore", "%6.2f", self.clashscore, 40, 20, None), ("Overall score", "%6.2f", self.mpscore, None, None, None), ] for stat_info in stats : yield stat_info ######################################################################## class pdb_header_info(slots_getstate_setstate): """ Container for information extracted from the PDB header (if available). """ __slots__ = ["d_min", "d_max", "r_work", "r_free", "rms_bonds", "rms_angles", "refinement_program", "n_tls_groups"] def __init__(self, pdb_file, pdb_hierarchy=None): for name in self.__slots__ : setattr(self, name, None) if (pdb_file is not None): import iotbx.pdb.hierarchy from iotbx.pdb import extract_rfactors_resolutions_sigma pdb_in = iotbx.pdb.hierarchy.input(file_name=pdb_file) published_results = extract_rfactors_resolutions_sigma.extract( file_lines=pdb_in.input.remark_section(), file_name=None) if (published_results is not None): self.r_work = published_results.r_work self.r_free = published_results.r_free self.d_min = published_results.high self.d_max = published_results.low self.refinement_program = pdb_in.input.get_program_name() # XXX phenix.refine hack, won't work for other programs lines = open(pdb_file).readlines() for line in lines : if (line.startswith("REMARK Final:")): fields = line.strip().split() self.rms_bonds = float(fields[-4]) self.rms_angles = float(fields[-1]) break if (pdb_hierarchy is not None): tls_groups = pdb_in.input.extract_tls_params(pdb_hierarchy).tls_params if (tls_groups is not None): self.n_tls_groups = len(tls_groups) def is_phenix_refinement(self): return (self.refinement_program is not None and "phenix" in self.refinement_program.lower()) def show(self, out=sys.stdout, prefix="", include_r_factors=True, include_rms_geom=True): if (self.refinement_program is not None): print("%sRefinement program = %s" % (prefix, self.refinement_program), file=out) if (include_r_factors): if (self.d_min is not None): print("%sHigh resolution = %6.2f" % (prefix, self.d_min), file=out) if (self.r_work is not None): print("%sR-work = %8.4f" % (prefix, self.r_work), file=out) if (self.r_free is not None): print("%sR-free = %8.4f" % (prefix, self.r_free), file=out) if (include_rms_geom): if (self.rms_bonds is not None): print("%sRMS(bonds) = %8.4f" % (prefix, self.rms_bonds), file=out) if (self.rms_angles is not None): print("%sRMS(angles) = %6.2f" % (prefix, self.rms_angles), file=out) class residue_multi_criterion(residue): """ Container for multiple outliers associated with a single residue. If data are used, this may include real-space statistics regardless of whether the residue is technically an outlier or not. """ __slots__ = residue.__slots__ + ["outliers", "n_confs", "i_seq"] def __init__(self, **kwds): residue.__init__(self, **kwds) self.outliers = [] def add_outlier(self, outlier): if isinstance(outlier, residue): assert self.is_same_residue_group(outlier) self.outliers.append(outlier) def _find_outlier_type(self, outlier_type=None, outlier_types=(), retrieve_all=False): assert (outlier_type is not None) or (len(outlier_types) > 0) for outlier in self.outliers : if (not outlier.is_outlier()) and (not retrieve_all): continue otype = type(outlier).__name__ if (otype == outlier_type) or (otype in outlier_types): return True return False def is_ramachandran_outlier(self): return self._find_outlier_type("ramachandran") def is_rotamer_outlier(self): return self._find_outlier_type("rotamer") def is_cbeta_outlier(self): return self._find_outlier_type("cbeta") def is_clash_outlier(self): return self._find_outlier_type("clash") def is_geometry_outlier(self): return self._find_outlier_type( outlier_types=["bond","angle","dihedral","chirality","planarity"]) def __str__(self): outliers = [] if self.is_ramachandran_outlier() : outliers.append("rama") if self.is_rotamer_outlier() : outliers.append("rota") if self.is_cbeta_outlier() : outliers.append("cb") if self.is_clash_outlier() : outliers.append("clash") if self.is_geometry_outlier() : outliers.append("geo") if (len(outliers) == 0) : outliers = ["---"] return "%s %s" % (self.id_str(), ",".join(outliers)) def __hash__(self): return self.residue_group_id_str().__hash__() def __cmp__(self, other): return cmp(self.i_seq, other.i_seq) def get_real_space_plot_values(self, use_numpy_NaN=True): for outlier in self.outliers : if (type(outlier).__name__ == 'residue_real_space'): values = [ outlier.b_iso, outlier.cc, outlier.two_fofc, outlier.fmodel ] return values if (use_numpy_NaN): import numpy return [ numpy.NaN ] * 4 else : return [ None ] * 4 def is_map_outlier(self, cc_min=0.8): b_iso, cc, two_fofc, fmodel = self.get_real_space_plot_values(False) if (cc is None): return None elif (cc < cc_min): return True return False def get_outlier_plot_values(self, use_numpy_NaN=True): y = [] if self.is_ramachandran_outlier() : y.append(1) else : y.append(None) if self.is_rotamer_outlier() : y.append(1) else : y.append(None) if self.is_cbeta_outlier() : y.append(1) else : y.append(None) if self.is_clash_outlier() : y.append(1) else : y.append(None) if (use_numpy_NaN): import numpy y_ = [] for yval in y : if (yval is None) : y_.append(numpy.NaN) else : y_.append(yval) return y_ return y class multi_criterion_view(slots_getstate_setstate): """ Container for generating multi-criterion plots and tables from separate lists of outliers. """ __slots__ = ["residues", "is_populated"] def __init__(self, pdb_hierarchy, include_all=False): self.is_populated = False self.residues = {} i_seq = 0 for chain in pdb_hierarchy.only_model().chains(): if (not include_all): if (not chain.is_protein()) and (not chain.is_na()): continue for residue_group in chain.residue_groups(): atom_group = residue_group.atom_groups()[0] resname = atom_group.resname if (resname == "HOH") : continue combined = residue_multi_criterion( chain_id=chain.id, resseq=residue_group.resseq, icode=residue_group.icode, resname=residue_group.atom_groups()[0].resname, altloc="", i_seq=i_seq, n_confs=len(residue_group.atom_groups())) # set_coordinates_from_hierarchy does not seem to work? combined.xyz = atom_group.atoms().extract_xyz().mean() id_str = combined.residue_group_id_str() self.residues[id_str] = combined i_seq += 1 def process_outliers(self, outliers, log=sys.stderr): self.is_populated = True for outlier in outliers : if outlier.is_single_residue_object(): if (outlier.resname == "HOH") : continue id_str = outlier.residue_group_id_str() if (id_str in self.residues): self.residues[id_str].add_outlier(outlier) else : print("missing residue group '%s'" % id_str, file=log) else : have_ids = set([]) for atom in outlier.atoms_info : id_str = atom.residue_group_id_str() if (atom.resname == "HOH") or (id_str in have_ids) : continue if (id_str in self.residues): self.residues[id_str].add_outlier(outlier) have_ids.add(id_str) else : print("missing residue group '%s'" % id_str, file=log) def get_residue_group_data(self, residue_group): residue_validation = self.residues.get(residue_group.id_str(), None) if (residue_validation is None): raise RuntimeError("Can't find residue '%s'" % residue_group.id_str()) return residue_validation def data(self): return sorted(self.residues.values()) def binned_data(self): from mmtbx.validation import graphics return graphics.residue_binner(self.data()) def get_y_limits(self): import numpy values = [] for outlier in self.data(): values.append(outlier.get_real_space_plot_values(False)) values = numpy.array(values).transpose() if (len(values) > 0): rho_min = min(min(values[2]), min(values[3])) rho_max = max(max(values[2]), max(values[3])) return { "rho" : (rho_min, rho_max), "b" : (min(values[0]), max(values[0])), "cc" : (min(values[1]), max(values[1])), } else: raise Sorry('No residues (usually protein or nucleic acid) are available for generating plots.') def display_wx_plots(self, parent=None): import wxtbx.plots.molprobity frame = wxtbx.plots.molprobity.multi_criterion_frame( parent=parent, title="MolProbity multi-criterion plot", validation=self) frame.Show() # ============================================================================= # MolProbity ProgramTemplate class MolProbityTemplate(ProgramTemplate): def get_results_as_PDB_JSON(self): return None # MolProbity CLI Parser class MolProbityParser(CCTBXParser): def add_default_options(self): super(MolProbityParser, self).add_default_options() # add extra CLI option for PDB JSON self.add_argument( '--write-pdb-json', '--write_pdb_json', action='store_true', help='write output in JSON file for PDB' ) # MolProbity run_program function # Since the JSON output comes at the end, there is no easy way to modify the # default run_program function # But, this can be the basis for running other MolProbity validation tools # that can output a JSON file specific for the PDB. def run_molprobity_program(program_class=None, custom_process_arguments=None, args=None, logger=None): ''' Function for running programs using CCTBXParser and the program template :param program_class: ProgramTemplate type (required) :param custom_process_arguments: Custom function to parse unknown arguments (optional) :param args: list of command-line arguments (optional) :param logger: logger (e.g. multi_out) for output (optional) :rtype: whatever is returned from program_class.get_results() ''' assert (program_class is not None) if (args is None): args = sys.argv[1:] # create logger if (logger is None): logger = multi_out() logger.register('stdout', sys.stdout) # start timer t = show_times(out=logger) # create parser parser = MolProbityParser(program_class=program_class, custom_process_arguments=custom_process_arguments, logger=logger) namespace = parser.parse_args(args) # start program print('Starting job', file=logger) print('='*79, file=logger) task = program_class(parser.data_manager, parser.working_phil.extract(), master_phil=parser.master_phil, logger=logger) # custom constructor (optional) task.custom_init() # validate inputs task.validate() # run program task.run() # clean up (optional) task.clean_up() # output JSON file for PDB if (namespace.write_pdb_json): filename, ext = os.path.splitext( os.path.basename(parser.data_manager.get_default_model_name())) filename += '_pdb.json' json_text = task.get_results_as_PDB_JSON() print('\nJSON output') print('-'*79, file=logger) print(' Writing results in JSON format to %s.' % filename, file=logger) parser.data_manager._write_text(None, filename, json_text, overwrite=namespace.overwrite) # stop timer print('', file=logger) print('='*79, file=logger) print('Job complete', file=logger) t() return task.get_results()
36.778681
102
0.672349
1000b0fcac70c571fd2bc6661dc6ca29755365af
1,119
py
Python
tune_parameters.py
wuga214/NCE_Projected_LRec
5628c33e66fec2709a7b4741aabeec90f948ae5c
[ "MIT" ]
30
2018-11-06T22:17:05.000Z
2022-01-31T23:32:10.000Z
tune_parameters.py
wuga214/NCE_Projected_LRec
5628c33e66fec2709a7b4741aabeec90f948ae5c
[ "MIT" ]
2
2018-12-17T06:07:31.000Z
2021-01-09T00:17:14.000Z
tune_parameters.py
wuga214/NCE_Projected_LRec
5628c33e66fec2709a7b4741aabeec90f948ae5c
[ "MIT" ]
7
2018-12-07T05:48:26.000Z
2021-07-28T13:49:42.000Z
import numpy as np import argparse from experiment.tuning import hyper_parameter_tuning from utils.io import load_numpy, save_dataframe_csv, load_yaml from utils.modelnames import models def main(args): params = load_yaml(args.grid) params['models'] = {params['models']: models[params['models']]} R_train = load_numpy(path=args.path, name=args.train) R_valid = load_numpy(path=args.path, name=args.valid) hyper_parameter_tuning(R_train, R_valid, params, save_path=args.name, measure=params['similarity'], gpu_on=args.gpu) if __name__ == "__main__": # Commandline arguments parser = argparse.ArgumentParser(description="ParameterTuning") parser.add_argument('-n', dest='name', default="autorecs_tuning.csv") parser.add_argument('-d', dest='path', default="datax/") parser.add_argument('-t', dest='train', default='Rtrain.npz') parser.add_argument('-v', dest='valid', default='Rvalid.npz') parser.add_argument('-y', dest='grid', default='config/default.yml') parser.add_argument('-gpu', dest='gpu', action='store_true') args = parser.parse_args() main(args)
43.038462
120
0.723861
f74ed9c32ce2f3b2bef22c7458ed2566fe9abcdf
5,048
py
Python
dashboard/pagination.py
encode/dashboard
a184d749a3a806f8d65574b5712ddce24169c677
[ "BSD-3-Clause" ]
92
2020-04-09T17:26:33.000Z
2022-03-21T02:23:59.000Z
dashboard/pagination.py
encode/staradmin
a184d749a3a806f8d65574b5712ddce24169c677
[ "BSD-3-Clause" ]
6
2020-04-21T14:01:56.000Z
2021-11-23T14:29:50.000Z
dashboard/pagination.py
encode/staradmin
a184d749a3a806f8d65574b5712ddce24169c677
[ "BSD-3-Clause" ]
7
2020-04-13T13:59:07.000Z
2022-03-13T02:18:41.000Z
import typing from dataclasses import dataclass from starlette.datastructures import URL, QueryParams @dataclass class PageControl: text: str url: URL = None is_active: bool = False is_disabled: bool = False def inclusive_range(st: int, en: int, cutoff: int) -> typing.List[int]: """ Return an inclusive range from 'st' to 'en', bounded within a minimum of 1 and a maximum of 'cutoff'. """ st = max(st, 1) en = min(en, cutoff) return list(range(st, en + 1)) def get_page_number(url: URL) -> int: """ Return a page number specified in the URL query parameters. """ query_params = QueryParams(url.query) try: return int(query_params.get("page", default="1")) except (TypeError, ValueError): return 1 def get_page_controls( url: URL, current_page: int, total_pages: int ) -> typing.List[PageControl]: """ Returns a list of pagination controls, using GitHub's style for rendering which controls should be displayed. See eg. issue pages in GitHub. Previous [1] 2 3 4 5 ... 14 15 Next """ assert total_pages >= 1 assert current_page >= 1 assert current_page <= total_pages # If we've only got a single page, then don't include pagination controls. if total_pages == 1: return [] # We always have 5 contextual page numbers around the current page. if current_page <= 2: # If we're on the first or second-to-first page, then our 5 contextual # pages should start from the first page onwards. main_block = inclusive_range(1, 5, cutoff=total_pages) elif current_page >= total_pages - 1: # If we're on the last or second-to-last page, then our 5 contextual # pages should end with the final page backwards. main_block = inclusive_range(total_pages - 4, total_pages, cutoff=total_pages) else: # All other cases, our 5 contextual pages should be 2 pages on either # side of our current page. main_block = inclusive_range( current_page - 2, current_page + 2, cutoff=total_pages ) # We always have 2 contextual page numbers at the start. start_block = inclusive_range(1, 2, cutoff=total_pages) if main_block[0] == 4: # If we've only got a gap of one between the start and main blocks # then fill in the gap with a page marker. # | 1 2 3 4 5 [6] 7 8 start_block += [3] elif main_block[0] > 4: # If we've got a gap of more that one between the start and main # blocks then fill in the gap with an ellipsis marker. # | 1 2 … 5 6 [7] 8 9 start_block += [None] # We always have 2 contextual page numbers at the end. end_block = inclusive_range(total_pages - 1, total_pages, cutoff=total_pages) if main_block[-1] == total_pages - 3: # If we've got a gap of one between the end and main blocks then # fill in the gap with an page marker. # 92 93 [94] 95 96 97 98 99 | end_block = [total_pages - 2] + end_block elif main_block[-1] < total_pages - 3: # If we've got a gap of more that one between the end and main # blocks then fill in the gap with an ellipsis marker. # 91 92 [93] 94 95 … 98 99 | end_block = [None] + end_block # We've got a list of integer/None values representing which pages to # display in the controls. Now we use those to generate the actual # PageControl instances. seen_numbers = set() controls = [] # Add a 'Previous' page control. if current_page == 1: previous_url = None previous_disabled = True elif current_page == 2: previous_url = url.remove_query_params("page") previous_disabled = False else: previous_url = url.include_query_params(page=current_page - 1) previous_disabled = False previous = PageControl( text="Previous", url=previous_url, is_disabled=previous_disabled ) controls.append(previous) for page_number in start_block + main_block + end_block: if page_number is None: gap = PageControl(text="…", is_disabled=True) controls.append(gap) elif page_number not in seen_numbers: seen_numbers.add(page_number) if page_number == 1: page_url = url.remove_query_params("page") else: page_url = url.include_query_params(page=page_number) page = PageControl( text=str(page_number), url=page_url, is_active=page_number == current_page, ) controls.append(page) # Add a 'Next' page control. if current_page == total_pages: next_url = None next_disabled = True else: next_url = url.include_query_params(page=current_page + 1) next_disabled = False next = PageControl(text="Next", url=next_url, is_disabled=next_disabled) controls.append(next) return controls
34.813793
86
0.636094
ea148b95f654a211233610ea11c4d24114cec630
958
py
Python
test/test_list_integrations_response.py
Logicworks/opsgenie-python-sdk
244c4c40ddcc25e70df5ba4425ab8d7c8da59c18
[ "Apache-2.0" ]
null
null
null
test/test_list_integrations_response.py
Logicworks/opsgenie-python-sdk
244c4c40ddcc25e70df5ba4425ab8d7c8da59c18
[ "Apache-2.0" ]
null
null
null
test/test_list_integrations_response.py
Logicworks/opsgenie-python-sdk
244c4c40ddcc25e70df5ba4425ab8d7c8da59c18
[ "Apache-2.0" ]
1
2020-11-07T11:27:13.000Z
2020-11-07T11:27:13.000Z
# coding: utf-8 """ OpsGenie REST API OpsGenie OpenAPI Specification # noqa: E501 OpenAPI spec version: 2.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import opsgenie_swagger from opsgenie_swagger.models.list_integrations_response import ListIntegrationsResponse # noqa: E501 from opsgenie_swagger.rest import ApiException class TestListIntegrationsResponse(unittest.TestCase): """ListIntegrationsResponse unit test stubs""" def setUp(self): pass def tearDown(self): pass def testListIntegrationsResponse(self): """Test ListIntegrationsResponse""" # FIXME: construct object with mandatory attributes with example values # model = opsgenie_swagger.models.list_integrations_response.ListIntegrationsResponse() # noqa: E501 pass if __name__ == '__main__': unittest.main()
23.365854
109
0.730689
be088c2a6648da2fb69c990b45fea7e3bc696d38
282
py
Python
Python/DefangIP.py
lywc20/daily-programming
78529e535aea5bda409e5a2a009274dca7011e29
[ "MIT" ]
null
null
null
Python/DefangIP.py
lywc20/daily-programming
78529e535aea5bda409e5a2a009274dca7011e29
[ "MIT" ]
null
null
null
Python/DefangIP.py
lywc20/daily-programming
78529e535aea5bda409e5a2a009274dca7011e29
[ "MIT" ]
null
null
null
def defangIPaddr(address): #convert to mutable list lAddress = list(address) delim = '' for i in range(len(lAddress)): if lAddress[i] == ".": lAddress[i] = "[.]" return delim.join(lAddress) ip = "1.1.1.1.1" print(defangIPaddr(ip))
16.588235
34
0.556738
424a84acc68ad320302adc3d409aa491347d787c
1,693
py
Python
hata/ext/slash/client_wrapper_extension.py
Multiface24111/hata
cd28f9ef158e347363669cc8d1d49db0ff41aba0
[ "0BSD" ]
173
2019-06-14T20:25:00.000Z
2022-03-21T19:36:10.000Z
hata/ext/slash/client_wrapper_extension.py
Multiface24111/hata
cd28f9ef158e347363669cc8d1d49db0ff41aba0
[ "0BSD" ]
52
2020-01-03T17:05:14.000Z
2022-03-31T11:39:50.000Z
hata/ext/slash/client_wrapper_extension.py
Multiface24111/hata
cd28f9ef158e347363669cc8d1d49db0ff41aba0
[ "0BSD" ]
47
2019-11-09T08:46:45.000Z
2022-03-31T14:33:34.000Z
__all__ = () from ...backend.utils import KeepType from ...discord.client.utils import ClientWrapper from ...discord.events.handling_helpers import _EventHandlerManagerRouter from .application_command import SlasherApplicationCommand from .slasher import Slasher def interactions_getter(manager_router): """ Gets the slash command processer using `Client.slasher` of an ``_EventHandlerManagerRouter``. Parameters ---------- manager_router : ``_EventHandlerManagerRouter`` The caller manager router. Returns ------- handlers : `list` of ``Slasher`` instances """ handlers = [] for client in manager_router.parent.clients: manager = getattr(client, 'interactions', None) if manager is None: continue handler = manager.parent if isinstance(handler, Slasher): handlers.append(handler) return handlers def from_class_constructor(klass): """ Creates a slash command from the given class. Raises ------ BaseException Any exception raised by the respective ``SlasherApplicationCommand`` constructor. """ return SlasherApplicationCommand.from_class(klass) @KeepType(ClientWrapper) class ClientWrapper: @property def interactions(self): """ Returns a ``_EventHandlerManagerRouter`` instance, with what slash commands can be added to more clients at the same time. Returns ------- event_handler_manager_router : ``_EventHandlerManagerRouter`` """ return _EventHandlerManagerRouter(self, interactions_getter, from_class_constructor)
26.453125
119
0.668636
be34d11c1611ac231e35cfbdbe5b460d2a618197
1,633
py
Python
grr/client/grr_response_client/client_actions/operating_system.py
dekoder/grr
27ba38dc0f5ad4f3e0cdbfb146a0a789e3b0d27b
[ "Apache-2.0" ]
3
2018-09-30T01:31:29.000Z
2019-04-22T11:44:54.000Z
grr/client/grr_response_client/client_actions/operating_system.py
tomchop/grr
27ba38dc0f5ad4f3e0cdbfb146a0a789e3b0d27b
[ "Apache-2.0" ]
1
2022-03-02T09:58:05.000Z
2022-03-02T09:58:05.000Z
grr/client/grr_response_client/client_actions/operating_system.py
tomchop/grr
27ba38dc0f5ad4f3e0cdbfb146a0a789e3b0d27b
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python """A facade to operating system dependent client actions.""" from __future__ import unicode_literals import platform # pylint: disable=g-import-not-at-top # pylint: disable=g-wrong-blank-lines # These imports populate the Action registry if platform.system() == "Linux": from grr_response_client.client_actions.linux import linux submodule = linux elif platform.system() == "Windows": from grr_response_client.client_actions.windows import windows submodule = windows elif platform.system() == "Darwin": from grr_response_client.client_actions.osx import osx import grr_response_client.client_actions.osx.local # pylint: disable=unused-import submodule = osx # pylint: enable=g-import-not-at-top # pylint: enable=g-wrong-blank-lines # pylint: disable=invalid-name EnumerateInterfaces = submodule.EnumerateInterfaces EnumerateInterfacesFromClient = submodule.EnumerateInterfacesFromClient EnumerateFilesystems = submodule.EnumerateFilesystems EnumerateFilesystemsFromClient = submodule.EnumerateFilesystemsFromClient if platform.system() == "Linux": EnumerateUsers = submodule.EnumerateUsers EnumerateUsersFromClient = submodule.EnumerateUsersFromClient else: EnumerateUsers = None EnumerateUsersFromClient = None GetInstallDate = submodule.GetInstallDate if platform.system() == "Darwin": OSXEnumerateRunningServices = submodule.OSXEnumerateRunningServices EnumerateRunningServices = submodule.OSXEnumerateRunningServicesFromClient else: OSXEnumerateRunningServices = None EnumerateRunningServices = None Uninstall = submodule.Uninstall UpdateAgent = submodule.UpdateAgent
34.744681
86
0.818739
1dea2b1ae7abaae13eb07f27e2fd379b8fee2af0
784
py
Python
object_detection/YOLO_V3/models/layers/blocks_module.py
Gaurav14cs17/Computer-Vision
49054f6984bf3833bf0529da58c4d216bcc6b5bf
[ "MIT" ]
null
null
null
object_detection/YOLO_V3/models/layers/blocks_module.py
Gaurav14cs17/Computer-Vision
49054f6984bf3833bf0529da58c4d216bcc6b5bf
[ "MIT" ]
null
null
null
object_detection/YOLO_V3/models/layers/blocks_module.py
Gaurav14cs17/Computer-Vision
49054f6984bf3833bf0529da58c4d216bcc6b5bf
[ "MIT" ]
null
null
null
import torch.nn as nn from ..layers.conv_module import Convolutional class Residual_block(nn.Module): def __init__(self, filters_in=None, filters_out=None, filters_medium=None): super(Residual_block, self).__init__() self.__conv1 = Convolutional(filters_in=filters_in, filters_out=filters_medium, kernel_size=1, stride=1, padding=0, batch_norm="bn", activate="leaky") self.__conv2 = Convolutional(filters_in=filters_medium, filters_out=filters_out, kernel_size=3, stride=1, padding=1, batch_norm="bn", activate="leaky") def forward(self, x): ''' x - > ( -1 , c , n , m ) ''' r = self.__conv1(x) r = self.__conv2(r) return x + r
41.263158
113
0.604592
85871e733fe05835e1e9719ccdbdf17cbe1888cd
10,476
py
Python
tests/html_quotations_test.py
a-listware/talon
e9f65b3a8097193323829bccaf5233e02463265e
[ "Apache-2.0" ]
null
null
null
tests/html_quotations_test.py
a-listware/talon
e9f65b3a8097193323829bccaf5233e02463265e
[ "Apache-2.0" ]
null
null
null
tests/html_quotations_test.py
a-listware/talon
e9f65b3a8097193323829bccaf5233e02463265e
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import absolute_import # noinspection PyUnresolvedReferences import re from unittest.mock import Mock, patch from nose.tools import assert_false, assert_true, eq_, ok_ from tests.fixtures import (OLK_SRC_BODY_SECTION, REPLY_QUOTATIONS_SHARE_BLOCK, REPLY_SEPARATED_BY_HR) from talon import quotations, utils as u RE_WHITESPACE = re.compile(r"\s") RE_DOUBLE_WHITESPACE = re.compile(r"\s") def test_quotation_splitter_inside_blockquote(): msg_body = """Reply <blockquote> <div> On 11-Apr-2011, at 6:54 PM, Bob &lt;bob@example.com&gt; wrote: </div> <div> Test </div> </blockquote>""" eq_("<html><head></head><body>Reply</body></html>", RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def test_quotation_splitter_outside_blockquote(): msg_body = """Reply <div> On 11-Apr-2011, at 6:54 PM, Bob &lt;bob@example.com&gt; wrote: </div> <blockquote> <div> Test </div> </blockquote> """ eq_("<html><head></head><body>Reply</body></html>", RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def test_regular_blockquote(): msg_body = """Reply <blockquote>Regular</blockquote> <div> On 11-Apr-2011, at 6:54 PM, Bob &lt;bob@example.com&gt; wrote: </div> <blockquote> <div> <blockquote>Nested</blockquote> </div> </blockquote> """ eq_("<html><head></head><body>Reply<blockquote>Regular</blockquote></body></html>", RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def test_no_blockquote(): msg_body = """ <html> <body> Reply <div> On 11-Apr-2011, at 6:54 PM, Bob &lt;bob@example.com&gt; wrote: </div> <div> Test </div> </body> </html> """ reply = """ <html> <head></head> <body> Reply </body></html>""" eq_(RE_WHITESPACE.sub('', reply), RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def test_empty_body(): eq_('', quotations.extract_from_html('')) def test_validate_output_html(): msg_body = """Reply <div> On 11-Apr-2011, at 6:54 PM, Bob &lt;bob@example.com&gt; wrote: <blockquote> <div> Test </div> </blockquote> </div> <div/> """ out = quotations.extract_from_html(msg_body) ok_('<html>' in out and '</html>' in out, 'Invalid HTML - <html>/</html> tag not present') ok_('<div/>' not in out, 'Invalid HTML output - <div/> element is not valid') def test_gmail_quote(): msg_body = """Reply <div class="gmail_quote"> <div class="gmail_quote"> On 11-Apr-2011, at 6:54 PM, Bob &lt;bob@example.com&gt; wrote: <div> Test </div> </div> </div>""" eq_("<html><head></head><body>Reply</body></html>", RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def test_gmail_quote_compact(): msg_body = 'Reply' \ '<div class="gmail_quote">' \ '<div class="gmail_quote">On 11-Apr-2011, at 6:54 PM, Bob &lt;bob@example.com&gt; wrote:' \ '<div>Test</div>' \ '</div>' \ '</div>' eq_("<html><head></head><body>Reply</body></html>", RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def test_gmail_quote_blockquote(): msg_body = """Message <blockquote class="gmail_quote"> <div class="gmail_default"> My name is William Shakespeare. <br/> </div> </blockquote>""" eq_(RE_WHITESPACE.sub('', msg_body), RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def test_unicode_in_reply(): msg_body = u"""Reply \xa0 \xa0 Text<br> <div> <br> </div> <blockquote> Quote </blockquote>""" eq_("<html><head></head><body>Reply&#160;&#160;Text<br><div><br></div>" "</body></html>", RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def test_blockquote_disclaimer(): msg_body = """ <html> <body> <div> <div> message </div> <blockquote> Quote </blockquote> </div> <div> disclaimer </div> </body> </html> """ stripped_html = """ <html> <head></head> <body> <div> <div> message </div> </div> <div> disclaimer </div> </body> </html> """ eq_(RE_WHITESPACE.sub('', stripped_html), RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def test_date_block(): msg_body = """ <div> message<br> <div> <hr> Date: Fri, 23 Mar 2012 12:35:31 -0600<br> To: <a href="mailto:bob@example.com">bob@example.com</a><br> From: <a href="mailto:rob@example.com">rob@example.com</a><br> Subject: You Have New Mail From Mary!<br><br> text </div> </div> """ eq_('<html><head></head><body><div>message<br></div></body></html>', RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def test_from_block(): msg_body = """<div> message<br> <div> <hr> From: <a href="mailto:bob@example.com">bob@example.com</a><br> Date: Fri, 23 Mar 2012 12:35:31 -0600<br> To: <a href="mailto:rob@example.com">rob@example.com</a><br> Subject: You Have New Mail From Mary!<br><br> text </div></div> """ eq_('<html><head></head><body><div>message<br></div></body></html>', RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def test_reply_shares_div_with_from_block(): msg_body = ''' <body> <div> Blah<br><br> <hr>Date: Tue, 22 May 2012 18:29:16 -0600<br> To: xx@hotmail.ca<br> From: quickemail@ashleymadison.com<br> Subject: You Have New Mail From x!<br><br> </div> </body>''' eq_('<html><head></head><body><div>Blah<br><br></div></body></html>', RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def test_reply_quotations_share_block(): stripped_html = quotations.extract_from_plain(REPLY_QUOTATIONS_SHARE_BLOCK) ok_(stripped_html) ok_('From' not in stripped_html) def test_OLK_SRC_BODY_SECTION_stripped(): eq_('<html><head></head><body><div>Reply</div></body></html>', RE_WHITESPACE.sub( '', quotations.extract_from_html(OLK_SRC_BODY_SECTION))) def test_reply_separated_by_hr(): eq_('<html><head></head><body><div>Hi<div>there</div></div></body></html>', RE_WHITESPACE.sub( '', quotations.extract_from_html(REPLY_SEPARATED_BY_HR))) def test_from_block_and_quotations_in_separate_divs(): msg_body = ''' Reply <div> <hr/> <div> <font> <b>From: bob@example.com</b> <b>Date: Thu, 24 Mar 2016 08:07:12 -0700</b> </font> </div> <div> Quoted message </div> </div> ''' eq_('<html><head></head><body>Reply<div><hr></div></body></html>', RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) def extract_reply_and_check(filename): import sys kwargs = {} if sys.version_info > (3, 0): kwargs["encoding"] = "utf8" f = open(filename, **kwargs) msg_body = f.read() reply = quotations.extract_from_html(msg_body) plain_reply = u.html_to_text(reply) eq_(RE_WHITESPACE.sub('', "Hi. I am fine.\n\nThanks,\nAlex"), RE_WHITESPACE.sub('', plain_reply)) def test_gmail_reply(): extract_reply_and_check("tests/fixtures/html_replies/gmail.html") def test_mail_ru_reply(): extract_reply_and_check("tests/fixtures/html_replies/mail_ru.html") def test_hotmail_reply(): extract_reply_and_check("tests/fixtures/html_replies/hotmail.html") def test_ms_outlook_2003_reply(): extract_reply_and_check("tests/fixtures/html_replies/ms_outlook_2003.html") def test_ms_outlook_2007_reply(): extract_reply_and_check("tests/fixtures/html_replies/ms_outlook_2007.html") def test_ms_outlook_2010_reply(): extract_reply_and_check("tests/fixtures/html_replies/ms_outlook_2010.html") def test_thunderbird_reply(): extract_reply_and_check("tests/fixtures/html_replies/thunderbird.html") def test_windows_mail_reply(): extract_reply_and_check("tests/fixtures/html_replies/windows_mail.html") def test_yandex_ru_reply(): extract_reply_and_check("tests/fixtures/html_replies/yandex_ru.html") def test_CRLF(): """CR is not converted to '&#13;' """ symbol = '&#13;' extracted = quotations.extract_from_html('<html>\r\n</html>') assert_false(symbol in extracted) eq_('<html></html>', RE_WHITESPACE.sub('', extracted)) msg_body = """My reply <blockquote> <div> On 11-Apr-2011, at 6:54 PM, Bob &lt;bob@example.com&gt; wrote: </div> <div> Test </div> </blockquote>""" msg_body = msg_body.replace('\n', '\r\n') extracted = quotations.extract_from_html(msg_body) assert_false(symbol in extracted) # Keep new lines otherwise "My reply" becomes one word - "Myreply" eq_("<html><head></head><body>My\nreply\n</body></html>", extracted) def test_gmail_forwarded_msg(): msg_body = """<div dir="ltr"><br><div class="gmail_quote">---------- Forwarded message ----------<br>From: <b class="gmail_sendername">Bob</b> <span dir="ltr">&lt;<a href="mailto:bob@example.com">bob@example.com</a>&gt;</span><br>Date: Fri, Feb 11, 2010 at 5:59 PM<br>Subject: Bob WFH today<br>To: Mary &lt;<a href="mailto:mary@example.com">mary@example.com</a>&gt;<br><br><br><div dir="ltr">eom</div> </div><br></div>""" extracted = quotations.extract_from_html(msg_body) eq_(RE_WHITESPACE.sub('', msg_body), RE_WHITESPACE.sub('', extracted)) def test_readable_html_empty(): msg_body = """ <blockquote> Reply <div> On 11-Apr-2011, at 6:54 PM, Bob &lt;bob@example.com&gt; wrote: </div> <div> Test </div> </blockquote>""" eq_(RE_WHITESPACE.sub('', msg_body), RE_WHITESPACE.sub('', quotations.extract_from_html(msg_body))) @patch.object(quotations, 'html_document_fromstring', Mock(return_value=None)) def test_bad_html(): bad_html = "<html></html>" eq_(bad_html, quotations.extract_from_html(bad_html)) def test_remove_namespaces(): msg_body = """ <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns="http://www.w3.org/TR/REC-html40"> <body> <o:p>Dear Sir,</o:p> <o:p>Thank you for the email.</o:p> <blockquote>thing</blockquote> </body> </html> """ rendered = quotations.extract_from_html(msg_body) assert_true("<p>" in rendered) assert_true("xmlns" in rendered) assert_true("<o:p>" not in rendered) assert_true("<xmlns:o>" not in rendered)
23.917808
405
0.643948
66f701627e391a8dd856cd06cb1658959055c464
2,952
py
Python
ros/src/twist_controller/twist_controller.py
Abosobaie/CarND-Capstone-Project
ed26f4586120588b325916f2086420ef583be164
[ "MIT" ]
null
null
null
ros/src/twist_controller/twist_controller.py
Abosobaie/CarND-Capstone-Project
ed26f4586120588b325916f2086420ef583be164
[ "MIT" ]
9
2020-01-28T22:18:21.000Z
2022-03-12T00:05:03.000Z
ros/src/twist_controller/twist_controller.py
Jianshu-Wang/CarND-Capstone-Project
ed26f4586120588b325916f2086420ef583be164
[ "MIT" ]
null
null
null
import rospy from yaw_controller import YawController from pid import PID from lowpass import LowPassFilter GAS_DENSITY = 2.858 ONE_MPH = 0.44704 class Controller(object): def __init__(self, vehicle_mass, fuel_capacity, brake_deadband, decel_limit, accel_limit, wheel_radius, wheel_base, steer_ratio, max_lat_accel, max_steer_angle): #Yaw Controller self.yaw_controller = YawController(wheel_base, steer_ratio, 0.1, max_lat_accel, max_steer_angle) #PID kp = 2 ki = 0.0004 kd = 0.1 mn = 0. # Minimum throttle value mx = 0.2 # Maximum throttle value self.throttle_controller = PID(kp, ki, kd, mn, max) #LowPassFilter because velocity coming on messages are noise, so, we need to filter high frequency noise tau = 0.5 ts = 0.02 #sample time self.vel_lpf = LowPassFilter(tau,ts) self.vehicle_mass = vehicle_mass self.fuel_capacity = fuel_capacity self.brake_deadband = brake_deadband self.decel_limit = decel_limit self.accel_limit = accel_limit self.wheel_radius = wheel_radius self.wheel_base = wheel_base self.steer_ratio = steer_ratio self.max_lat_accel = max_lat_accel self.max_steer_angle = max_steer_angle self.last_vel = 0 self.brake = 0 self.last_time = rospy.get_time() def control(self, current_vel, dbw_enabled, linear_vel, angular_vel): # Return throttle, brake, steer if not dbw_enabled: self.throttle_controller.reset() return 0., 0., 0. current_vel = self.vel_lpf.filt(current_vel) steering = self.yaw_controller.get_steering(linear_vel, angular_vel , current_vel) vel_error = linear_vel - current_vel self.last_vel = current_vel current_time = rospy.get_time() sample_time = current_time - self.last_time self.last_time = current_time throttle = self.throttle_controller.step(vel_error, sample_time) brake = 0 if linear_vel == 0. and current_vel < 0.1: throttle = 0 self.brake = 700 # 700 Nm to hold the car in place if we are stopped at traffic light. print("Condition1", current_vel, linear_vel) elif throttle < 0.1 and vel_error < 0: throttle = 0 decelerator = max(vel_error,self.decel_limit) self.brake = abs(decelerator) * (self.vehicle_mass + (self.fuel_capacity * GAS_DENSITY))* self.wheel_radius # Torque is in Nm units print("Condition2", current_vel, linear_vel) else: self.brake = 0 print("Condition3", current_vel, linear_vel) return throttle, self.brake, steering
31.741935
144
0.614499
ec6bfc8bc2e6c1a6a670afb35530468e97fd07ef
10,192
py
Python
climetlab/readers/netcdf.py
emadehsan/climetlab
82d3911565179f66ae19d17d96e94fc7456e7725
[ "Apache-2.0" ]
182
2020-07-24T14:44:32.000Z
2022-03-31T12:25:28.000Z
climetlab/readers/netcdf.py
emadehsan/climetlab
82d3911565179f66ae19d17d96e94fc7456e7725
[ "Apache-2.0" ]
30
2020-07-22T10:29:12.000Z
2022-03-31T13:55:04.000Z
climetlab/readers/netcdf.py
emadehsan/climetlab
82d3911565179f66ae19d17d96e94fc7456e7725
[ "Apache-2.0" ]
32
2020-09-12T14:02:11.000Z
2022-02-17T08:18:37.000Z
# (C) Copyright 2020 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation # nor does it submit to any jurisdiction. # # The code is copied from skinnywms, and we should combile later import datetime from contextlib import closing from itertools import product import numpy as np import xarray as xr from climetlab.core import Base from climetlab.utils.bbox import BoundingBox from climetlab.utils.dates import to_datetime from . import Reader def as_datetime(self, time): return datetime.datetime.strptime(str(time)[:19], "%Y-%m-%dT%H:%M:%S") def as_level(self, level): n = float(level) if int(n) == n: return int(n) return n class Slice: def __init__(self, name, value, index, is_dimension, is_info): self.name = name self.index = index self.value = value self.is_dimension = (not is_info,) self.is_info = is_info def __repr__(self): return "[%s:%s=%s]" % (self.name, self.index, self.value) class TimeSlice(Slice): pass class Coordinate: def __init__(self, variable, info): self.variable = variable # We only support 1D coordinate for now # assert len(variable.dims) == 1 self.is_info = info self.is_dimension = not info if variable.values.ndim == 0: self.values = [self.convert(variable.values)] else: self.values = [self.convert(t) for t in variable.values.flatten()] def make_slice(self, value): return self.slice_class( self.variable.name, value, self.values.index(value), self.is_dimension, self.is_info, ) def __repr__(self): return "%s[name=%s,values=%s]" % ( self.__class__.__name__, self.variable.name, len(self.values), ) class TimeCoordinate(Coordinate): slice_class = TimeSlice is_dimension = True convert = as_datetime class LevelCoordinate(Coordinate): # This class is just in case we want to specialise # 'level', othewise, it is the same as OtherCoordinate slice_class = Slice is_dimension = False convert = as_level class OtherCoordinate(Coordinate): slice_class = Slice is_dimension = False convert = as_level class DataSet: def __init__(self, ds): self._ds = ds self._bbox = {} self._cache = {} @property def data_vars(self): return self._ds.data_vars def __getitem__(self, key): if key not in self._cache: self._cache[key] = self._ds[key] return self._cache[key] def bbox(self, variable): data_array = self[variable] dims = data_array.dims lat = dims[-2] lon = dims[-1] if (lat, lon) not in self._bbox: dims = data_array.dims latitude = data_array[lat] longitude = data_array[lon] self._bbox[(lat, lon)] = ( np.amax(latitude.data), np.amin(longitude.data), np.amin(latitude.data), np.amax(longitude.data), ) return self._bbox[(lat, lon)] class NetCDFField(Base): def __init__(self, path, ds, variable, slices, non_dim_coords): data_array = ds[variable] self.north, self.west, self.south, self.east = ds.bbox(variable) self.path = path self.variable = variable self.slices = slices self.non_dim_coords = non_dim_coords self.name = self.variable self.title = getattr( data_array, "long_name", getattr(data_array, "standard_name", self.variable), ) self.time = non_dim_coords.get("valid_time", non_dim_coords.get("time")) # print('====', non_dim_coords) for s in self.slices: if isinstance(s, TimeSlice): self.time = s.value if s.is_info: self.title += " (" + s.name + "=" + str(s.value) + ")" def plot_map(self, backend): dimensions = dict((s.name, s.index) for s in self.slices) backend.bounding_box( north=self.north, south=self.south, west=self.west, east=self.east ) backend.plot_netcdf(self.path, self.variable, dimensions) def __repr__(self): return "NetCDFField[%r,%r]" % (self.variable, self.slices) def to_bounding_box(self): return BoundingBox( north=self.north, south=self.south, east=self.east, west=self.west ) # class MultiNetcdfReaders(GriddedMultiReaders): # engine = "netcdf4" class NetCDFReader(Reader): open_mfdataset_backend_kwargs = {} open_mfdataset_engine = None def __init__(self, source, path): super().__init__(source, path) self.fields = None def _scan(self): if self.fields is None: self.fields = self.get_fields() def __repr__(self): return "NetCDFReader(%s)" % (self.path,) def __iter__(self): self._scan() return iter(self.fields) def __len__(self): self._scan() return len(self.fields) def __getitem__(self, n): self._scan() return self.fields[n] def get_fields(self): with closing( xr.open_mfdataset(self.path, combine="by_coords", engine="netcdf4") ) as ds: # or nested return self._get_fields(DataSet(ds)) def _get_fields(self, ds): # noqa C901 # Select only geographical variables has_lat = False has_lon = False fields = [] skip = set() for name in ds.data_vars: v = ds[name] skip.update(getattr(v, "coordinates", "").split(" ")) skip.update(getattr(v, "bounds", "").split(" ")) skip.update(getattr(v, "grid_mapping", "").split(" ")) for name in ds.data_vars: if name in skip: continue v = ds[name] coordinates = [] # self.log.info('Scanning file: %s var=%s coords=%s', self.path, name, v.coords) info = [value for value in v.coords if value not in v.dims] non_dim_coords = {} for coord in v.coords: if coord not in v.dims: non_dim_coords[coord] = ds[coord].values continue c = ds[coord] # self.log.info("COORD %s %s %s %s", coord, type(coord), hasattr(c, 'calendar'), c) standard_name = getattr(c, "standard_name", None) axis = getattr(c, "axis", None) long_name = getattr(c, "long_name", None) use = False if ( standard_name in ("longitude", "projection_x_coordinate") or (long_name == "longitude") or (axis == "X") ): has_lon = True use = True if ( standard_name in ("latitude", "projection_y_coordinate") or (long_name == "latitude") or (axis == "Y") ): has_lat = True use = True # Of course, not every one sets the standard_name if standard_name in ("time", "forecast_reference_time") or axis == "T": coordinates.append(TimeCoordinate(c, coord in info)) use = True # TODO: Support other level types if standard_name in ( "air_pressure", "model_level_number", "altitude", ): # or axis == 'Z': coordinates.append(LevelCoordinate(c, coord in info)) use = True if axis in ("X", "Y"): use = True if not use: coordinates.append(OtherCoordinate(c, coord in info)) if not (has_lat and has_lon): # self.log.info("NetCDFReader: skip %s (Not a 2 field)", name) continue for values in product(*[c.values for c in coordinates]): slices = [] for value, coordinate in zip(values, coordinates): slices.append(coordinate.make_slice(value)) fields.append(NetCDFField(self.path, ds, name, slices, non_dim_coords)) if not fields: raise Exception("NetCDFReader no 2D fields found in %s" % (self.path,)) return fields def to_xarray(self, **kwargs): return type(self).to_xarray_multi([self.path], **kwargs) @classmethod def to_xarray_multi(cls, paths, **kwargs): import xarray as xr options = dict() options.update(kwargs.get("xarray_open_mfdataset_kwargs", {})) return xr.open_mfdataset( paths, **options, ) def to_metview(self): from climetlab.metview import mv_read return mv_read(self.path) def plot_map(self, *args, **kwargs): return self.get_fields()[0].plot_map(*args, **kwargs) # Used by normalisers def to_datetime(self): times = self.to_datetime_list() assert len(times) == 1 return times[0] def to_datetime_list(self): # TODO: check if that can be done faster result = set() for s in self.get_fields(): result.add(to_datetime(s.time)) return sorted(result) def to_bounding_box(self): return BoundingBox.multi_merge([s.to_bounding_box() for s in self.get_fields()]) def reader(source, path, magic=None, deeper_check=False): if magic is None or magic[:4] in (b"\x89HDF", b"CDF\x01", b"CDF\x02"): return NetCDFReader(source, path)
27.397849
99
0.562206
c5dd915da1718c573bd1489fb012a2465fb7c2c6
2,293
py
Python
tests/test_dwi_run.py
alex-reardon/ANTsPyMM
ecedca733bac15f0200649070fc0412b16f82ed6
[ "Apache-2.0" ]
null
null
null
tests/test_dwi_run.py
alex-reardon/ANTsPyMM
ecedca733bac15f0200649070fc0412b16f82ed6
[ "Apache-2.0" ]
null
null
null
tests/test_dwi_run.py
alex-reardon/ANTsPyMM
ecedca733bac15f0200649070fc0412b16f82ed6
[ "Apache-2.0" ]
1
2021-11-05T18:02:53.000Z
2021-11-05T18:02:53.000Z
import sys, os import unittest os.environ["TF_NUM_INTEROP_THREADS"] = "8" os.environ["TF_NUM_INTRAOP_THREADS"] = "8" os.environ["ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS"] = "8" import tempfile import shutil import tensorflow as tf import antspymm import antspyt1w import antspynet import ants testingClass = unittest.TestCase( ) islocal = False id1 = "I1499279_Anon_20210819142214_5" id2 = "I1499337_Anon_20210819142214_6" img1 = ants.image_read( antspymm.get_data( id1, target_extension=".nii.gz") ) img2 = ants.image_read( antspymm.get_data( id2, target_extension=".nii.gz") ) # img1 = ants.image_read( "processed/dwp0sr.nii.gz" ) # img2 = ants.image_read( "processed/dwp1sr.nii.gz" ) b0indices = antspymm.segment_timeseries_by_meanvalue( img1 )['highermeans'] b0indices2 = antspymm.segment_timeseries_by_meanvalue( img1 )['highermeans'] # FIXME: - test that these are the same values # NOTE: could run SR at this point - will take a long time - example here: # mdlfn = antspymm.get_data( "brainSR", target_extension=".h5") # mdl = tf.keras.models.load_model( mdlfn ) # srimg = antspymm.super_res_mcimage( img, mdl, verbose=False ) dwp = antspymm.dewarp_imageset( [img1,img2], iterations=2, padding=6, target_idx = b0indices, syn_sampling = 20, syn_metric='mattes', type_of_transform = 'SyN', total_sigma = 0.0, random_seed=1, reg_iterations = [200,50,20] ) if islocal: print('dewarp done') ants.image_write( dwp['dewarped'][0], './dewarped0.nii.gz' ) ants.image_write( dwp['dewarped'][1], './dewarped1.nii.gz' ) # FIXME: - add test # testingClass.assertAlmostEqual( # float( dwp['dewarpedmean'].mean() ), # float( 108.2 ), 0, "template mean not close enough") # now reconstruct DTI bvec = antspymm.get_data( id1, target_extension=".bvec") bval = antspymm.get_data( id1, target_extension=".bval") dd = antspymm.dipy_dti_recon( dwp['dewarped'][0], bval, bvec, vol_idx=b0indices ) # ants.image_write( dd['RGB'], '/tmp/tempsr_rgb.nii.gz' ) bvec = antspymm.get_data( id2, target_extension=".bvec") bval = antspymm.get_data( id2, target_extension=".bval") ee = antspymm.dipy_dti_recon( dwp['dewarped'][1], bval, bvec, vol_idx=b0indices ) # ants.image_write( ee['RGB'], '/tmp/temp_rgb2.nii.gz' ) # FIXME: - add test # sys.exit(os.EX_OK) # code 0, all ok
37.590164
81
0.726995
3fd1b0b09d0d48a7daeea19606b2c068b80c1e31
3,968
py
Python
experiments/sarsa_2way-single-intersection.py
huyz-git/sumo-rl
fb5c57b0664b8bf5d5673d84acb4dcc9c7a947e7
[ "MIT" ]
1
2021-01-13T00:55:03.000Z
2021-01-13T00:55:03.000Z
experiments/sarsa_2way-single-intersection.py
huyz-git/sumo-rl
fb5c57b0664b8bf5d5673d84acb4dcc9c7a947e7
[ "MIT" ]
null
null
null
experiments/sarsa_2way-single-intersection.py
huyz-git/sumo-rl
fb5c57b0664b8bf5d5673d84acb4dcc9c7a947e7
[ "MIT" ]
1
2021-04-14T05:53:07.000Z
2021-04-14T05:53:07.000Z
import argparse import os import sys import pandas as pd from datetime import datetime if 'SUMO_HOME' in os.environ: tools = os.path.join(os.environ['SUMO_HOME'], 'tools') sys.path.append(tools) else: sys.exit("Please declare the environment variable 'SUMO_HOME'") import traci from sumo_rl.util.gen_route import write_route_file from sumo_rl.environment.env import SumoEnvironment from sumo_rl.agents.sarsa_lambda import TrueOnlineSarsaLambda if __name__ == '__main__': prs = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="""SarsaLambda Single-Intersection""") prs.add_argument("-route", dest="route", type=str, default='nets/2way-single-intersection/single-intersection-gen.rou.xml', help="Route definition xml file.\n") prs.add_argument("-a", dest="alpha", type=float, default=0.0001, required=False, help="Alpha learning rate.\n") prs.add_argument("-g", dest="gamma", type=float, default=0.99, required=False, help="Gamma discount rate.\n") prs.add_argument("-e", dest="epsilon", type=float, default=0.05, required=False, help="Epsilon.\n") prs.add_argument("-mingreen", dest="min_green", type=int, default=5, required=False, help="Minimum green time.\n") prs.add_argument("-maxgreen", dest="max_green", type=int, default=50, required=False, help="Maximum green time.\n") prs.add_argument("-gui", action="store_true", default=False, help="Run with visualization on SUMO.\n") prs.add_argument("-fixed", action="store_true", default=False, help="Run with fixed timing traffic signals.\n") prs.add_argument("-s", dest="seconds", type=int, default=400000, required=False, help="Number of simulation seconds.\n") prs.add_argument("-runs", dest="runs", type=int, default=1, help="Number of runs.\n") args = prs.parse_args() experiment_time = str(datetime.now()).split('.')[0] out_csv = 'outputs/2way-single-intersection/sarsa_lambda' write_route_file('nets/2way-single-intersection/single-intersection-gen.rou.xml', 400000, 100000) env = SumoEnvironment(net_file='nets/2way-single-intersection/single-intersection.net.xml', single_agent=True, route_file=args.route, out_csv_name=out_csv, use_gui=args.gui, num_seconds=args.seconds, min_green=args.min_green, max_green=args.max_green, max_depart_delay=0, time_to_load_vehicles=120, phases=[ traci.trafficlight.Phase(32, "GGrrrrGGrrrr"), traci.trafficlight.Phase(2, "yyrrrryyrrrr"), traci.trafficlight.Phase(32, "rrGrrrrrGrrr"), traci.trafficlight.Phase(2, "rryrrrrryrrr"), traci.trafficlight.Phase(32, "rrrGGrrrrGGr"), traci.trafficlight.Phase(2, "rrryyrrrryyr"), traci.trafficlight.Phase(32, "rrrrrGrrrrrG"), traci.trafficlight.Phase(2, "rrrrryrrrrry") ]) for run in range(1, args.runs+1): obs = env.reset() agent = TrueOnlineSarsaLambda(env.observation_space, env.action_space, alpha=args.alpha, gamma=args.gamma, epsilon=args.epsilon, fourier_order=7) done = False if args.fixed: while not done: _, _, done, _ = env.step({}) else: while not done: action = agent.act(agent.get_features(obs)) next_obs, r, done, _ = env.step(action=action) agent.learn(state=obs, action=action, reward=r, next_state=next_obs, done=done) obs = next_obs env.save_csv(out_csv, run)
47.807229
164
0.614163
23f0db27ce933bc2bd64620c112cb731a4699a09
521
py
Python
rest/member/instance-post-example-1/instance-post-example-1.6.x.py
azaddeveloper/api-snippets
f88b153cd7186fa70b33733b205886502db0d1f2
[ "MIT" ]
3
2020-05-05T10:01:02.000Z
2021-02-06T14:23:13.000Z
rest/member/instance-post-example-1/instance-post-example-1.6.x.py
azaddeveloper/api-snippets
f88b153cd7186fa70b33733b205886502db0d1f2
[ "MIT" ]
null
null
null
rest/member/instance-post-example-1/instance-post-example-1.6.x.py
azaddeveloper/api-snippets
f88b153cd7186fa70b33733b205886502db0d1f2
[ "MIT" ]
1
2019-10-02T14:36:36.000Z
2019-10-02T14:36:36.000Z
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) member = client.queues("QU5ef8732a3c49700934481addd5ce1659") \ .members("Front") \ .update(url="http://demo.twilio.com/docs/voice.xml", method="POST") print(member.wait_time)
34.733333
72
0.712092
313c4ee2709eb07fbb5875e08cbd27711df3944f
3,634
py
Python
tests/st/ops/ascend/test_aicpu_ops/test_reshape.py
GuoSuiming/mindspore
48afc4cfa53d970c0b20eedfb46e039db2a133d5
[ "Apache-2.0" ]
3,200
2020-02-17T12:45:41.000Z
2022-03-31T20:21:16.000Z
tests/st/ops/ascend/test_aicpu_ops/test_reshape.py
forwhat461/mindspore
59a277756eb4faad9ac9afcc7fd526e8277d4994
[ "Apache-2.0" ]
176
2020-02-12T02:52:11.000Z
2022-03-28T22:15:55.000Z
tests/st/ops/ascend/test_aicpu_ops/test_reshape.py
forwhat461/mindspore
59a277756eb4faad9ac9afcc7fd526e8277d4994
[ "Apache-2.0" ]
621
2020-03-09T01:31:41.000Z
2022-03-30T03:43:19.000Z
# Copyright 2019 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ import numpy as np import mindspore.context as context import mindspore.nn as nn from mindspore import Tensor from mindspore.ops import operations as P context.set_context(mode=context.PYNATIVE_MODE, device_target="Ascend") class Net(nn.Cell): def __init__(self): super(Net, self).__init__() self.reshape = P.Reshape() def construct(self, tensor): return self.reshape(tensor, (4, 4)) def test_net_bool(): x = np.random.randn(1, 16, 1, 1).astype(np.bool) net = Net() output = net(Tensor(x)) print(output.asnumpy()) assert np.all(output.asnumpy() == np.reshape(x, (4, 4))) def test_net_int8(): x = np.random.randn(1, 16, 1, 1).astype(np.int8) net = Net() output = net(Tensor(x)) print(output.asnumpy()) assert np.all(output.asnumpy() == np.reshape(x, (4, 4))) def test_net_uint8(): x = np.random.randn(1, 16, 1, 1).astype(np.uint8) net = Net() output = net(Tensor(x)) print(output.asnumpy()) assert np.all(output.asnumpy() == np.reshape(x, (4, 4))) def test_net_int16(): x = np.random.randn(1, 16, 1, 1).astype(np.int16) net = Net() output = net(Tensor(x)) print(output.asnumpy()) assert np.all(output.asnumpy() == np.reshape(x, (4, 4))) def test_net_uint16(): x = np.random.randn(1, 16, 1, 1).astype(np.uint16) net = Net() output = net(Tensor(x)) print(output.asnumpy()) assert np.all(output.asnumpy() == np.reshape(x, (4, 4))) def test_net_int32(): x = np.random.randn(1, 16, 1, 1).astype(np.int32) net = Net() output = net(Tensor(x)) print(output.asnumpy()) assert np.all(output.asnumpy() == np.reshape(x, (4, 4))) def test_net_uint32(): x = np.random.randn(1, 16, 1, 1).astype(np.uint32) net = Net() output = net(Tensor(x)) print(output.asnumpy()) assert np.all(output.asnumpy() == np.reshape(x, (4, 4))) def test_net_int64(): x = np.random.randn(1, 16, 1, 1).astype(np.int64) net = Net() output = net(Tensor(x)) print(output.asnumpy()) assert np.all(output.asnumpy() == np.reshape(x, (4, 4))) def test_net_uint64(): x = np.random.randn(1, 16, 1, 1).astype(np.uint64) net = Net() output = net(Tensor(x)) print(output.asnumpy()) assert np.all(output.asnumpy() == np.reshape(x, (4, 4))) def test_net_float16(): x = np.random.randn(1, 16, 1, 1).astype(np.float16) net = Net() output = net(Tensor(x)) print(output.asnumpy()) assert np.all(output.asnumpy() == np.reshape(x, (4, 4))) def test_net_float32(): x = np.random.randn(1, 16, 1, 1).astype(np.float32) net = Net() output = net(Tensor(x)) print(output.asnumpy()) assert np.all(output.asnumpy() == np.reshape(x, (4, 4))) def test_net_float64(): x = np.random.randn(1, 16, 1, 1).astype(np.float64) net = Net() output = net(Tensor(x)) print(output.asnumpy()) assert np.all(output.asnumpy() == np.reshape(x, (4, 4)))
28.390625
78
0.624381
9d9e5dcdd286f34161d29d70de25d6fc6a7675ff
933
py
Python
setup.py
alicebambi/idcode_recognition
64dd391d7be64cc8af40d610ad72a22843c73629
[ "MIT" ]
null
null
null
setup.py
alicebambi/idcode_recognition
64dd391d7be64cc8af40d610ad72a22843c73629
[ "MIT" ]
null
null
null
setup.py
alicebambi/idcode_recognition
64dd391d7be64cc8af40d610ad72a22843c73629
[ "MIT" ]
null
null
null
#!/usr/bin/env python #-*- coding:utf-8 -*- ############################################# # File Name: setup.py # Author: xingming # Mail: huoxingming@gmail.com # Created Time: 2015-12-11 01:25:34 AM ############################################# from setuptools import setup, find_packages setup( name = "ufzh", version = "1.0.0", keywords = ("pip", "ufzh"), description = "深度学习实现知乎验证码识别", long_description = "深度学习实现知乎验证码识别", license = "MIT Licence", author = "bambi", author_email = "bambi2017@aliyun.com", packages = find_packages(), include_package_data = True, data_files=[('ufzh/checkpoint', ['ufzh/checkpoint/checkpoint', 'ufzh/checkpoint/ocr-model-22001.data-00000-of-00001', 'ufzh/checkpoint/ocr-model-22001.index','ufzh/checkpoint/ocr-model-22001.meta'])], platforms = "any", install_requires = ['requests', "bs4", 'tensorflow==1.2.1', 'pillow', 'numpy', 'tqdm'] )
30.096774
204
0.596999
a3af649915970b070f8c497cf67a91b240f7d034
65,763
py
Python
O365/drive.py
livejake/python-o365
7179e85b95778a52affbf70596388530dedf90c9
[ "Apache-2.0" ]
null
null
null
O365/drive.py
livejake/python-o365
7179e85b95778a52affbf70596388530dedf90c9
[ "Apache-2.0" ]
null
null
null
O365/drive.py
livejake/python-o365
7179e85b95778a52affbf70596388530dedf90c9
[ "Apache-2.0" ]
null
null
null
import logging import warnings from pathlib import Path from time import sleep from urllib.parse import urlparse, quote from dateutil.parser import parse from .address_book import Contact from .utils import ApiComponent, Pagination, NEXT_LINK_KEYWORD, \ OneDriveWellKnowFolderNames log = logging.getLogger(__name__) SIZE_THERSHOLD = 1024 * 1024 * 2 # 2 MB UPLOAD_SIZE_LIMIT_SIMPLE = 1024 * 1024 * 4 # 4 MB UPLOAD_SIZE_LIMIT_SESSION = 1024 * 1024 * 60 # 60 MB CHUNK_SIZE_BASE = 1024 * 320 # 320 Kb # 5 MB --> Must be a multiple of CHUNK_SIZE_BASE DEFAULT_UPLOAD_CHUNK_SIZE = 1024 * 1024 * 5 ALLOWED_PDF_EXTENSIONS = {'.csv', '.doc', '.docx', '.odp', '.ods', '.odt', '.pot', '.potm', '.potx', '.pps', '.ppsx', '.ppsxm', '.ppt', '.pptm', '.pptx', '.rtf', '.xls', '.xlsx'} class DownloadableMixin: def download(self, to_path=None, name=None, chunk_size='auto', convert_to_pdf=False): """ Downloads this file to the local drive. Can download the file in chunks with multiple requests to the server. :param to_path: a path to store the downloaded file :type to_path: str or Path :param str name: the name you want the stored file to have. :param int chunk_size: number of bytes to retrieve from each api call to the server. if auto, files bigger than SIZE_THERSHOLD will be chunked (into memory, will be however only 1 request) :param bool convert_to_pdf: will try to download the converted pdf if file extension in ALLOWED_PDF_EXTENSIONS :return: Success / Failure :rtype: bool """ # TODO: Add download with more than one request (chunk_requests) with # header 'Range'. For example: 'Range': 'bytes=0-1024' if to_path is None: to_path = Path() else: if not isinstance(to_path, Path): to_path = Path(to_path) if not to_path.exists(): raise FileNotFoundError('{} does not exist'.format(to_path)) if name and not Path(name).suffix and self.name: name = name + Path(self.name).suffix name = name or self.name to_path = to_path / name url = self.build_url( self._endpoints.get('download').format(id=self.object_id)) try: if chunk_size is None: stream = False elif chunk_size == 'auto': if self.size and self.size > SIZE_THERSHOLD: stream = True else: stream = False chunk_size = None elif isinstance(chunk_size, int): stream = True else: raise ValueError("Argument chunk_size must be either 'auto' " "or any integer number representing bytes") params = {} if convert_to_pdf and Path(name).suffix in ALLOWED_PDF_EXTENSIONS: params['format'] = 'pdf' with self.con.get(url, stream=stream, params=params) as response: if not response: log.debug('Downloading driveitem Request failed: {}'.format( response.reason)) return False with to_path.open(mode='wb') as output: if stream: for chunk in response.iter_content( chunk_size=chunk_size): if chunk: output.write(chunk) else: output.write(response.content) except Exception as e: log.error( 'Error downloading driveitem {}. Error: {}'.format(self.name, str(e))) return False return True class CopyOperation(ApiComponent): """ https://github.com/OneDrive/onedrive-api-docs/issues/762 """ _endpoints = { # all prefixed with /drives/{drive_id} on main_resource by default 'item': '/items/{id}', } def __init__(self, *, parent=None, con=None, **kwargs): """ :param parent: parent for this operation :type parent: Drive :param Connection con: connection to use if no parent specified :param Protocol protocol: protocol to use if no parent specified (kwargs) :param str main_resource: use this resource instead of parent resource (kwargs) :param str monitor_url: :param str item_id: """ if parent and con: raise ValueError('Need a parent or a connection but not both') self.con = parent.con if parent else con self.parent = parent # parent will be always a DriveItem # Choose the main_resource passed in kwargs over parent main_resource main_resource = kwargs.pop('main_resource', None) or ( getattr(parent, 'main_resource', None) if parent else None) super().__init__( protocol=parent.protocol if parent else kwargs.get('protocol'), main_resource=main_resource) self.monitor_url = kwargs.get('monitor_url', None) self.item_id = kwargs.get('item_id', None) if self.monitor_url is None and self.item_id is None: raise ValueError('Must provide a valid monitor_url or item_id') if self.monitor_url is not None and self.item_id is not None: raise ValueError( 'Must provide a valid monitor_url or item_id, but not both') if self.item_id: self.status = 'completed' self.completion_percentage = 100.0 else: self.status = 'inProgress' self.completion_percentage = 0.0 def _request_status(self): """ Checks the api endpoint to check if the async job progress """ if self.item_id: return True response = self.con.get(self.monitor_url) if not response: return False data = response.json() self.status = data.get('status', 'inProgress') self.completion_percentage = data.get(self._cc('percentageComplete'), 0) self.item_id = data.get(self._cc('resourceId'), None) return self.item_id is not None def check_status(self, delay=0): """ Checks the api endpoint in a loop :param delay: number of seconds to wait between api calls. Note Connection 'requests_delay' also apply. :return: tuple of status and percentage complete :rtype: tuple(str, float) """ if not self.item_id: while not self._request_status(): # wait until _request_status returns True yield self.status, self.completion_percentage if self.item_id is None: sleep(delay) else: yield self.status, self.completion_percentage def get_item(self): """ Returns the item copied :return: Copied Item :rtype: DriveItem """ return self.parent.get_item( self.item_id) if self.item_id is not None else None class DriveItemVersion(ApiComponent, DownloadableMixin): """ A version of a DriveItem """ _endpoints = { 'download': '/versions/{id}/content', 'restore': '/versions/{id}/restoreVersion' } def __init__(self, *, parent=None, con=None, **kwargs): """ Version of DriveItem :param parent: parent for this operation :type parent: DriveItem :param Connection con: connection to use if no parent specified :param Protocol protocol: protocol to use if no parent specified (kwargs) :param str main_resource: use this resource instead of parent resource (kwargs) """ if parent and con: raise ValueError('Need a parent or a connection but not both') self.con = parent.con if parent else con self._parent = parent if isinstance(parent, DriveItem) else None protocol = parent.protocol if parent else kwargs.get('protocol') # Choose the main_resource passed in kwargs over parent main_resource main_resource = kwargs.pop('main_resource', None) or ( getattr(parent, 'main_resource', None) if parent else None) resource_prefix = '/items/{item_id}'.format( item_id=self._parent.object_id) main_resource = '{}{}'.format( main_resource or (protocol.default_resource if protocol else ''), resource_prefix) super().__init__(protocol=protocol, main_resource=main_resource) cloud_data = kwargs.get(self._cloud_data_key, {}) self.driveitem_id = self._parent.object_id self.object_id = cloud_data.get('id', '1.0') self.name = self.object_id modified = cloud_data.get(self._cc('lastModifiedDateTime'), None) local_tz = self.protocol.timezone self.modified = parse(modified).astimezone( local_tz) if modified else None self.size = cloud_data.get('size', 0) modified_by = cloud_data.get(self._cc('lastModifiedBy'), {}).get('user', None) self.modified_by = Contact(con=self.con, protocol=self.protocol, **{ self._cloud_data_key: modified_by}) if modified_by else None def __str__(self): return self.__repr__() def __repr__(self): return ('Version Id: {} | Modified on: {} | by: {}' ''.format(self.name, self.modified, self.modified_by.display_name if self.modified_by else None)) def restore(self): """ Restores this DriveItem Version. You can not restore the current version (last one). :return: Success / Failure :rtype: bool """ url = self.build_url( self._endpoints.get('restore').format(id=self.object_id)) response = self.con.post(url) return bool(response) def download(self, to_path=None, name=None, chunk_size='auto', convert_to_pdf=False): """ Downloads this version. You can not download the current version (last one). :return: Success / Failure :rtype: bool """ return super().download(to_path=to_path, name=name, chunk_size=chunk_size, convert_to_pdf=convert_to_pdf) class DriveItemPermission(ApiComponent): """ A Permission representation for a DriveItem """ _endpoints = { 'permission': '/items/{driveitem_id}/permissions/{id}' } def __init__(self, *, parent=None, con=None, **kwargs): """ Permissions for DriveItem :param parent: parent for this operation :type parent: DriveItem :param Connection con: connection to use if no parent specified :param Protocol protocol: protocol to use if no parent specified (kwargs) :param str main_resource: use this resource instead of parent resource (kwargs) """ if parent and con: raise ValueError('Need a parent or a connection but not both') self.con = parent.con if parent else con self._parent = parent if isinstance(parent, DriveItem) else None # Choose the main_resource passed in kwargs over parent main_resource main_resource = kwargs.pop('main_resource', None) or ( getattr(parent, 'main_resource', None) if parent else None) protocol = parent.protocol if parent else kwargs.get('protocol') super().__init__(protocol=protocol, main_resource=main_resource) self.driveitem_id = self._parent.object_id cloud_data = kwargs.get(self._cloud_data_key, {}) self.object_id = cloud_data.get(self._cc('id')) self.inherited_from = cloud_data.get(self._cc('inheritedFrom'), None) link = cloud_data.get(self._cc('link'), None) self.permission_type = 'owner' if link: self.permission_type = 'link' self.share_type = link.get('type', 'view') self.share_scope = link.get('scope', 'anonymous') self.share_link = link.get('webUrl', None) invitation = cloud_data.get(self._cc('invitation'), None) if invitation: self.permission_type = 'invitation' self.share_email = invitation.get('email', '') invited_by = invitation.get('invitedBy', {}) self.invited_by = invited_by.get('user', {}).get( self._cc('displayName'), None) or invited_by.get('application', {}).get( self._cc('displayName'), None) self.require_sign_in = invitation.get(self._cc('signInRequired'), True) self.roles = cloud_data.get(self._cc('roles'), []) granted_to = cloud_data.get(self._cc('grantedTo'), {}) self.granted_to = granted_to.get('user', {}).get( self._cc('displayName')) or granted_to.get('application', {}).get( self._cc('displayName')) self.share_id = cloud_data.get(self._cc('shareId'), None) def __str__(self): return self.__repr__() def __repr__(self): return 'Permission for {} of type: {}'.format(self._parent.name, self.permission_type) def update_roles(self, roles='view'): """ Updates the roles of this permission :return: Success / Failure :rtype: bool """ if not self.object_id: return False url = self.build_url(self._endpoints.get('permission').format( driveitem_id=self.driveitem_id, id=self.object_id)) if roles in {'view', 'read'}: data = {'roles': ['read']} elif roles == {'edit', 'write'}: data = {'roles': ['write']} else: raise ValueError('"{}" is not a valid share_type'.format(roles)) response = self.con.patch(url, data=data) if not response: return False self.roles = data.get('roles', []) return True def delete(self): """ Deletes this permission. Only permissions that are not inherited can be deleted. :return: Success / Failure :rtype: bool """ if not self.object_id: return False url = self.build_url(self._endpoints.get('permission').format( driveitem_id=self.driveitem_id, id=self.object_id)) response = self.con.delete(url) if not response: return False self.object_id = None return True class DriveItem(ApiComponent): """ A DriveItem representation. Groups all functionality """ _endpoints = { # all prefixed with /drives/{drive_id} on main_resource by default 'list_items': '/items/{id}/children', 'thumbnails': '/items/{id}/thumbnails', 'item': '/items/{id}', 'copy': '/items/{id}/copy', 'download': '/items/{id}/content', 'search': "/items/{id}/search(q='{search_text}')", 'versions': '/items/{id}/versions', 'version': '/items/{id}/versions/{version_id}', 'simple_upload': '/items/{id}:/{filename}:/content', 'create_upload_session': '/items/{id}:/{filename}:/createUploadSession', 'share_link': '/items/{id}/createLink', 'share_invite': '/items/{id}/invite', 'permissions': '/items/{id}/permissions', } def __init__(self, *, parent=None, con=None, **kwargs): """ Create a DriveItem :param parent: parent for this operation :type parent: Drive or drive.Folder :param Connection con: connection to use if no parent specified :param Protocol protocol: protocol to use if no parent specified (kwargs) :param str main_resource: use this resource instead of parent resource (kwargs) """ if parent and con: raise ValueError('Need a parent or a connection but not both') self.con = parent.con if parent else con self._parent = parent if isinstance(parent, DriveItem) else None self.drive = parent if isinstance(parent, Drive) else ( parent.drive if isinstance(parent.drive, Drive) else kwargs.get( 'drive', None)) # Choose the main_resource passed in kwargs over parent main_resource main_resource = kwargs.pop('main_resource', None) or ( getattr(parent, 'main_resource', None) if parent else None) protocol = parent.protocol if parent else kwargs.get('protocol') if parent and not isinstance(parent, DriveItem): # parent is a Drive so append the drive route to the main_resource drive_id = (None if parent.object_id == 'root' else parent.object_id) or None # prefix with the current known drive or the default one resource_prefix = '/drives/{drive_id}'.format( drive_id=drive_id) if drive_id else '/drive' main_resource = '{}{}'.format(main_resource or ( protocol.default_resource if protocol else ''), resource_prefix) super().__init__(protocol=protocol, main_resource=main_resource) cloud_data = kwargs.get(self._cloud_data_key, {}) self.object_id = cloud_data.get(self._cc('id')) self.name = cloud_data.get(self._cc('name'), '') self.web_url = cloud_data.get(self._cc('webUrl')) created_by = cloud_data.get(self._cc('createdBy'), {}).get('user', None) self.created_by = Contact(con=self.con, protocol=self.protocol, **{ self._cloud_data_key: created_by}) if created_by else None modified_by = cloud_data.get(self._cc('lastModifiedBy'), {}).get('user', None) self.modified_by = Contact(con=self.con, protocol=self.protocol, **{ self._cloud_data_key: modified_by}) if modified_by else None created = cloud_data.get(self._cc('createdDateTime'), None) modified = cloud_data.get(self._cc('lastModifiedDateTime'), None) local_tz = self.protocol.timezone self.created = parse(created).astimezone(local_tz) if created else None self.modified = parse(modified).astimezone( local_tz) if modified else None self.description = cloud_data.get(self._cc('description'), '') self.size = cloud_data.get(self._cc('size'), 0) self.shared = cloud_data.get(self._cc('shared'), {}).get('scope', None) parent_reference = cloud_data.get(self._cc('parentReference'), {}) self.parent_id = parent_reference.get('id', None) self.drive_id = parent_reference.get(self._cc('driveId'), None) remote_item = cloud_data.get(self._cc('remoteItem'), None) self.remote_item = self._classifier(remote_item)(parent=self, **{ self._cloud_data_key: remote_item}) if remote_item else None # Thumbnails self.thumbnails = cloud_data.get(self._cc('thumbnails'), []) def __str__(self): return self.__repr__() def __repr__(self): return '{}: {}'.format(self.__class__.__name__, self.name) def __eq__(self, other): obj_id = getattr(other, 'object_id', None) if obj_id is not None: return self.object_id == obj_id return False @staticmethod def _classifier(item): """ Subclass to change factory classes """ if 'folder' in item: return Folder elif 'image' in item: return Image elif 'photo' in item: return Photo else: return File @property def is_folder(self): """ Returns if this DriveItem is a Folder """ return isinstance(self, Folder) @property def is_file(self): """ Returns if this DriveItem is a File """ return isinstance(self, File) @property def is_image(self): """ Returns if this DriveItem is a Image """ return isinstance(self, Image) @property def is_photo(self): """ Returns if this DriveItem is a Photo """ return isinstance(self, Photo) def get_parent(self): """ the parent of this DriveItem :return: Parent of this item :rtype: Drive or drive.Folder """ if self._parent and self._parent.object_id == self.parent_id: return self._parent else: if self.parent_id: return self.drive.get_item(self.parent_id) else: # return the drive return self.drive def get_thumbnails(self, size=None): """ Returns this Item Thumbnails. Thumbnails are not supported on SharePoint Server 2016. :param size: request only the specified size: ej: "small", Custom 300x400 px: "c300x400", Crop: "c300x400_Crop" :return: Thumbnail Data :rtype: dict """ if not self.object_id: return [] url = self.build_url( self._endpoints.get('thumbnails').format(id=self.object_id)) params = {} if size is not None: params['select'] = size response = self.con.get(url, params=params) if not response: return [] data = response.json() if not self.thumbnails or size is None: self.thumbnails = data return data def update(self, **kwargs): """ Updates this item :param kwargs: all the properties to be updated. only name and description are allowed at the moment. :return: Success / Failure :rtype: bool """ if not self.object_id: return False url = self.build_url( self._endpoints.get('item').format(id=self.object_id)) data = {self._cc(key): value for key, value in kwargs.items() if key in {'name', 'description'}} # convert keys to protocol casing if not data: return False response = self.con.patch(url, data=data) if not response: return False new_data = response.json() for key in data: value = new_data.get(key, None) if value: setattr(self, self.protocol.to_api_case(key), value) return True def delete(self): """ Moves this item to the Recycle Bin :return: Success / Failure :rtype: bool """ if not self.object_id: return False url = self.build_url( self._endpoints.get('item').format(id=self.object_id)) response = self.con.delete(url) if not response: return False self.object_id = None return True def move(self, target): """ Moves this DriveItem to another Folder. Can't move between different Drives. :param target: a Folder, Drive item or Item Id string. If it's a drive the item will be moved to the root folder. :type target: drive.Folder or DriveItem or str :return: Success / Failure :rtype: bool """ if isinstance(target, Folder): target_id = target.object_id elif isinstance(target, Drive): # we need the root folder id root_folder = target.get_root_folder() if not root_folder: return False target_id = root_folder.object_id elif isinstance(target, str): target_id = target else: raise ValueError('Target must be a Folder or Drive') if not self.object_id or not target_id: raise ValueError( 'Both self, and target must have a valid object_id.') if target_id == 'root': raise ValueError("When moving, target id can't be 'root'") url = self.build_url( self._endpoints.get('item').format(id=self.object_id)) data = {'parentReference': {'id': target_id}} response = self.con.patch(url, data=data) if not response: return False self.parent_id = target_id return True def copy(self, target=None, name=None): """ Asynchronously creates a copy of this DriveItem and all it's child elements. :param target: target location to move to. If it's a drive the item will be moved to the root folder. :type target: drive.Folder or Drive :param name: a new name for the copy. :rtype: CopyOperation """ if target is None and name is None: raise ValueError('Must provide a target or a name (or both)') if isinstance(target, Folder): target_id = target.object_id drive_id = target.drive_id elif isinstance(target, Drive): # we need the root folder root_folder = target.get_root_folder() if not root_folder: return None target_id = root_folder.object_id drive_id = root_folder.drive_id elif target is None: target_id = None drive_id = None else: raise ValueError('Target, if provided, must be a Folder or Drive') if not self.object_id: return None if target_id == 'root': raise ValueError("When copying, target id can't be 'root'") url = self.build_url( self._endpoints.get('copy').format(id=self.object_id)) if target_id and drive_id: data = {'parentReference': {'id': target_id, 'driveId': drive_id}} else: data = {} if name: # incorporate the extension if the name provided has none. if not Path(name).suffix and self.name: name = name + Path(self.name).suffix data['name'] = name response = self.con.post(url, data=data) if not response: return None # Find out if the server has run a Sync or Async operation location = response.headers.get('Location', None) if 'monitor' in location: # Async operation return CopyOperation(parent=self.drive, monitor_url=location) else: # Sync operation. Item is ready to be retrieved path = urlparse(location).path item_id = path.split('/')[-1] return CopyOperation(parent=self.drive, item_id=item_id) def get_versions(self): """ Returns a list of available versions for this item :return: list of versions :rtype: list[DriveItemVersion] """ if not self.object_id: return [] url = self.build_url( self._endpoints.get('versions').format(id=self.object_id)) response = self.con.get(url) if not response: return [] data = response.json() # Everything received from cloud must be passed as self._cloud_data_key return [DriveItemVersion(parent=self, **{self._cloud_data_key: item}) for item in data.get('value', [])] def get_version(self, version_id): """ Returns a version for specified id :return: a version object of specified id :rtype: DriveItemVersion """ if not self.object_id: return None url = self.build_url( self._endpoints.get('version').format(id=self.object_id, version_id=version_id)) response = self.con.get(url) if not response: return None data = response.json() # Everything received from cloud must be passed as self._cloud_data_key return DriveItemVersion(parent=self, **{self._cloud_data_key: data}) def share_with_link(self, share_type='view', share_scope='anonymous'): """ Creates or returns a link you can share with others :param str share_type: 'view' to allow only view access, 'edit' to allow editions, and 'embed' to allow the DriveItem to be embedded :param str share_scope: 'anonymous': anyone with the link can access. 'organization' Only organization members can access :return: link to share :rtype: DriveItemPermission """ if not self.object_id: return None url = self.build_url( self._endpoints.get('share_link').format(id=self.object_id)) data = { 'type': share_type, 'scope': share_scope } response = self.con.post(url, data=data) if not response: return None data = response.json() # return data.get('link', {}).get('webUrl') return DriveItemPermission(parent=self, **{self._cloud_data_key: data}) def share_with_invite(self, recipients, require_sign_in=True, send_email=True, message=None, share_type='view'): """ Sends an invitation to access or edit this DriveItem :param recipients: a string or Contact or a list of the former representing recipients of this invitation :type recipients: list[str] or list[Contact] or str or Contact :param bool require_sign_in: if True the recipients invited will need to log in to view the contents :param bool send_email: if True an email will be send to the recipients :param str message: the body text of the message emailed :param str share_type: 'view': will allow to read the contents. 'edit' will allow to modify the contents :return: link to share :rtype: DriveItemPermission """ if not self.object_id: return None to = [] if recipients is None: raise ValueError('Provide a valid to parameter') elif isinstance(recipients, (list, tuple)): for x in recipients: if isinstance(x, str): to.append({'email': x}) elif isinstance(x, Contact): to.append({'email': x.main_email}) else: raise ValueError( 'All the recipients must be either strings or Contacts') elif isinstance(recipients, str): to.append({'email': recipients}) elif isinstance(recipients, Contact): to.append({'email': recipients.main_email}) else: raise ValueError( 'All the recipients must be either strings or Contacts') url = self.build_url( self._endpoints.get('share_invite').format(id=self.object_id)) data = { 'recipients': to, self._cc('requireSignIn'): require_sign_in, self._cc('sendInvitation'): send_email, } if share_type in {'view', 'read'}: data['roles'] = ['read'] elif share_type in {'edit', 'write'}: data['roles'] = ['write'] else: raise ValueError( '"{}" is not a valid share_type'.format(share_type)) if send_email and message: data['message'] = message response = self.con.post(url, data=data) if not response: return None data = response.json() return DriveItemPermission(parent=self, **{self._cloud_data_key: data}) def get_permissions(self): """ Returns a list of DriveItemPermissions with the permissions granted for this DriveItem. :return: List of Permissions :rtype: list[DriveItemPermission] """ if not self.object_id: return [] url = self.build_url( self._endpoints.get('permissions').format(id=self.object_id)) response = self.con.get(url) if not response: return None data = response.json() # Everything received from cloud must be passed as self._cloud_data_key return [DriveItemPermission(parent=self, **{self._cloud_data_key: item}) for item in data.get('value', [])] class File(DriveItem, DownloadableMixin): """ A File """ def __init__(self, **kwargs): super().__init__(**kwargs) cloud_data = kwargs.get(self._cloud_data_key, {}) self.mime_type = cloud_data.get(self._cc('file'), {}).get( self._cc('mimeType'), None) @property def extension(self): return Path(self.name).suffix class Image(File): """ An Image """ def __init__(self, **kwargs): super().__init__(**kwargs) cloud_data = kwargs.get(self._cloud_data_key, {}) image = cloud_data.get(self._cc('image'), {}) self.height = image.get(self._cc('height'), 0) self.width = image.get(self._cc('width'), 0) @property def dimensions(self): """ Dimension of the Image :return: width x height :rtype: str """ return '{}x{}'.format(self.width, self.height) class Photo(Image): """ Photo Object. Inherits from Image but has more attributes """ def __init__(self, **kwargs): super().__init__(**kwargs) cloud_data = kwargs.get(self._cloud_data_key, {}) photo = cloud_data.get(self._cc('photo'), {}) taken = photo.get(self._cc('takenDateTime'), None) local_tz = self.protocol.timezone self.taken_datetime = parse(taken).astimezone( local_tz) if taken else None self.camera_make = photo.get(self._cc('cameraMake'), None) self.camera_model = photo.get(self._cc('cameraModel'), None) self.exposure_denominator = photo.get(self._cc('exposureDenominator'), None) self.exposure_numerator = photo.get(self._cc('exposureNumerator'), None) self.fnumber = photo.get(self._cc('fNumber'), None) self.focal_length = photo.get(self._cc('focalLength'), None) self.iso = photo.get(self._cc('iso'), None) class Folder(DriveItem): """ A Folder inside a Drive """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) cloud_data = kwargs.get(self._cloud_data_key, {}) self.child_count = cloud_data.get(self._cc('folder'), {}).get( self._cc('childCount'), 0) self.special_folder = cloud_data.get(self._cc('specialFolder'), {}).get( 'name', None) def get_items(self, limit=None, *, query=None, order_by=None, batch=None): """ Returns all the items inside this folder :param int limit: max no. of folders to get. Over 999 uses batch. :param query: applies a OData filter to the request :type query: Query or str :param order_by: orders the result set based on this condition :type order_by: Query or str :param int batch: batch size, retrieves items in batches allowing to retrieve more items than the limit. :return: list of items in this folder :rtype: list[DriveItem] or Pagination """ url = self.build_url( self._endpoints.get('list_items').format(id=self.object_id)) if limit is None or limit > self.protocol.max_top_value: batch = self.protocol.max_top_value params = {'$top': batch if batch else limit} if order_by: params['$orderby'] = order_by if query: if query.has_filters: warnings.warn('Filters are not allowed by the ' 'Api Provider in this method') query.clear_filters() if isinstance(query, str): params['$filter'] = query else: params.update(query.as_params()) response = self.con.get(url, params=params) if not response: return iter(()) data = response.json() # Everything received from cloud must be passed as self._cloud_data_key items = ( self._classifier(item)(parent=self, **{self._cloud_data_key: item}) for item in data.get('value', [])) next_link = data.get(NEXT_LINK_KEYWORD, None) if batch and next_link: return Pagination(parent=self, data=items, constructor=self._classifier, next_link=next_link, limit=limit) else: return items def create_child_folder(self, name, description=None): """ Creates a Child Folder :param str name: the name of the new child folder :param str description: the description of the new child folder :return: newly created folder :rtype: drive.Folder """ if not self.object_id: return None url = self.build_url( self._endpoints.get('list_items').format(id=self.object_id)) data = {'name': name, 'folder': {}} if description: data['description'] = description response = self.con.post(url, data=data) if not response: return None folder = response.json() return self._classifier(folder)(parent=self, **{self._cloud_data_key: folder}) def download_contents(self, to_folder=None): """ This will download each file and folder sequentially. Caution when downloading big folder structures :param drive.Folder to_folder: folder where to store the contents """ to_folder = to_folder or Path() if not to_folder.exists(): to_folder.mkdir() for item in self.get_items(query=self.new_query().select('id', 'size')): if item.is_folder and item.child_count > 0: item.download_contents(to_folder=to_folder / item.name) else: item.download(to_folder) def search(self, search_text, limit=None, *, query=None, order_by=None, batch=None): """ Search for DriveItems under this folder The search API uses a search service under the covers, which requires indexing of content. As a result, there will be some time between creation of an item and when it will appear in search results. :param str search_text: The query text used to search for items. Values may be matched across several fields including filename, metadata, and file content. :param int limit: max no. of folders to get. Over 999 uses batch. :param query: applies a OData filter to the request :type query: Query or str :param order_by: orders the result set based on this condition :type order_by: Query or str :param int batch: batch size, retrieves items in batches allowing to retrieve more items than the limit. :return: list of items in this folder :rtype: list[DriveItem] or Pagination """ if not isinstance(search_text, str) or not search_text: raise ValueError('Provide a valid search_text') url = self.build_url( self._endpoints.get('search').format(id=self.object_id, search_text=search_text)) if limit is None or limit > self.protocol.max_top_value: batch = self.protocol.max_top_value params = {'$top': batch if batch else limit} if order_by: params['$orderby'] = order_by if query: if query.has_filters: warnings.warn( 'Filters are not allowed by the Api ' 'Provider in this method') query.clear_filters() if isinstance(query, str): params['$filter'] = query else: params.update(query.as_params()) response = self.con.get(url, params=params) if not response: return iter(()) data = response.json() # Everything received from cloud must be passed as self._cloud_data_key items = ( self._classifier(item)(parent=self, **{self._cloud_data_key: item}) for item in data.get('value', [])) next_link = data.get(NEXT_LINK_KEYWORD, None) if batch and next_link: return Pagination(parent=self, data=items, constructor=self._classifier, next_link=next_link, limit=limit) else: return items def upload_file(self, item, chunk_size=DEFAULT_UPLOAD_CHUNK_SIZE): """ Uploads a file :param item: path to the item you want to upload :type item: str or Path :param chunk_size: Only applies if file is bigger than 4MB. Chunk size for uploads. Must be a multiple of 327.680 bytes :return: uploaded file :rtype: DriveItem """ if item is None: raise ValueError('Item must be a valid path to file') item = Path(item) if not isinstance(item, Path) else item if not item.exists(): raise ValueError('Item must exist') if not item.is_file(): raise ValueError('Item must be a file') file_size = item.stat().st_size if file_size <= UPLOAD_SIZE_LIMIT_SIMPLE: # Simple Upload url = self.build_url( self._endpoints.get('simple_upload').format(id=self.object_id, filename=quote(item.name))) # headers = {'Content-type': 'text/plain'} headers = {'Content-type': 'application/octet-stream'} # headers = None with item.open(mode='rb') as file: data = file.read() response = self.con.put(url, headers=headers, data=data) if not response: return None data = response.json() return self._classifier(data)(parent=self, **{self._cloud_data_key: data}) else: # Resumable Upload url = self.build_url( self._endpoints.get('create_upload_session').format( id=self.object_id, filename=quote(item.name))) response = self.con.post(url) if not response: return None data = response.json() upload_url = data.get(self._cc('uploadUrl'), None) if upload_url is None: log.error('Create upload session response without ' 'upload_url for file {}'.format(item.name)) return None current_bytes = 0 with item.open(mode='rb') as file: while True: data = file.read(chunk_size) if not data: break transfer_bytes = len(data) headers = { 'Content-type': 'application/octet-stream', 'Content-Length': str(len(data)), 'Content-Range': 'bytes {}-{}/{}' ''.format(current_bytes, current_bytes + transfer_bytes - 1, file_size) } current_bytes += transfer_bytes # this request mut NOT send the authorization header. # so we use a naive simple request. response = self.con.naive_request(upload_url, 'PUT', data=data, headers=headers) if not response: return None if response.status_code != 202: # file is completed data = response.json() return self._classifier(data)(parent=self, **{ self._cloud_data_key: data}) class Drive(ApiComponent): """ A Drive representation. A Drive is a Container of Folders and Files and act as a root item """ _endpoints = { 'default_drive': '/drive', 'get_drive': '/drives/{id}', 'get_root_item_default': '/drive/root', 'get_root_item': '/drives/{id}/root', 'list_items_default': '/drive/root/children', 'list_items': '/drives/{id}/root/children', 'get_item_default': '/drive/items/{item_id}', 'get_item': '/drives/{id}/items/{item_id}', 'get_item_by_path_default': '/drive/root:{item_path}', 'get_item_by_path': '/drives/{id}/root:{item_path}', 'recent_default': '/drive/recent', 'recent': '/drives/{id}/recent', 'shared_with_me_default': '/drive/sharedWithMe', 'shared_with_me': '/drives/{id}/sharedWithMe', 'get_special_default': '/drive/special/{name}', 'get_special': '/drives/{id}/special/{name}', 'search_default': "/drive/search(q='{search_text}')", 'search': "/drives/{id}/search(q='{search_text}')", } def __init__(self, *, parent=None, con=None, **kwargs): """ Create a drive representation :param parent: parent for this operation :type parent: Drive or Storage :param Connection con: connection to use if no parent specified :param Protocol protocol: protocol to use if no parent specified (kwargs) :param str main_resource: use this resource instead of parent resource (kwargs) """ if parent and con: raise ValueError('Need a parent or a connection but not both') self.con = parent.con if parent else con self.parent = parent if isinstance(parent, Drive) else None # Choose the main_resource passed in kwargs over parent main_resource main_resource = kwargs.pop('main_resource', None) or ( getattr(parent, 'main_resource', None) if parent else None) super().__init__( protocol=parent.protocol if parent else kwargs.get('protocol'), main_resource=main_resource) self._update_data(kwargs) def _update_data(self, data): cloud_data = data.get(self._cloud_data_key, {}) self.object_id = cloud_data.get(self._cc('id')) # Fallback to manual drive self.name = cloud_data.get(self._cc('name'), data.get('name', '')) self.description = cloud_data.get(self._cc('description')) self.drive_type = cloud_data.get(self._cc('driveType')) self.web_url = cloud_data.get(self._cc('webUrl')) owner = cloud_data.get(self._cc('owner'), {}).get('user', None) self.owner = Contact(con=self.con, protocol=self.protocol, **{self._cloud_data_key: owner}) if owner else None self.quota = cloud_data.get(self._cc('quota')) # dict created = cloud_data.get(self._cc('createdDateTime'), None) modified = cloud_data.get(self._cc('lastModifiedDateTime'), None) local_tz = self.protocol.timezone self.created = parse(created).astimezone(local_tz) if created else None self.modified = parse(modified).astimezone( local_tz) if modified else None def __str__(self): return self.__repr__() def __repr__(self): return 'Drive: {}'.format( self.name or self.object_id or 'Default Drive') def get_root_folder(self): """ Returns the Root Folder of this drive :return: Root Folder :rtype: DriveItem """ if self.object_id: # reference the current drive_id url = self.build_url( self._endpoints.get('get_root_item').format(id=self.object_id)) else: # we don't know the drive_id so go to the default drive url = self.build_url(self._endpoints.get('get_root_item_default')) response = self.con.get(url) if not response: return None data = response.json() # Everything received from cloud must be passed as self._cloud_data_key return self._classifier(data)(parent=self, **{self._cloud_data_key: data}) def _base_get_list(self, url, limit=None, *, query=None, order_by=None, batch=None): """ Returns a collection of drive items """ if limit is None or limit > self.protocol.max_top_value: batch = self.protocol.max_top_value params = {'$top': batch if batch else limit} if order_by: params['$orderby'] = order_by if query: if query.has_filters: warnings.warn( 'Filters are not allowed by the Api Provider ' 'in this method') query.clear_filters() if isinstance(query, str): params['$filter'] = query else: params.update(query.as_params()) response = self.con.get(url, params=params) if not response: return iter(()) data = response.json() # Everything received from cloud must be passed as self._cloud_data_key items = ( self._classifier(item)(parent=self, **{self._cloud_data_key: item}) for item in data.get('value', [])) next_link = data.get(NEXT_LINK_KEYWORD, None) if batch and next_link: return Pagination(parent=self, data=items, constructor=self._classifier, next_link=next_link, limit=limit) else: return items def get_items(self, limit=None, *, query=None, order_by=None, batch=None): """ Returns a collection of drive items from the root folder :param int limit: max no. of items to get. Over 999 uses batch. :param query: applies a OData filter to the request :type query: Query or str :param order_by: orders the result set based on this condition :type order_by: Query or str :param int batch: batch size, retrieves items in batches allowing to retrieve more items than the limit. :return: list of items in this folder :rtype: list[DriveItem] or Pagination """ if self.object_id: # reference the current drive_id url = self.build_url( self._endpoints.get('list_items').format(id=self.object_id)) else: # we don't know the drive_id so go to the default url = self.build_url(self._endpoints.get('list_items_default')) return self._base_get_list(url, limit=limit, query=query, order_by=order_by, batch=batch) def get_recent(self, limit=None, *, query=None, order_by=None, batch=None): """ Returns a collection of recently used DriveItems :param int limit: max no. of items to get. Over 999 uses batch. :param query: applies a OData filter to the request :type query: Query or str :param order_by: orders the result set based on this condition :type order_by: Query or str :param int batch: batch size, retrieves items in batches allowing to retrieve more items than the limit. :return: list of items in this folder :rtype: list[DriveItem] or Pagination """ if self.object_id: # reference the current drive_id url = self.build_url( self._endpoints.get('recent').format(id=self.object_id)) else: # we don't know the drive_id so go to the default url = self.build_url(self._endpoints.get('recent_default')) return self._base_get_list(url, limit=limit, query=query, order_by=order_by, batch=batch) def get_shared_with_me(self, limit=None, *, query=None, order_by=None, batch=None): """ Returns a collection of DriveItems shared with me :param int limit: max no. of items to get. Over 999 uses batch. :param query: applies a OData filter to the request :type query: Query or str :param order_by: orders the result set based on this condition :type order_by: Query or str :param int batch: batch size, retrieves items in batches allowing to retrieve more items than the limit. :return: list of items in this folder :rtype: list[DriveItem] or Pagination """ if self.object_id: # reference the current drive_id url = self.build_url( self._endpoints.get('shared_with_me').format(id=self.object_id)) else: # we don't know the drive_id so go to the default url = self.build_url(self._endpoints.get('shared_with_me_default')) return self._base_get_list(url, limit=limit, query=query, order_by=order_by, batch=batch) def get_item(self, item_id): """ Returns a DriveItem by it's Id :return: one item :rtype: DriveItem """ if self.object_id: # reference the current drive_id url = self.build_url( self._endpoints.get('get_item').format(id=self.object_id, item_id=item_id)) else: # we don't know the drive_id so go to the default drive url = self.build_url( self._endpoints.get('get_item_default').format(item_id=item_id)) response = self.con.get(url) if not response: return None data = response.json() # Everything received from cloud must be passed as self._cloud_data_key return self._classifier(data)(parent=self, **{self._cloud_data_key: data}) def get_item_by_path(self, item_path): """ Returns a DriveItem by it's path: /path/to/file :return: one item :rtype: DriveItem """ if self.object_id: # reference the current drive_id url = self.build_url( self._endpoints.get('get_item_by_path').format(id=self.object_id, item_path=item_path)) else: # we don't know the drive_id so go to the default drive url = self.build_url( self._endpoints.get('get_item_by_path_default').format(item_path=item_path)) response = self.con.get(url) if not response: return None data = response.json() # Everything received from cloud must be passed as self._cloud_data_key return self._classifier(data)(parent=self, **{self._cloud_data_key: data}) def get_special_folder(self, name): """ Returns the specified Special Folder :return: a special Folder :rtype: drive.Folder """ name = name if \ isinstance(name, OneDriveWellKnowFolderNames) \ else OneDriveWellKnowFolderNames(name.lower()) name = name.value if self.object_id: # reference the current drive_id url = self.build_url( self._endpoints.get('get_special').format(id=self.object_id, name=name)) else: # we don't know the drive_id so go to the default url = self.build_url( self._endpoints.get('get_special_default').format(name=name)) response = self.con.get(url) if not response: return None data = response.json() # Everything received from cloud must be passed as self._cloud_data_key return self._classifier(data)(parent=self, **{self._cloud_data_key: data}) @staticmethod def _classifier(item): """ Subclass to change factory classes """ if 'folder' in item: return Folder elif 'image' in item: return Image elif 'photo' in item: return Photo else: return File def refresh(self): """ Updates this drive with data from the server :return: Success / Failure :rtype: bool """ if self.object_id is None: url = self.build_url(self._endpoints.get('default_drive')) else: url = self.build_url( self._endpoints.get('get_drive').format(id=self.object_id)) response = self.con.get(url) if not response: return False drive = response.json() self._update_data({self._cloud_data_key: drive}) return True def search(self, search_text, limit=None, *, query=None, order_by=None, batch=None): """ Search for DriveItems under this drive. Your app can search more broadly to include items shared with the current user. To broaden the search scope, use this search instead the Folder Search. The search API uses a search service under the covers, which requires indexing of content. As a result, there will be some time between creation of an item and when it will appear in search results. :param str search_text: The query text used to search for items. Values may be matched across several fields including filename, metadata, and file content. :param int limit: max no. of items to get. Over 999 uses batch. :param query: applies a OData filter to the request :type query: Query or str :param order_by: orders the result set based on this condition :type order_by: Query or str :param int batch: batch size, retrieves items in batches allowing to retrieve more items than the limit. :return: list of items in this folder :rtype: list[DriveItem] or Pagination """ if not isinstance(search_text, str) or not search_text: raise ValueError('Provide a valid search_text') if self.object_id is None: url = self.build_url(self._endpoints.get('search_default').format( search_text=search_text)) else: url = self.build_url( self._endpoints.get('search').format(id=self.object_id, search_text=search_text)) if limit is None or limit > self.protocol.max_top_value: batch = self.protocol.max_top_value params = {'$top': batch if batch else limit} if order_by: params['$orderby'] = order_by if query: if query.has_filters: warnings.warn( 'Filters are not allowed by the Api Provider ' 'in this method') query.clear_filters() if isinstance(query, str): params['$filter'] = query else: params.update(query.as_params()) response = self.con.get(url, params=params) if not response: return iter(()) data = response.json() # Everything received from cloud must be passed as self._cloud_data_key items = ( self._classifier(item)(parent=self, **{self._cloud_data_key: item}) for item in data.get('value', [])) next_link = data.get(NEXT_LINK_KEYWORD, None) if batch and next_link: return Pagination(parent=self, data=items, constructor=self._classifier, next_link=next_link, limit=limit) else: return items class Storage(ApiComponent): """ Parent Class that holds drives """ _endpoints = { 'default_drive': '/drive', 'get_drive': '/drives/{id}', 'list_drives': '/drives', } drive_constructor = Drive def __init__(self, *, parent=None, con=None, **kwargs): """ Create a storage representation :param parent: parent for this operation :type parent: Account :param Connection con: connection to use if no parent specified :param Protocol protocol: protocol to use if no parent specified (kwargs) :param str main_resource: use this resource instead of parent resource (kwargs) """ if parent and con: raise ValueError('Need a parent or a connection but not both') self.con = parent.con if parent else con # Choose the main_resource passed in kwargs over parent main_resource main_resource = kwargs.pop('main_resource', None) or ( getattr(parent, 'main_resource', None) if parent else None) super().__init__( protocol=parent.protocol if parent else kwargs.get('protocol'), main_resource=main_resource) def __str__(self): return self.__repr__() def __repr__(self): return 'Storage for resource: {}'.format(self.main_resource) def get_default_drive(self, request_drive=False): """ Returns a Drive instance :param request_drive: True will make an api call to retrieve the drive data :return: default One Drive :rtype: Drive """ if request_drive is False: return Drive(con=self.con, protocol=self.protocol, main_resource=self.main_resource, name='Default Drive') url = self.build_url(self._endpoints.get('default_drive')) response = self.con.get(url) if not response: return None drive = response.json() # Everything received from cloud must be passed as self._cloud_data_key return self.drive_constructor(con=self.con, protocol=self.protocol, main_resource=self.main_resource, **{self._cloud_data_key: drive}) def get_drive(self, drive_id): """ Returns a Drive instance :param drive_id: the drive_id to be retrieved :return: Drive for the id :rtype: Drive """ if not drive_id: return None url = self.build_url( self._endpoints.get('get_drive').format(id=drive_id)) response = self.con.get(url) if not response: return None drive = response.json() # Everything received from cloud must be passed as self._cloud_data_key return self.drive_constructor(con=self.con, protocol=self.protocol, main_resource=self.main_resource, **{self._cloud_data_key: drive}) def get_drives(self, limit=None, *, query=None, order_by=None, batch=None): """ Returns a collection of drives :param int limit: max no. of items to get. Over 999 uses batch. :param query: applies a OData filter to the request :type query: Query or str :param order_by: orders the result set based on this condition :type order_by: Query or str :param int batch: batch size, retrieves items in batches allowing to retrieve more items than the limit. :return: list of drives in this Storage :rtype: list[Drive] or Pagination """ url = self.build_url(self._endpoints.get('list_drives')) if limit is None or limit > self.protocol.max_top_value: batch = self.protocol.max_top_value params = {'$top': batch if batch else limit} if order_by: params['$orderby'] = order_by if query: if isinstance(query, str): params['$filter'] = query else: params.update(query.as_params()) response = self.con.get(url, params=params) if not response: return [] data = response.json() # Everything received from cloud must be passed as self._cloud_data_key drives = [self.drive_constructor(parent=self, **{self._cloud_data_key: drive}) for drive in data.get('value', [])] next_link = data.get(NEXT_LINK_KEYWORD, None) if batch and next_link: return Pagination(parent=self, data=drives, constructor=self.drive_constructor, next_link=next_link, limit=limit) else: return drives
36.821389
92
0.577239
204a9dae555e8b94b1ad26ba3a89d291fb2723b6
1,608
py
Python
tests/test_merge.py
Be5yond/testtp
abefbb7e9d9e086f372c247df5df00713294f841
[ "Apache-2.0" ]
2
2020-12-15T03:01:39.000Z
2021-01-04T05:51:39.000Z
tests/test_merge.py
Be5yond/testtp
abefbb7e9d9e086f372c247df5df00713294f841
[ "Apache-2.0" ]
null
null
null
tests/test_merge.py
Be5yond/testtp
abefbb7e9d9e086f372c247df5df00713294f841
[ "Apache-2.0" ]
null
null
null
import json from copy import deepcopy import testtp merge = testtp.utils.merge DATA = { 'a': 1, 'b': 'strgs', 'c': [{'type': 'a'}, {'type': 'b'}], 'd': { 'd1': [1,2,3], 'd2': 123, 'd3': {'k': 'v'} }, 'e': True } def test_schema_equal(): schema = { 'a': 1, 'b': 'strgs', 'c': [{'type': 'a'}, {'type': 'b'}], 'd': { 'd1': [1,2,3], 'd2': 123, 'd3': {'k': 'v'} }, 'e': True } ret = merge(deepcopy(DATA), schema) print(json.dumps(ret, indent=4)) def test_schema_check_datatype(): schema = { 'a': int, 'b': str, 'c': list, 'd': dict } ret = merge(deepcopy(DATA), schema) print(json.dumps(ret, indent=4)) def test_schema_check_part(): schema = { 'c': [dict], 'd': {'d2': int} } ret = merge(deepcopy(DATA), schema) print(json.dumps(ret, indent=4)) def test_schema_custom_function(): def le_100(i): return i < 100 schema = { 'a': le_100 } ret = merge(deepcopy(DATA), schema) print(json.dumps(ret, indent=4)) def test_schema_custom_method(): class Checker: @staticmethod def le_100(i): return i < 100 schema = { 'a': Checker.le_100 } ret = merge(deepcopy(DATA), schema) print(json.dumps(ret, indent=4)) def test_schema_addtion_checkpoint(): schema = { 'a': '' } ret = merge(deepcopy(DATA), schema) print(json.dumps(ret, indent=4)) # test_schema_custom_method()
20.1
44
0.49005
cb2bdc6b83d00092da195f03fe0e9f1c711a9a8c
519
py
Python
main_page/urls.py
slusarczyk41/my_django_website
1ae95297a1a5901a57f858cca1cf90fbd8c2dfb1
[ "MIT" ]
null
null
null
main_page/urls.py
slusarczyk41/my_django_website
1ae95297a1a5901a57f858cca1cf90fbd8c2dfb1
[ "MIT" ]
null
null
null
main_page/urls.py
slusarczyk41/my_django_website
1ae95297a1a5901a57f858cca1cf90fbd8c2dfb1
[ "MIT" ]
null
null
null
from django.urls import path from . import views app_name = 'main_page' urlpatterns = [ path('', views.index, name='index'), path('services/', views.services, name='services'), path('about/', views.about, name='about'), path('contact/', views.contact, name='contact'), path('valuation/', views.valuation, name='valuation'), path('contact_endpoint/', views.contact_endpoint, name='contact_endpoint'), path('download_cv_endpoint/', views.download_cv_endpoint, name='download_cv_endpoint'), ]
37.071429
91
0.699422
fedd9bdeb6f2c4998b627d11f67593f879664eca
5,031
py
Python
test/functional/feature_versionbits_warning.py
BitcoinReload/BitcoinReload
c927ca366ba769e33903b8e4f90d364c74e5e590
[ "MIT" ]
1
2022-03-23T00:32:26.000Z
2022-03-23T00:32:26.000Z
test/functional/feature_versionbits_warning.py
BitcoinReload/BitcoinReload
c927ca366ba769e33903b8e4f90d364c74e5e590
[ "MIT" ]
null
null
null
test/functional/feature_versionbits_warning.py
BitcoinReload/BitcoinReload
c927ca366ba769e33903b8e4f90d364c74e5e590
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2016-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test version bits warning system. Generate chains with block versions that appear to be signalling unknown soft-forks, and test that warning alerts are generated. """ import os import re from test_framework.blocktools import create_block, create_coinbase from test_framework.messages import msg_block from test_framework.p2p import P2PInterface from test_framework.test_framework import BitcoinReloadTestFramework VB_PERIOD = 144 # versionbits period length for regtest VB_THRESHOLD = 108 # versionbits activation threshold for regtest VB_TOP_BITS = 0x20000000 VB_UNKNOWN_BIT = 27 # Choose a bit unassigned to any deployment VB_UNKNOWN_VERSION = VB_TOP_BITS | (1 << VB_UNKNOWN_BIT) WARN_UNKNOWN_RULES_ACTIVE = "unknown new rules activated (versionbit {})".format(VB_UNKNOWN_BIT) VB_PATTERN = re.compile("Warning: unknown new rules activated.*versionbit") class VersionBitsWarningTest(BitcoinReloadTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def setup_network(self): self.alert_filename = os.path.join(self.options.tmpdir, "alert.txt") # Open and close to create zero-length file with open(self.alert_filename, 'w', encoding='utf8'): pass self.extra_args = [["-alertnotify=echo %s >> \"" + self.alert_filename + "\""]] self.setup_nodes() def send_blocks_with_version(self, peer, numblocks, version): """Send numblocks blocks to peer with version set""" tip = self.nodes[0].getbestblockhash() height = self.nodes[0].getblockcount() block_time = self.nodes[0].getblockheader(tip)["time"] + 1 tip = int(tip, 16) for _ in range(numblocks): block = create_block(tip, create_coinbase(height + 1), block_time) block.nVersion = version block.solve() peer.send_message(msg_block(block)) block_time += 1 height += 1 tip = block.sha256 peer.sync_with_ping() def versionbits_in_alert_file(self): """Test that the versionbits warning has been written to the alert file.""" alert_text = open(self.alert_filename, 'r', encoding='utf8').read() return VB_PATTERN.search(alert_text) is not None def run_test(self): node = self.nodes[0] peer = node.add_p2p_connection(P2PInterface()) node_deterministic_address = node.get_deterministic_priv_key().address # Mine one period worth of blocks node.generatetoaddress(VB_PERIOD, node_deterministic_address) self.log.info("Check that there is no warning if previous VB_BLOCKS have <VB_THRESHOLD blocks with unknown versionbits version.") # Build one period of blocks with < VB_THRESHOLD blocks signaling some unknown bit self.send_blocks_with_version(peer, VB_THRESHOLD - 1, VB_UNKNOWN_VERSION) node.generatetoaddress(VB_PERIOD - VB_THRESHOLD + 1, node_deterministic_address) # Check that we're not getting any versionbit-related errors in get*info() assert not VB_PATTERN.match(node.getmininginfo()["warnings"]) assert not VB_PATTERN.match(node.getnetworkinfo()["warnings"]) # Build one period of blocks with VB_THRESHOLD blocks signaling some unknown bit self.send_blocks_with_version(peer, VB_THRESHOLD, VB_UNKNOWN_VERSION) node.generatetoaddress(VB_PERIOD - VB_THRESHOLD, node_deterministic_address) self.log.info("Check that there is a warning if previous VB_BLOCKS have >=VB_THRESHOLD blocks with unknown versionbits version.") # Mine a period worth of expected blocks so the generic block-version warning # is cleared. This will move the versionbit state to ACTIVE. node.generatetoaddress(VB_PERIOD, node_deterministic_address) # Stop-start the node. This is required because bitcoinreloadd will only warn once about unknown versions or unknown rules activating. self.restart_node(0) # Generating one block guarantees that we'll get out of IBD node.generatetoaddress(1, node_deterministic_address) self.wait_until(lambda: not node.getblockchaininfo()['initialblockdownload']) # Generating one more block will be enough to generate an error. node.generatetoaddress(1, node_deterministic_address) # Check that get*info() shows the versionbits unknown rules warning assert WARN_UNKNOWN_RULES_ACTIVE in node.getmininginfo()["warnings"] assert WARN_UNKNOWN_RULES_ACTIVE in node.getnetworkinfo()["warnings"] # Check that the alert file shows the versionbits unknown rules warning self.wait_until(lambda: self.versionbits_in_alert_file()) if __name__ == '__main__': VersionBitsWarningTest().main()
48.375
142
0.719141
fbf0e14576e50aaa801de5dc50f88606553add6d
5,637
py
Python
tweet_engine.py
alybel/vrbase
c01a8b641e3e6c011fe32e343fa01eca01f4c7c6
[ "MIT" ]
null
null
null
tweet_engine.py
alybel/vrbase
c01a8b641e3e6c011fe32e343fa01eca01f4c7c6
[ "MIT" ]
null
null
null
tweet_engine.py
alybel/vrbase
c01a8b641e3e6c011fe32e343fa01eca01f4c7c6
[ "MIT" ]
null
null
null
#! /usr/bin/python -u import sys import os.path import time valureach_ops_path = "/home/vr/valureach_ops" sys.path.append("%s/bluebird" % valureach_ops_path) import load_config import bblib as bbl import random import vr_main import subprocess def rtime(): return int(random.random() * 10 * 60) def tweet_account(account_name=""): print "starting", account_name account_path = "%s/accounts/%s/" % (valureach_ops_path, account_name) if not os.path.isfile("%s/tweet.py" % account_path): return False sys.path.append(account_path) cfg = load_config.load_config(account_name) import tweet bbl.set_cfg(cfg) auth, api = bbl.connect_app_to_twitter() #Check for correct frequency freq = tweet.freq * 60 logfile = "%stweet_engine.log" % account_path if os.path.isfile(logfile): with open(logfile, 'r') as f: for line in f: if "tweetid" in line: tweet_id =line.strip("\n").split(":")[1] try: api.destroy_status(tweet_id) print account_name,"tweet destroyed in ramping up", tweet_id except: pass #reset the logfile f = open(logfile, "w") f.close() while True: #Tweet own tweets sel_tweet = random.choice(tweet.tweets) print "selected tweet:", sel_tweet res = api.update_status(sel_tweet) with open(logfile, 'a') as f: f.write("tweetid:%d\n" % res.id) print account_name, "tweeted:", sel_tweet time.sleep(rtime()) #retweet tweets from friended accounts for account in tweet.watch_account: print "seeking for tweets to retweet in", account apath = "%s/accounts/%s/" % (valureach_ops_path, account) lf = "%stweet_engine.log"%apath if not os.path.isfile(lf): continue with open(lf,'r') as f2: for line in f2: print line if "tweetid" in line: tweet_id = line.strip("\n").split(":")[1] print "tweet_id", tweet_id try: api.retweet(tweet_id) print "retweeted", tweet_id except Exception,e: print e print "retweet not carried out", tweet_id print "reached sleep point" time.sleep(freq) #remove own tweets try: api.destroy_status(res.id) except: pass print account_name, "status deleted" with open(logfile, 'a') as f: f.write("deleted-tweetiid:%d\n"%res.id) f = open(logfile, "w") f.close() time.sleep(rtime()) def clean_account(account, api = None): """ not used yet """ if not api: api = get_account_api(account) account_path = "%s/accounts/%s/" % (valureach_ops_path, account_name) logfile = "%stweet_engine.log"%account_path if os.path.isfile(logfile): with open(logfile, 'r') as f: for line in f: if "tweetid" in line: tweet_id = line.strip("\n").split(":")[1] try: api.destroy_status(tweet_id) print account_name,"tweet destroyed in ramping up", tweet_id except: pass def get_account_api(account): account_path = "%s/accounts/%s/" % (valureach_ops_path, account_name) sys.path.append(account_path) import config as cfg bbl.set_cfg(cfg) auth, api = bbl.connect_app_to_twitter() return api def start_account(account): if os.path.isfile("accounts/%s/.tweet_engine_lock" % account): print "tweet engine Account", account, "is locked. is already running?" return False print "starting account", account with open("stdout/tweet_engine_%s.out" % account, "w") as f: subprocess.Popen(["python", "tweet_engine.py", "%s" % account], stdout=f) subprocess.call(["touch","accounts/%s/.tweet_engine_lock" % account]) return True def stop_account(account): procname = "tweet_engine.py" subprocess.call(["rm","accounts/%s/.tweet_engine_lock" % account]) print "lockfile removed" for proc in psutil.process_iter(): if proc.name() == procname and account in proc.cmdline()[-1]: print "killing", proc.cmdline() psutil.Process(proc.pid).kill() return True if not auto_call: print "no running tweet engine proccess for account", account, "could be found" return False def remove_all_lockfiles(): accounts = vr_main.get_accounts() for account in accounts: subprocess.call(["rm","accounts/%s/.tweet_engine_lock" % account]) print "all tweet_engine lockfiles removed" def start_all(): accounts = vr_main.get_accounts() for account in accounts: start_account(account) if __name__ == "__main__": args = sys.argv if not len(args) == 2: print "usage: tweet_engine.py <account_name>" print "other options: all, stopall" sys.exit() print "starting for account", args[1] if args[1] == "all": start_all() elif args[1] == "stopall": subprocess.call(["killall", "tweet_engine.py"]) subprocess.call(["killall", "tweet_engine.py"]) remove_all_lockfiles() else: tweet_account(args[1])
34.796296
87
0.573532
6e3169d0e8d671dc0eb5c30e1fe8db3a520d546f
118
py
Python
mujoco_parallel/__init__.py
thanhbok26b/mujoco-rewards-landscape-visualization
c1a95b38a0ea03468bbbb7ce013eff37ccd67101
[ "MIT" ]
null
null
null
mujoco_parallel/__init__.py
thanhbok26b/mujoco-rewards-landscape-visualization
c1a95b38a0ea03468bbbb7ce013eff37ccd67101
[ "MIT" ]
null
null
null
mujoco_parallel/__init__.py
thanhbok26b/mujoco-rewards-landscape-visualization
c1a95b38a0ea03468bbbb7ce013eff37ccd67101
[ "MIT" ]
null
null
null
from .mujoco_parallel import MujocoParallel from .worker_manager import WorkerManager from .config import benchmarks
23.6
43
0.864407
827735cfbb792b3d588edfd9636ab425182577de
1,539
py
Python
backend/tests/test_api_admin.py
kevinmonisit/shrunk
55106356735c3491f8c8c0774f5ae500ba1c970a
[ "MIT" ]
13
2015-05-08T00:26:23.000Z
2021-07-28T15:42:10.000Z
backend/tests/test_api_admin.py
kevinmonisit/shrunk
55106356735c3491f8c8c0774f5ae500ba1c970a
[ "MIT" ]
68
2015-01-12T20:27:44.000Z
2021-05-17T19:08:05.000Z
backend/tests/test_api_admin.py
kevinmonisit/shrunk
55106356735c3491f8c8c0774f5ae500ba1c970a
[ "MIT" ]
7
2015-08-05T20:31:20.000Z
2022-01-28T21:14:06.000Z
# admin.get_endpoint_stats GET /api/v1/admin/stats/endpoint # admin.get_overview_stats POST /api/v1/admin/stats/overview from datetime import datetime, timezone, timedelta from werkzeug.test import Client from util import dev_login def test_endpoint_stats(client: Client) -> None: with dev_login(client, 'admin'): resp = client.get('/api/v1/admin/stats/endpoint') assert resp.status_code == 200 assert 'stats' in resp.json assert isinstance(resp.json['stats'], list) def test_endpoint_stats_unauthorized(client: Client) -> None: with dev_login(client, 'user'): resp = client.get('/api/v1/admin/stats/endpoint') assert resp.status_code == 403 def test_overview_stats(client: Client) -> None: with dev_login(client, 'admin'): resp = client.post('/api/v1/admin/stats/overview', json={}) assert resp.status_code == 200 def test_overview_stats_range(client: Client) -> None: with dev_login(client, 'admin'): end = datetime.now(timezone.utc) begin = end - timedelta(days=2) resp = client.post('/api/v1/admin/stats/overview', json={ 'range': { 'begin': begin.isoformat(), 'end': end.isoformat(), }, }) assert resp.status_code == 200 def test_overview_stats_unauthorized(client: Client) -> None: with dev_login(client, 'user'): resp = client.post('/api/v1/admin/stats/overview', json={}) assert resp.status_code == 403
32.0625
69
0.641975
ef072dc2734042c31d6d854b96644cc8d09645de
30,675
py
Python
tools/metrics/actions/extract_actions.py
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
tools/metrics/actions/extract_actions.py
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
tools/metrics/actions/extract_actions.py
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
#!/usr/bin/env python # # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Extract UserMetrics "actions" strings from the Chrome source. This program generates the list of known actions we expect to see in the user behavior logs. It walks the Chrome source, looking for calls to UserMetrics functions, extracting actions and warning on improper calls, as well as generating the lists of possible actions in situations where there are many possible actions. See also: base/metrics/user_metrics.h After extracting all actions, the content will go through a pretty print function to make sure it's well formatted. If the file content needs to be changed, a window will be prompted asking for user's consent. The old version will also be saved in a backup file. """ from __future__ import print_function __author__ = 'evanm (Evan Martin)' import logging import os import re import shutil import sys from xml.dom import minidom if sys.version_info.major == 2: from HTMLParser import HTMLParser else: from html.parser import HTMLParser import action_utils import actions_model # Import the metrics/common module for pretty print xml. sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common')) import presubmit_util import diff_util import pretty_print_xml USER_METRICS_ACTION_RE = re.compile(r""" [^a-zA-Z] # Preceded by a non-alphabetical character. (?: # Begin non-capturing group. UserMetricsAction # C++ / Objective C function name. | # or... RecordUserAction\.record # Java function name. ) # End non-capturing group. \( # Opening parenthesis. \s* # Any amount of whitespace, including new lines. (.+?) # A sequence of characters for the param. \) # Closing parenthesis. """, re.VERBOSE | re.DOTALL # Verbose syntax and makes . also match new lines. ) USER_METRICS_ACTION_RE_JS = re.compile(r""" chrome\.send # Start of function call. \( # Opening parenthesis. \s* # Any amount of whitespace, including new lines. # WebUI message handled by CoreOptionsHandler. 'coreOptionsUserMetricsAction' , # Separator after first parameter. \s* # Any amount of whitespace, including new lines. \[ # Opening bracket for arguments for C++ function. \s* # Any amount of whitespace, including new lines. (.+?) # A sequence of characters for the param. \s* # Any amount of whitespace, including new lines. \] # Closing bracket. \s* # Any amount of whitespace, including new lines. \) # Closing parenthesis. """, re.VERBOSE | re.DOTALL # Verbose syntax and makes . also match new lines. ) USER_METRICS_ACTION_RE_DEVTOOLS = re.compile(r""" InspectorFrontendHost\.recordUserMetricsAction # Start of function call. \( # Opening parenthesis. \s* # Any amount of whitespace, including new lines. (.+?) # A sequence of characters for the param. \s* # Any amount of whitespace, including new lines. \) # Closing parenthesis. """, re.VERBOSE | re.DOTALL # Verbose syntax and makes . also match new lines. ) COMPUTED_ACTION_RE = re.compile(r'RecordComputedAction') QUOTED_STRING_RE = re.compile(r"""('[^']+'|"[^"]+")$""") # Files that are known to use content::RecordComputedAction(), which means # they require special handling code in this script. # To add a new file, add it to this list and add the appropriate logic to # generate the known actions to AddComputedActions() below. KNOWN_COMPUTED_USERS = ( 'back_forward_menu_model.cc', 'options_page_view.cc', 'render_view_host.cc', # called using webkit identifiers 'user_metrics.cc', # method definition 'new_tab_ui.cc', # most visited clicks 1-9 'extension_metrics_module.cc', # extensions hook for user metrics 'language_options_handler_common.cc', # languages and input methods in CrOS 'cros_language_options_handler.cc', # languages and input methods in CrOS 'external_metrics.cc', # see AddChromeOSActions() 'core_options_handler.cc', # see AddWebUIActions() 'browser_render_process_host.cc', # see AddRendererActions() 'render_thread_impl.cc', # impl of RenderThread::RecordComputedAction() 'render_process_host_impl.cc', # browser side impl for # RenderThread::RecordComputedAction() 'mock_render_thread.cc', # mock of RenderThread::RecordComputedAction() 'ppb_pdf_impl.cc', # see AddClosedSourceActions() 'pepper_pdf_host.cc', # see AddClosedSourceActions() 'record_user_action.cc', # see RecordUserAction.java 'blink_platform_impl.cc', # see WebKit/public/platform/Platform.h 'devtools_ui_bindings.cc', # see AddDevToolsActions() 'sharing_hub_bubble_controller.cc', # share targets 'sharing_hub_sub_menu_model.cc', # share targets ) # Language codes used in Chrome. The list should be updated when a new # language is added to app/l10n_util.cc, as follows: # # % (cat app/l10n_util.cc | \ # perl -n0e 'print $1 if /kAcceptLanguageList.*?\{(.*?)\}/s' | \ # perl -nle 'print $1, if /"(.*)"/'; echo 'es-419') | \ # sort | perl -pe "s/(.*)\n/'\$1', /" | \ # fold -w75 -s | perl -pe 's/^/ /;s/ $//'; echo # # The script extracts language codes from kAcceptLanguageList, but es-419 # (Spanish in Latin America) is an exception. LANGUAGE_CODES = ( 'af', 'am', 'ar', 'az', 'be', 'bg', 'bh', 'bn', 'br', 'bs', 'ca', 'co', 'cs', 'cy', 'da', 'de', 'de-AT', 'de-CH', 'de-DE', 'el', 'en', 'en-AU', 'en-CA', 'en-GB', 'en-NZ', 'en-US', 'en-ZA', 'eo', 'es', 'es-419', 'et', 'eu', 'fa', 'fi', 'fil', 'fo', 'fr', 'fr-CA', 'fr-CH', 'fr-FR', 'fy', 'ga', 'gd', 'gl', 'gn', 'gu', 'ha', 'haw', 'he', 'hi', 'hr', 'hu', 'hy', 'ia', 'id', 'is', 'it', 'it-CH', 'it-IT', 'ja', 'jw', 'ka', 'kk', 'km', 'kn', 'ko', 'ku', 'ky', 'la', 'ln', 'lo', 'lt', 'lv', 'mk', 'ml', 'mn', 'mo', 'mr', 'ms', 'mt', 'nb', 'ne', 'nl', 'nn', 'no', 'oc', 'om', 'or', 'pa', 'pl', 'ps', 'pt', 'pt-BR', 'pt-PT', 'qu', 'rm', 'ro', 'ru', 'sd', 'sh', 'si', 'sk', 'sl', 'sn', 'so', 'sq', 'sr', 'st', 'su', 'sv', 'sw', 'ta', 'te', 'tg', 'th', 'ti', 'tk', 'to', 'tr', 'tt', 'tw', 'ug', 'uk', 'ur', 'uz', 'vi', 'xh', 'yi', 'yo', 'zh', 'zh-CN', 'zh-TW', 'zu', ) # Input method IDs used in Chrome OS. The list should be updated when a # new input method is added to # chromeos/ime/input_methods.txt in the Chrome tree, as # follows: # # % sort chromeos/ime/input_methods.txt | \ # perl -ne "print \"'\$1', \" if /^([^#]+?)\s/" | \ # fold -w75 -s | perl -pe 's/^/ /;s/ $//'; echo # # The script extracts input method IDs from input_methods.txt. INPUT_METHOD_IDS = ( 'xkb:am:phonetic:arm', 'xkb:be::fra', 'xkb:be::ger', 'xkb:be::nld', 'xkb:bg::bul', 'xkb:bg:phonetic:bul', 'xkb:br::por', 'xkb:by::bel', 'xkb:ca::fra', 'xkb:ca:eng:eng', 'xkb:ca:multix:fra', 'xkb:ch::ger', 'xkb:ch:fr:fra', 'xkb:cz::cze', 'xkb:cz:qwerty:cze', 'xkb:de::ger', 'xkb:de:neo:ger', 'xkb:dk::dan', 'xkb:ee::est', 'xkb:es::spa', 'xkb:es:cat:cat', 'xkb:fi::fin', 'xkb:fr::fra', 'xkb:gb:dvorak:eng', 'xkb:gb:extd:eng', 'xkb:ge::geo', 'xkb:gr::gre', 'xkb:hr::scr', 'xkb:hu::hun', 'xkb:il::heb', 'xkb:is::ice', 'xkb:it::ita', 'xkb:jp::jpn', 'xkb:latam::spa', 'xkb:lt::lit', 'xkb:lv:apostrophe:lav', 'xkb:mn::mon', 'xkb:no::nob', 'xkb:pl::pol', 'xkb:pt::por', 'xkb:ro::rum', 'xkb:rs::srp', 'xkb:ru::rus', 'xkb:ru:phonetic:rus', 'xkb:se::swe', 'xkb:si::slv', 'xkb:sk::slo', 'xkb:tr::tur', 'xkb:ua::ukr', 'xkb:us::eng', 'xkb:us:altgr-intl:eng', 'xkb:us:colemak:eng', 'xkb:us:dvorak:eng', 'xkb:us:intl:eng', ) # The path to the root of the repository. REPOSITORY_ROOT = os.path.join(os.path.dirname(__file__), '..', '..', '..') number_of_files_total = 0 # Tags that need to be inserted to each 'action' tag and their default content. TAGS = {'description': 'Please enter the description of the metric.', 'owner': ('Please list the metric\'s owners. Add more owner tags as ' 'needed.')} SHARE_TARGETS = { 'CopyURLSelected', 'QRCodeSelected', 'ScreenshotSelected', 'SendTabToSelfSelected', 'CastSelected', 'SavePageSelected', 'ThirdPartyAppSelected' } def AddComputedActions(actions): """Add computed actions to the actions list. Arguments: actions: set of actions to add to. """ # Actions for back_forward_menu_model.cc. for dir in ('BackMenu_', 'ForwardMenu_'): actions.add(dir + 'ShowFullHistory') actions.add(dir + 'Popup') for i in range(1, 20): actions.add(dir + 'HistoryClick' + str(i)) actions.add(dir + 'ChapterClick' + str(i)) # Actions for new_tab_ui.cc. for i in range(1, 10): actions.add('MostVisited%d' % i) # Actions for language_options_handler.cc (Chrome OS specific). for input_method_id in INPUT_METHOD_IDS: actions.add('LanguageOptions_DisableInputMethod_%s' % input_method_id) actions.add('LanguageOptions_EnableInputMethod_%s' % input_method_id) for language_code in LANGUAGE_CODES: actions.add('LanguageOptions_UiLanguageChange_%s' % language_code) actions.add('LanguageOptions_SpellCheckLanguageChange_%s' % language_code) # Actions for sharing_hub_bubble_controller.cc and # sharing_hub_sub_menu_model.cc. for share_target in SHARE_TARGETS: actions.add('SharingHubDesktop.%s' % share_target) def AddPDFPluginActions(actions): """Add actions that are sent by the PDF plugin. Arguments actions: set of actions to add to. """ actions.add('PDF.LoadFailure') actions.add('PDF.LoadSuccess') actions.add('PDF.PreviewDocumentLoadFailure') actions.add('PDF.PrintPage') actions.add('PDF.ZoomFromBrowser') actions.add('PDF_Unsupported_3D') actions.add('PDF_Unsupported_Attachment') actions.add('PDF_Unsupported_Bookmarks') actions.add('PDF_Unsupported_Digital_Signature') actions.add('PDF_Unsupported_Movie') actions.add('PDF_Unsupported_Portfolios_Packages') actions.add('PDF_Unsupported_Rights_Management') actions.add('PDF_Unsupported_Screen') actions.add('PDF_Unsupported_Shared_Form') actions.add('PDF_Unsupported_Shared_Review') actions.add('PDF_Unsupported_Sound') actions.add('PDF_Unsupported_XFA') def AddBookmarkManagerActions(actions): """Add actions that are used by BookmarkManager. Arguments actions: set of actions to add to. """ actions.add('BookmarkManager_Command_AddPage') actions.add('BookmarkManager_Command_Copy') actions.add('BookmarkManager_Command_Cut') actions.add('BookmarkManager_Command_Delete') actions.add('BookmarkManager_Command_Edit') actions.add('BookmarkManager_Command_Export') actions.add('BookmarkManager_Command_Import') actions.add('BookmarkManager_Command_NewFolder') actions.add('BookmarkManager_Command_OpenIncognito') actions.add('BookmarkManager_Command_OpenInNewTab') actions.add('BookmarkManager_Command_OpenInNewWindow') actions.add('BookmarkManager_Command_OpenInSame') actions.add('BookmarkManager_Command_Paste') actions.add('BookmarkManager_Command_ShowInFolder') actions.add('BookmarkManager_Command_Sort') actions.add('BookmarkManager_Command_UndoDelete') actions.add('BookmarkManager_Command_UndoGlobal') actions.add('BookmarkManager_Command_UndoNone') actions.add('BookmarkManager_NavigateTo_BookmarkBar') actions.add('BookmarkManager_NavigateTo_Mobile') actions.add('BookmarkManager_NavigateTo_Other') actions.add('BookmarkManager_NavigateTo_Recent') actions.add('BookmarkManager_NavigateTo_Search') actions.add('BookmarkManager_NavigateTo_SubFolder') def AddChromeOSActions(actions): """Add actions reported by non-Chrome processes in Chrome OS. Arguments: actions: set of actions to add to. """ # Actions sent by Chrome OS update engine. actions.add('Updater.ServerCertificateChanged') actions.add('Updater.ServerCertificateFailed') def AddExtensionActions(actions): """Add actions reported by extensions via chrome.metricsPrivate API. Arguments: actions: set of actions to add to. """ # Actions sent by Chrome OS File Browser. actions.add('FileBrowser.CreateNewFolder') actions.add('FileBrowser.PhotoEditor.Edit') actions.add('FileBrowser.PhotoEditor.View') actions.add('FileBrowser.SuggestApps.ShowDialog') # Actions sent by Google Now client. actions.add('GoogleNow.MessageClicked') actions.add('GoogleNow.ButtonClicked0') actions.add('GoogleNow.ButtonClicked1') actions.add('GoogleNow.Dismissed') # Actions sent by Chrome Connectivity Diagnostics. actions.add('ConnectivityDiagnostics.LaunchSource.OfflineChromeOS') actions.add('ConnectivityDiagnostics.LaunchSource.WebStore') actions.add('ConnectivityDiagnostics.UA.LogsShown') actions.add('ConnectivityDiagnostics.UA.PassingTestsShown') actions.add('ConnectivityDiagnostics.UA.SettingsShown') actions.add('ConnectivityDiagnostics.UA.TestResultExpanded') actions.add('ConnectivityDiagnostics.UA.TestSuiteRun') class InvalidStatementException(Exception): """Indicates an invalid statement was found.""" class ActionNameFinder: """Helper class to find action names in source code file.""" def __init__(self, path, contents, action_re): self.__path = path self.__pos = 0 self.__contents = contents self.__action_re = action_re def FindNextAction(self): """Finds the next action name in the file. Returns: The name of the action found or None if there are no more actions. Raises: InvalidStatementException if the next action statement is invalid and could not be parsed. There may still be more actions in the file, so FindNextAction() can continue to be called to find following ones. """ match = self.__action_re.search(self.__contents, pos=self.__pos) if not match: return None match_start = match.start() self.__pos = match.end() match = QUOTED_STRING_RE.match(match.group(1)) if not match: if self.__action_re == USER_METRICS_ACTION_RE_JS: return None self._RaiseException(match_start, self.__pos) # Remove surrounding quotation marks. return match.group(1)[1:-1] def _RaiseException(self, match_start, match_end): """Raises an InvalidStatementException for the specified code range.""" line_number = self.__contents.count('\n', 0, match_start) + 1 # Add 1 to |match_start| since the RE checks the preceding character. statement = self.__contents[match_start + 1:match_end] raise InvalidStatementException( '%s uses UserMetricsAction incorrectly on line %d:\n%s' % (self.__path, line_number, statement)) def GrepForActions(path, actions): """Grep a source file for calls to UserMetrics functions. Arguments: path: path to the file actions: set of actions to add to """ global number_of_files_total number_of_files_total = number_of_files_total + 1 # Check the extension, using the regular expression for C++ syntax by default. ext = os.path.splitext(path)[1].lower() if ext == '.js': action_re = USER_METRICS_ACTION_RE_JS else: action_re = USER_METRICS_ACTION_RE finder = ActionNameFinder(path, open(path).read(), action_re) while True: try: action_name = finder.FindNextAction() if not action_name: break actions.add(action_name) except InvalidStatementException as e: logging.warning(str(e)) if action_re != USER_METRICS_ACTION_RE: return line_number = 0 for line in open(path): line_number = line_number + 1 if COMPUTED_ACTION_RE.search(line): # Warn if this file shouldn't be calling RecordComputedAction. if os.path.basename(path) not in KNOWN_COMPUTED_USERS: logging.warning('%s has RecordComputedAction statement on line %d' % (path, line_number)) class WebUIActionsParser(HTMLParser): """Parses an HTML file, looking for all tags with a 'metric' attribute. Adds user actions corresponding to any metrics found. Arguments: actions: set of actions to add to """ def __init__(self, actions): HTMLParser.__init__(self) self.actions = actions def handle_starttag(self, tag, attrs): # We only care to examine tags that have a 'metric' attribute. attrs = dict(attrs) if not 'metric' in attrs: return # Boolean metrics have two corresponding actions. All other metrics have # just one corresponding action. By default, we check the 'dataType' # attribute. is_boolean = ('dataType' in attrs and attrs['dataType'] == 'boolean') if 'type' in attrs and attrs['type'] in ('checkbox', 'radio'): if attrs['type'] == 'checkbox': is_boolean = True else: # Radio buttons are boolean if and only if their values are 'true' or # 'false'. assert(attrs['type'] == 'radio') if 'value' in attrs and attrs['value'] in ['true', 'false']: is_boolean = True if is_boolean: self.actions.add(attrs['metric'] + '_Enable') self.actions.add(attrs['metric'] + '_Disable') else: self.actions.add(attrs['metric']) def GrepForWebUIActions(path, actions): """Grep a WebUI source file for elements with associated metrics. Arguments: path: path to the file actions: set of actions to add to """ close_called = False try: parser = WebUIActionsParser(actions) parser.feed(open(path).read()) # An exception can be thrown by parser.close(), so do it in the try to # ensure the path of the file being parsed gets printed if that happens. close_called = True parser.close() except Exception as e: print("Error encountered for path %s" % path) raise e finally: if not close_called: parser.close() def GrepForDevToolsActions(path, actions): """Grep a DevTools source file for calls to UserMetrics functions. Arguments: path: path to the file actions: set of actions to add to """ global number_of_files_total number_of_files_total = number_of_files_total + 1 ext = os.path.splitext(path)[1].lower() if ext != '.js': return finder = ActionNameFinder(path, open(path).read(), USER_METRICS_ACTION_RE_DEVTOOLS) while True: try: action_name = finder.FindNextAction() if not action_name: break actions.add(action_name) except InvalidStatementException as e: logging.warning(str(e)) def WalkDirectory(root_path, actions, extensions, callback): for path, dirs, files in os.walk(root_path): if '.svn' in dirs: dirs.remove('.svn') if '.git' in dirs: dirs.remove('.git') for file in files: filename, ext = os.path.splitext(file) if ext in extensions and not filename.endswith('test'): callback(os.path.join(path, file), actions) def AddLiteralActions(actions): """Add literal actions specified via calls to UserMetrics functions. Arguments: actions: set of actions to add to. """ EXTENSIONS = ('.cc', '.cpp', '.mm', '.c', '.m', '.java') # Walk the source tree to process all files. ash_root = os.path.normpath(os.path.join(REPOSITORY_ROOT, 'ash')) WalkDirectory(ash_root, actions, EXTENSIONS, GrepForActions) chrome_root = os.path.normpath(os.path.join(REPOSITORY_ROOT, 'chrome')) WalkDirectory(chrome_root, actions, EXTENSIONS, GrepForActions) content_root = os.path.normpath(os.path.join(REPOSITORY_ROOT, 'content')) WalkDirectory(content_root, actions, EXTENSIONS, GrepForActions) components_root = os.path.normpath(os.path.join(REPOSITORY_ROOT, 'components')) WalkDirectory(components_root, actions, EXTENSIONS, GrepForActions) net_root = os.path.normpath(os.path.join(REPOSITORY_ROOT, 'net')) WalkDirectory(net_root, actions, EXTENSIONS, GrepForActions) webkit_root = os.path.normpath(os.path.join(REPOSITORY_ROOT, 'webkit')) WalkDirectory(os.path.join(webkit_root, 'glue'), actions, EXTENSIONS, GrepForActions) WalkDirectory(os.path.join(webkit_root, 'port'), actions, EXTENSIONS, GrepForActions) webkit_core_root = os.path.normpath( os.path.join(REPOSITORY_ROOT, 'third_party/blink/renderer/core')) WalkDirectory(webkit_core_root, actions, EXTENSIONS, GrepForActions) def AddWebUIActions(actions): """Add user actions defined in WebUI files. Arguments: actions: set of actions to add to. """ resources_root = os.path.join(REPOSITORY_ROOT, 'chrome', 'browser', 'resources') WalkDirectory(resources_root, actions, ('.html'), GrepForWebUIActions) WalkDirectory(resources_root, actions, ('.js'), GrepForActions) def AddDevToolsActions(actions): """Add user actions defined in DevTools frontend files. Arguments: actions: set of actions to add to. """ resources_root = os.path.join(REPOSITORY_ROOT, 'third_party', 'blink', 'renderer', 'devtools', 'front_end') WalkDirectory(resources_root, actions, ('.js'), GrepForDevToolsActions) def AddHistoryPageActions(actions): """Add actions that are used in History page. Arguments actions: set of actions to add to. """ actions.add('HistoryPage_BookmarkStarClicked') actions.add('HistoryPage_EntryMenuRemoveFromHistory') actions.add('HistoryPage_EntryLinkClick') actions.add('HistoryPage_EntryLinkRightClick') actions.add('HistoryPage_SearchResultClick') actions.add('HistoryPage_EntryMenuShowMoreFromSite') actions.add('HistoryPage_NewestHistoryClick') actions.add('HistoryPage_NewerHistoryClick') actions.add('HistoryPage_OlderHistoryClick') actions.add('HistoryPage_Search') actions.add('HistoryPage_InitClearBrowsingData') actions.add('HistoryPage_RemoveSelected') actions.add('HistoryPage_SearchResultRemove') actions.add('HistoryPage_ConfirmRemoveSelected') actions.add('HistoryPage_CancelRemoveSelected') def AddAutomaticResetBannerActions(actions): """Add actions that are used for the automatic profile settings reset banners in chrome://settings. Arguments actions: set of actions to add to. """ # These actions relate to the the automatic settings reset banner shown as # a result of the reset prompt. actions.add('AutomaticReset_WebUIBanner_BannerShown') actions.add('AutomaticReset_WebUIBanner_ManuallyClosed') actions.add('AutomaticReset_WebUIBanner_ResetClicked') # These actions relate to the the automatic settings reset banner shown as # a result of settings hardening. actions.add('AutomaticSettingsReset_WebUIBanner_BannerShown') actions.add('AutomaticSettingsReset_WebUIBanner_ManuallyClosed') actions.add('AutomaticSettingsReset_WebUIBanner_LearnMoreClicked') actions.add('AutomaticSettingsReset_WebUIBanner_ResetClicked') class Error(Exception): pass def _ExtractText(parent_dom, tag_name): """Extract the text enclosed by |tag_name| under |parent_dom| Args: parent_dom: The parent Element under which text node is searched for. tag_name: The name of the tag which contains a text node. Returns: A (list of) string enclosed by |tag_name| under |parent_dom|. """ texts = [] for child_dom in parent_dom.getElementsByTagName(tag_name): text_dom = child_dom.childNodes if text_dom.length != 1: raise Error('More than 1 child node exists under %s' % tag_name) if text_dom[0].nodeType != minidom.Node.TEXT_NODE: raise Error('%s\'s child node is not a text node.' % tag_name) texts.append(text_dom[0].data) return texts def ParseActionFile(file_content): """Parse the XML data currently stored in the file. Args: file_content: a string containing the action XML file content. Returns: (actions_dict, comment_nodes, suffixes): - actions_dict is a dict from user action name to Action object. - comment_nodes is a list of top-level comment nodes. - suffixes is a list of <action-suffix> DOM elements. """ dom = minidom.parseString(file_content) comment_nodes = [] # Get top-level comments. It is assumed that all comments are placed before # <actions> tag. Therefore the loop will stop if it encounters a non-comment # node. for node in dom.childNodes: if node.nodeType == minidom.Node.COMMENT_NODE: comment_nodes.append(node) else: break actions_dict = {} # Get each user action data. for action_dom in dom.getElementsByTagName('action'): action_name = action_dom.getAttribute('name') not_user_triggered = bool(action_dom.getAttribute('not_user_triggered')) owners = _ExtractText(action_dom, 'owner') # There is only one description for each user action. Get the first element # of the returned list. description_list = _ExtractText(action_dom, 'description') if len(description_list) > 1: logging.error('User action "%s" has more than one description. Exactly ' 'one description is needed for each user action. Please ' 'fix.', action_name) sys.exit(1) description = description_list[0] if description_list else None # There is at most one obsolete tag for each user action. obsolete_list = _ExtractText(action_dom, 'obsolete') if len(obsolete_list) > 1: logging.error('User action "%s" has more than one obsolete tag. At most ' 'one obsolete tag can be added for each user action. Please' ' fix.', action_name) sys.exit(1) obsolete = obsolete_list[0] if obsolete_list else None actions_dict[action_name] = action_utils.Action(action_name, description, owners, not_user_triggered, obsolete) suffixes = dom.getElementsByTagName('action-suffix') action_utils.CreateActionsFromSuffixes(actions_dict, suffixes) return actions_dict, comment_nodes, suffixes def _CreateActionTag(doc, action): """Create a new action tag. Format of an action tag: <action name="name" not_user_triggered="true"> <obsolete>Deprecated.</obsolete> <owner>Owner</owner> <description>Description.</description> </action> not_user_triggered is an optional attribute. If set, it implies that the belonging action is not a user action. A user action is an action that is logged exactly once right after a user has made an action. <obsolete> is an optional tag. It's added to actions that are no longer used any more. If action_name is in actions_dict, the values to be inserted are based on the corresponding Action object. If action_name is not in actions_dict, the default value from TAGS is used. Args: doc: The document under which the new action tag is created. action: An Action object representing the data to be inserted. Returns: An action tag Element with proper children elements, or None if a tag should not be created for this action (e.g. if it comes from a suffix). """ if action.from_suffix: return None action_dom = doc.createElement('action') action_dom.setAttribute('name', action.name) # Add not_user_triggered attribute. if action.not_user_triggered: action_dom.setAttribute('not_user_triggered', 'true') # Create obsolete tag. if action.obsolete: obsolete_dom = doc.createElement('obsolete') action_dom.appendChild(obsolete_dom) obsolete_dom.appendChild(doc.createTextNode(action.obsolete)) # Create owner tag. if action.owners: # If owners for this action is not None, use the stored value. Otherwise, # use the default value. for owner in action.owners: owner_dom = doc.createElement('owner') owner_dom.appendChild(doc.createTextNode(owner)) action_dom.appendChild(owner_dom) else: # Use default value. owner_dom = doc.createElement('owner') owner_dom.appendChild(doc.createTextNode(TAGS.get('owner', ''))) action_dom.appendChild(owner_dom) # Create description tag. description_dom = doc.createElement('description') action_dom.appendChild(description_dom) if action.description: # If description for this action is not None, use the store value. # Otherwise, use the default value. description_dom.appendChild(doc.createTextNode(action.description)) else: description_dom.appendChild(doc.createTextNode( TAGS.get('description', ''))) return action_dom def PrettyPrint(actions_dict, comment_nodes, suffixes): """Given a list of actions, create a well-printed minidom document. Args: actions_dict: A mappting from action name to Action object. comment_nodes: A list of top-level comment nodes. suffixes: A list of <action-suffix> tags to be appended as-is. Returns: A well-printed minidom document that represents the input action data. """ doc = minidom.Document() # Attach top-level comments. for node in comment_nodes: doc.appendChild(node) actions_element = doc.createElement('actions') doc.appendChild(actions_element) # Attach action node based on updated |actions_dict|. for _, action in sorted(actions_dict.items()): action_tag = _CreateActionTag(doc, action) if action_tag: actions_element.appendChild(action_tag) for suffix_tag in suffixes: actions_element.appendChild(suffix_tag) return actions_model.PrettifyTree(doc) def UpdateXml(original_xml): actions_dict, comment_nodes, suffixes = ParseActionFile(original_xml) actions = set() AddComputedActions(actions) AddWebUIActions(actions) AddDevToolsActions(actions) AddLiteralActions(actions) AddAutomaticResetBannerActions(actions) AddBookmarkManagerActions(actions) AddChromeOSActions(actions) AddExtensionActions(actions) AddHistoryPageActions(actions) AddPDFPluginActions(actions) for action_name in actions: if action_name not in actions_dict: actions_dict[action_name] = action_utils.Action(action_name, None, []) return PrettyPrint(actions_dict, comment_nodes, suffixes) def main(argv): presubmit_util.DoPresubmitMain( argv, 'actions.xml', 'actions.old.xml', UpdateXml, script_name='extract_actions.py') if '__main__' == __name__: sys.exit(main(sys.argv))
37.591912
80
0.695485
302eeff0c32a51ff3b5056053c74952623c31ef1
4,216
py
Python
bin/newmap.py
sympolite/very-small-roguelike
cd3635cfe0db65a1df69fa5c1b72a4f794444449
[ "MIT" ]
1
2021-04-06T04:32:49.000Z
2021-04-06T04:32:49.000Z
bin/newmap.py
sympolite/very-small-roguelike
cd3635cfe0db65a1df69fa5c1b72a4f794444449
[ "MIT" ]
null
null
null
bin/newmap.py
sympolite/very-small-roguelike
cd3635cfe0db65a1df69fa5c1b72a4f794444449
[ "MIT" ]
1
2021-04-06T04:32:52.000Z
2021-04-06T04:32:52.000Z
import tdl import sys palettes = {'grey': ((45, 45, 45), (0, 0, 0), (180, 180, 180), (90, 90, 90))} MAXWIDTH = 9 MAXHEIGHT = 9 MINWIDTH = 3 MINHEIGHT = 3 FOV_ALGO = 'BASIC' FOV_LIGHT_WALLS = True class Tile: # a tile of the map and its properties def __init__(self, blocked, block_sight=None): self.blocked = blocked self.explored = False # by default, if a tile is blocked, it also blocks sight if block_sight is None: block_sight = blocked self.block_sight = block_sight class GameMap: def __init__(self, map_id, con): self.map_id = str(map_id) self.con = con self.palette = palettes['grey'] self.width, self.height = 0 self.tilemap = [] self.tilemap = [[]] self.load_tilemap() self.create_tilemap() def in_map_bounds(self, x, y): if 0 < x < self.width-1 and 0 < y < self.height-1: return True return False def load_tilemap(self): width = 0 height = 0 map_data = [] try: with open('maps/'+self.map_id+'.map') as map_file: for counter, line in enumerate(map_file): if 0 < len(line) <= MAXWIDTH and height <= MAXHEIGHT: map_data.append(line) self.height += 1 if counter == 0: self.width = len(line) elif len(line) != self.width: raise ValueError else: pass else: raise ValueError for datum in map_data: for char in datum: if char != "-" or char != "#": raise ValueError self.create_tilemap(map_data) except IOError: print("ERROR - .map file not found") sys.exit(1) except ValueError: print("ERROR - Invalid map data") sys.exit(1) def create_tilemap(self, mapdata): for i, row in enumerate(mapdata): for j, column in enumerate(mapdata[i]): if column == '-': self.tilemap[j][i] = Tile(False) elif column == '#': self.tilemap[j][i] = Tile(True) else: pass def is_visible_tile(self, x, y): if self.in_map_bounds(x, y): if self.tilemap[x][y].blocked: return False elif self.tilemap[x][y].block_sight: return False else: return True else: return False def draw(self, player): visible_tiles = tdl.map.quick_fov(player.x, player.y, self.is_visible_tile, fov=FOV_ALGO, radius=player.sight, lightWalls=False) for y in range(self.height): for x in range(self.width): #self.compute_fov(player) visible = (x, y) in visible_tiles wall = self.tilemap[x][y].block_sight if not visible: if self.tilemap[x][y].explored: if wall: self.con.draw_char(x, y, None, fg=None, bg=self.palette[1]) else: self.con.draw_char(x, y, None, fg=None, bg=self.palette[0]) else: if wall: self.con.draw_char(x, y, None, fg=None, bg=self.palette[3]) else: self.con.draw_char(x, y, None, fg=None, bg=self.palette[2]) self.tilemap[x][y].explored = True def clear(self): for y in range(self.height): for x in range(self.width): self.con.draw_char(x, y, ' ', fg=(0, 0, 0), bg=(0, 0, 0))
35.133333
88
0.446869
0fcf489f14e3b09b56d79865aa01194f384a99c3
160
py
Python
tests/python/test_browser.py
mdp/rpaframework
d427a3a4b9ea360780e449ece2674e275060310e
[ "Apache-2.0" ]
2
2021-04-17T17:24:20.000Z
2021-04-18T18:09:54.000Z
packages/main/tests/python/test_browser.py
aikarjal/rpaframework
cd0599b33b7fcca3d43ea45116a43fc7507b73c9
[ "Apache-2.0" ]
null
null
null
packages/main/tests/python/test_browser.py
aikarjal/rpaframework
cd0599b33b7fcca3d43ea45116a43fc7507b73c9
[ "Apache-2.0" ]
1
2021-02-11T21:00:11.000Z
2021-02-11T21:00:11.000Z
from unittest import TestCase class TestBrowserFunctionality(TestCase): def test_import(self): from RPA.Browser import Browser Browser()
17.777778
41
0.71875
47ae17fb1c7800cad28eaf9509185c35ad8ebeb8
6,842
py
Python
tests/test_dynamicbatching.py
terrorizer1980/ParlAI
f8fda24bd11804104b0a91aa84e170d3efbd8983
[ "MIT" ]
2
2020-08-27T05:21:14.000Z
2020-09-29T14:34:09.000Z
tests/test_dynamicbatching.py
terrorizer1980/ParlAI
f8fda24bd11804104b0a91aa84e170d3efbd8983
[ "MIT" ]
316
2021-03-19T14:53:31.000Z
2022-03-27T03:36:51.000Z
tests/test_dynamicbatching.py
terrorizer1980/ParlAI
f8fda24bd11804104b0a91aa84e170d3efbd8983
[ "MIT" ]
2
2020-10-29T18:14:33.000Z
2020-11-07T09:46:23.000Z
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from parlai.core.opt import Opt from parlai.tasks.integration_tests.agents import NUM_TEST, EXAMPLE_SIZE from parlai.utils.conversations import Conversations import parlai.utils.testing as testing_utils import os from typing import Dict, Any import unittest _TASK = 'integration_tests:variable_length' # we don't need a real agent, since we're only checking the number examples # is correct _DEFAULT_OPTIONS = { 'dict_file': 'zoo:unittest/transformer_generator2/model.dict', 'dict_tokenizer': 'space', 'batchsize': 16, 'dynamic_batching': 'full', 'num_epochs': 1, 'truncate': 8, 'model': 'parlai.agents.test_agents.test_agents:SilentTorchAgent', 'task': _TASK, } _RANKER_OPTIONS = { 'dict_file': 'zoo:unittest/transformer_generator2/model.dict', 'dict_tokenizer': 'space', 'batchsize': 32, 'num_epochs': 0.1, 'n_layers': 1, 'n_heads': 1, 'candidates': 'batch', 'ffn_size': 4, 'embedding_size': 4, 'task': _TASK, 'truncate': 8, 'model': 'transformer/ranker', } # TODO tests to write: # - multiple validation runs, streaming/not streaming # - ranking model class TestDynamicBatching(unittest.TestCase): def _test_correct_processed(self, num_goal: int, **kwargs: Dict[str, Any]): opt = Opt({**_DEFAULT_OPTIONS, **kwargs}) valid_report, test_report = testing_utils.train_model(opt) self.assertEqual(valid_report['exs'], num_goal) self.assertEqual(test_report['exs'], num_goal) def test_no_truncate(self): with self.assertRaises(ValueError): testing_utils.train_model(Opt({**_DEFAULT_OPTIONS, **{'truncate': -1}})) def test_no_batch_act(self): """ Fail when the agent doesn't support dynamic batching. """ with self.assertRaises(TypeError): testing_utils.train_model(model='repeat_label', task=_TASK) with self.assertRaises(TypeError): testing_utils.eval_model(model='repeat_label', task=_TASK) def test_ranking(self): testing_utils.train_model( Opt(datatype='train', dynamic_batching='full', **_RANKER_OPTIONS) ) def test_ranking_streaming(self): testing_utils.train_model( Opt(datatype='train:stream', dynamic_batching='full', **_RANKER_OPTIONS) ) def test_training(self): self._test_correct_processed(NUM_TEST, datatype='train') def test_streaming(self): self._test_correct_processed(NUM_TEST, datatype='train:stream') def test_multiworld(self): self._test_correct_processed( NUM_TEST + NUM_TEST * EXAMPLE_SIZE, task='integration_tests:variable_length,integration_tests:multiturn', ) def test_multiworld_stream(self): self._test_correct_processed( NUM_TEST + NUM_TEST * EXAMPLE_SIZE, task='integration_tests:variable_length,integration_tests:multiturn', datatype='train:stream', ) def test_world_logging(self): with testing_utils.tempdir() as tmpdir: save_report = os.path.join(tmpdir, 'report') testing_utils.eval_model( dict( model_file='zoo:unittest/transformer_generator2/model', task='integration_tests:multiturn_candidate', save_world_logs=True, report_filename=save_report, truncate=1024, dynamic_batching='full', batchsize=4, ) ) convo_fle = ( str(save_report) + '_integration_tests:multiturn_candidate_replies.jsonl' ) convos = Conversations(convo_fle) for convo in convos: self.assertEquals(len(convo), 2 * 4) # each episode is 4 turns # now assert that they are all from the same dynamic batch index dyn_batch_idx = convo[0]['dyn_batch_idx'] for i, turn in enumerate(convo): if i % 2 == 0 and i > 0: # we log the batch index in the teacher acts only self.assertEquals(dyn_batch_idx, turn['dyn_batch_idx']) def test_weird_batchsize(self): # intentionally a difficult number self._test_correct_processed(NUM_TEST, batchsize=7) def test_batchsize4(self): # intentionally an edgecase in the world self._test_correct_processed(NUM_TEST, batchsize=4) class TestBatchSort(unittest.TestCase): def _test_correct_processed(self, num_goal: int, **kwargs: Dict[str, Any]): opt = Opt({**_DEFAULT_OPTIONS, **kwargs}) opt['dynamic_batching'] = 'batchsort' valid_report, test_report = testing_utils.train_model(opt) self.assertEqual(valid_report['exs'], num_goal) self.assertEqual(test_report['exs'], num_goal) def test_no_batch_act(self): """ Fail when the agent doesn't support dynamic batching. """ with self.assertRaises(TypeError): testing_utils.train_model(model='repeat_label', task=_TASK) with self.assertRaises(TypeError): testing_utils.eval_model(model='repeat_label', task=_TASK) def test_ranking(self): testing_utils.train_model( Opt(datatype='train', dynamic_batching='batchsort', **_RANKER_OPTIONS) ) def test_ranking_streaming(self): testing_utils.train_model( Opt( datatype='train:stream', dynamic_batching='batchsort', **_RANKER_OPTIONS ) ) def test_training(self): self._test_correct_processed(NUM_TEST, datatype='train') def test_streaming(self): self._test_correct_processed(NUM_TEST, datatype='train:stream') def test_multiworld(self): self._test_correct_processed( NUM_TEST + NUM_TEST * EXAMPLE_SIZE, task='integration_tests:variable_length,integration_tests:multiturn', ) def test_multiworld_stream(self): self._test_correct_processed( NUM_TEST + NUM_TEST * EXAMPLE_SIZE, task='integration_tests:variable_length,integration_tests:multiturn', datatype='train:stream', ) def test_weird_batchsize(self): # intentionally a difficult number self._test_correct_processed(NUM_TEST, batchsize=7) def test_batchsize4(self): # intentionally an edgecase in the world self._test_correct_processed(NUM_TEST, batchsize=4) if __name__ == '__main__': unittest.main()
34.38191
88
0.647033
1333ec44fb48dc1afc96258d5fd14bb02e79d81d
566
py
Python
checkout/migrations/0005_order_user_profile.py
vladoprea/dream-woollies
7113400a03e4047312b88a3afff7e5969ff96f6b
[ "W3C", "PostgreSQL" ]
null
null
null
checkout/migrations/0005_order_user_profile.py
vladoprea/dream-woollies
7113400a03e4047312b88a3afff7e5969ff96f6b
[ "W3C", "PostgreSQL" ]
5
2021-06-04T23:31:01.000Z
2021-09-22T19:18:34.000Z
checkout/migrations/0005_order_user_profile.py
vladoprea/dream-woollies
7113400a03e4047312b88a3afff7e5969ff96f6b
[ "W3C", "PostgreSQL" ]
1
2020-08-17T14:27:29.000Z
2020-08-17T14:27:29.000Z
# Generated by Django 3.0.7 on 2020-07-23 12:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('profiles', '0001_initial'), ('checkout', '0004_auto_20200723_1235'), ] operations = [ migrations.AddField( model_name='order', name='user_profile', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='orders', to='profiles.UserProfile'), ), ]
26.952381
155
0.64841
596a942c40345e424ffbf90e7ddd80001482fddd
7,337
py
Python
pysnmp/EQLTAG-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
11
2021-02-02T16:27:16.000Z
2021-08-31T06:22:49.000Z
pysnmp/EQLTAG-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
75
2021-02-24T17:30:31.000Z
2021-12-08T00:01:18.000Z
pysnmp/EQLTAG-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module EQLTAG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EQLTAG-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:51:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion") eqlGroupId, eqlStorageGroupAdminAccountIndex, UTFString = mibBuilder.importSymbols("EQLGROUP-MIB", "eqlGroupId", "eqlStorageGroupAdminAccountIndex", "UTFString") eqliscsiLocalMemberId, eqliscsiVolumeIndex = mibBuilder.importSymbols("EQLVOLUME-MIB", "eqliscsiLocalMemberId", "eqliscsiVolumeIndex") equalLogic, = mibBuilder.importSymbols("EQUALLOGIC-SMI", "equalLogic") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") enterprises, NotificationType, Bits, MibIdentifier, Counter64, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, ModuleIdentity, Counter32, TimeTicks, ObjectIdentity, IpAddress, Integer32, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "NotificationType", "Bits", "MibIdentifier", "Counter64", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "ModuleIdentity", "Counter32", "TimeTicks", "ObjectIdentity", "IpAddress", "Integer32", "Unsigned32") TextualConvention, DisplayString, TruthValue, RowPointer, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "TruthValue", "RowPointer", "RowStatus") eqltagModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 12740, 23)) eqltagModule.setRevisions(('2011-10-02 00:00',)) if mibBuilder.loadTexts: eqltagModule.setLastUpdated('201403121459Z') if mibBuilder.loadTexts: eqltagModule.setOrganization('EqualLogic Inc.') eqltagObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 12740, 23, 1)) eqltagNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 12740, 23, 2)) eqltagConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 12740, 23, 3)) eqlTagTable = MibTable((1, 3, 6, 1, 4, 1, 12740, 23, 1, 1), ) if mibBuilder.loadTexts: eqlTagTable.setStatus('current') eqlTagEntry = MibTableRow((1, 3, 6, 1, 4, 1, 12740, 23, 1, 1, 1), ).setIndexNames((0, "EQLTAG-MIB", "eqlTagType"), (0, "EQLTAG-MIB", "eqlTagIndex")) if mibBuilder.loadTexts: eqlTagEntry.setStatus('current') eqlTagType = MibTableColumn((1, 3, 6, 1, 4, 1, 12740, 23, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("folder", 1))).clone(1)) if mibBuilder.loadTexts: eqlTagType.setStatus('current') eqlTagIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 12740, 23, 1, 1, 1, 2), Unsigned32()) if mibBuilder.loadTexts: eqlTagIndex.setStatus('current') eqlTagRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 12740, 23, 1, 1, 1, 3), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: eqlTagRowStatus.setStatus('current') eqlTagValue = MibTableColumn((1, 3, 6, 1, 4, 1, 12740, 23, 1, 1, 1, 4), UTFString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite") if mibBuilder.loadTexts: eqlTagValue.setStatus('current') eqlTagAdminAccountKey = MibTableColumn((1, 3, 6, 1, 4, 1, 12740, 23, 1, 1, 1, 5), Unsigned32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: eqlTagAdminAccountKey.setStatus('current') eqlTagValueDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 12740, 23, 1, 1, 1, 6), UTFString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite") if mibBuilder.loadTexts: eqlTagValueDescription.setStatus('current') eqlTagObjectTable = MibTable((1, 3, 6, 1, 4, 1, 12740, 23, 1, 2), ) if mibBuilder.loadTexts: eqlTagObjectTable.setStatus('current') eqlTagObjectEntry = MibTableRow((1, 3, 6, 1, 4, 1, 12740, 23, 1, 2, 1), ).setIndexNames((0, "EQLTAG-MIB", "eqlTagType"), (0, "EQLTAG-MIB", "eqlTagIndex"), (0, "EQLTAG-MIB", "eqlTagObjectIndex")) if mibBuilder.loadTexts: eqlTagObjectEntry.setStatus('current') eqlTagObjectIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 12740, 23, 1, 2, 1, 1), Unsigned32()) if mibBuilder.loadTexts: eqlTagObjectIndex.setStatus('current') eqlTagObjectTaggedObjectPointer = MibTableColumn((1, 3, 6, 1, 4, 1, 12740, 23, 1, 2, 1, 2), RowPointer()).setMaxAccess("readwrite") if mibBuilder.loadTexts: eqlTagObjectTaggedObjectPointer.setStatus('current') eqlTagObjectRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 12740, 23, 1, 2, 1, 3), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: eqlTagObjectRowStatus.setStatus('current') eqlAdminAccountTagTable = MibTable((1, 3, 6, 1, 4, 1, 12740, 23, 1, 3), ) if mibBuilder.loadTexts: eqlAdminAccountTagTable.setStatus('current') eqlAdminAccountTagEntry = MibTableRow((1, 3, 6, 1, 4, 1, 12740, 23, 1, 3, 1), ).setIndexNames((0, "EQLGROUP-MIB", "eqlGroupId"), (0, "EQLGROUP-MIB", "eqlStorageGroupAdminAccountIndex"), (0, "EQLTAG-MIB", "eqlTagType"), (0, "EQLTAG-MIB", "eqlTagIndex")) if mibBuilder.loadTexts: eqlAdminAccountTagEntry.setStatus('current') eqlAdminAccountTagAccess = MibTableColumn((1, 3, 6, 1, 4, 1, 12740, 23, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("read-only", 1), ("read-write", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: eqlAdminAccountTagAccess.setStatus('current') eqlVolumeTagTable = MibTable((1, 3, 6, 1, 4, 1, 12740, 23, 1, 4), ) if mibBuilder.loadTexts: eqlVolumeTagTable.setStatus('current') eqlVolumeTagEntry = MibTableRow((1, 3, 6, 1, 4, 1, 12740, 23, 1, 4, 1), ).setIndexNames((0, "EQLVOLUME-MIB", "eqliscsiLocalMemberId"), (0, "EQLVOLUME-MIB", "eqliscsiVolumeIndex"), (0, "EQLTAG-MIB", "eqlTagType"), (0, "EQLTAG-MIB", "eqlTagIndex")) if mibBuilder.loadTexts: eqlVolumeTagEntry.setStatus('current') eqlVolumeTagValue = MibTableColumn((1, 3, 6, 1, 4, 1, 12740, 23, 1, 4, 1, 1), UTFString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite") if mibBuilder.loadTexts: eqlVolumeTagValue.setStatus('current') mibBuilder.exportSymbols("EQLTAG-MIB", eqlAdminAccountTagEntry=eqlAdminAccountTagEntry, eqlTagObjectIndex=eqlTagObjectIndex, eqlVolumeTagTable=eqlVolumeTagTable, eqlTagValueDescription=eqlTagValueDescription, eqlTagTable=eqlTagTable, eqltagModule=eqltagModule, eqlTagIndex=eqlTagIndex, eqltagConformance=eqltagConformance, eqlVolumeTagValue=eqlVolumeTagValue, eqlAdminAccountTagTable=eqlAdminAccountTagTable, eqlTagValue=eqlTagValue, eqlVolumeTagEntry=eqlVolumeTagEntry, eqlTagType=eqlTagType, eqlAdminAccountTagAccess=eqlAdminAccountTagAccess, eqlTagObjectEntry=eqlTagObjectEntry, eqlTagObjectTaggedObjectPointer=eqlTagObjectTaggedObjectPointer, eqlTagObjectRowStatus=eqlTagObjectRowStatus, eqltagObjects=eqltagObjects, PYSNMP_MODULE_ID=eqltagModule, eqltagNotifications=eqltagNotifications, eqlTagAdminAccountKey=eqlTagAdminAccountKey, eqlTagObjectTable=eqlTagObjectTable, eqlTagEntry=eqlTagEntry, eqlTagRowStatus=eqlTagRowStatus)
116.460317
932
0.76857
e942c0deab528bd045371e99c9201111017a2648
1,857
py
Python
Django/api-basic2/photo/views.py
sug5806/TIL
2309d8a270e4a7b8961268a40b6492c5db317e37
[ "MIT" ]
null
null
null
Django/api-basic2/photo/views.py
sug5806/TIL
2309d8a270e4a7b8961268a40b6492c5db317e37
[ "MIT" ]
102
2020-02-12T00:10:33.000Z
2022-03-11T23:58:41.000Z
Django/api-basic2/photo/views.py
sug5806/TIL
2309d8a270e4a7b8961268a40b6492c5db317e37
[ "MIT" ]
null
null
null
from django.views.generic import ListView, CreateView, DetailView, UpdateView, DeleteView from rest_framework import generics from django.http import HttpResponse from .models import Photo from .serializers import * # Create your views here. def index(request): return HttpResponse('index') class PhotoList(ListView): model = Photo template_name = 'photo/photo_list.html' class PhotoCreate(CreateView): model = Photo template_name = 'photo/photo_create.html' fields = ['image', 'text'] def form_valid(self, form): if self.request.user.id: form.instance.author_id = self.request.user.id return super().form_valid(form) else: return False # get_absolute_url 이 있으므로 생략 가능 # success_url = '/' class PhotoDetail(DetailView): model = Photo template_name = 'photo/photo_detail.html' class PhotoUpdate(UpdateView): model = Photo fields = ['image', 'text'] template_name = 'photo/photo_update.html' class PhotoDelete(DeleteView): model = Photo template_name = 'photo/photo_delete.html' ###################################################### class PhotoListAPI(generics.ListAPIView): queryset = Photo.objects.all() serializer_class = PhotoListSerializer class PhotoCreateAPI(generics.CreateAPIView): serializer_class = PhotoCreateSerializer class PhotoDetailAPI(generics.RetrieveAPIView): queryset = Photo.objects.all() serializer_class = PhotoDetailSerializer class PhotoUpdateAPI(generics.UpdateAPIView): queryset = Photo.objects.all() serializer_class = PhotoUpdateSerializer class photoDeleteAPI(generics.DestroyAPIView): queryset = Photo.objects.all() # 토큰 인증 기능 추가, 기본 인증, 권한 클래스 # 1) 인증된 사용자만 API를 사용할 수 있도록 설정 : token 인증 # 2) 특정 동작에 대해 특정 권한을 득한 사용자만 사용할 수 있도록 설정 : permission클래스 추가
23.506329
89
0.695746
77ce043ae32f18025f1a4130286956c126ed8131
3,026
py
Python
util/DFA.py
MartrixG/comlier
a29a9201478d59da6786bbe1cd6760cd3bb481a9
[ "MIT" ]
null
null
null
util/DFA.py
MartrixG/comlier
a29a9201478d59da6786bbe1cd6760cd3bb481a9
[ "MIT" ]
null
null
null
util/DFA.py
MartrixG/comlier
a29a9201478d59da6786bbe1cd6760cd3bb481a9
[ "MIT" ]
null
null
null
import string class DFA(object): def __init__(self, data): self.name = data['name'][0] self.Q = data['Q'][0].split(' ') self.sigma = data['sigma'][0].split(' ') self.q0 = data['q0'][0] species = data['F'][0].split(' ') self.F = {} self.error = {} for spec in species: tmp = spec.split(",") if tmp[0] == 'comma': tmp[0] = tmp[1] = ',' self.F[tmp[0]] = tmp[1] tmp = "" for item in data['t']: tmp += item t = {} for item in tmp.split(' '): key, value = item.split(',') key = [key] if key[0] == 'digit': key = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] if key[0] == 'letter': key = [i for i in string.ascii_letters] if key[0] == 'comma': key = [','] value = value[0] + ',' for each_key in key: t[value[0] + each_key] = value[1] for error in data['error'][0].split(';'): state, statement = error.split(':') self.error[state] = statement self.t = t def scan(self, src_code): re = '' now_state = self.q0 now_ch = src_code.get_now() while True: if self.t.get(now_state + now_ch, None) is not None: now_state = self.t.get(now_state + now_ch) elif self.t.get(now_state + 'exc*', None) is not None and now_ch != '*': now_state = self.t.get(now_state + 'exc*') elif now_state in self.F.keys(): return re, self.F.get(now_state), src_code.line else: while src_code.has_next(): if src_code.get_now() not in (string.ascii_letters, '_', string.digits): break re += src_code.get_next() return -1, self.error[now_state] + "at " + src_code.get_pos(len(re)) + ".", src_code.line re += now_ch now_ch = src_code.get_next() def get_list(self): re = [] line = ["s\\Q"] for s in self.Q: line.append(s) re.append(line) for s in self.sigma: line = [s] for to in self.Q: tmp = to + s if self.t.get(tmp, None) is None: line.append('err') else: line.append(self.t.get(tmp)) re.append(line) return re def __repr__(self): re = self.name + ":\n" + "s\\Q\t" for s in self.Q: re += s + '\t' re += '\n' for s in self.sigma: re += s + '\t' for to in self.Q: tmp = to + s if self.t.get(tmp, None) is None: re += 'err\t' else: re += self.t.get(tmp) + '\t' re += '\n' return re
33.252747
105
0.41573
61fb23047037ee307ef4070a9eed543209d7b75d
947
py
Python
src/utils/snapshot.py
TUM-LMF/MTLCC-pytorch
894a470be2fb4b9e2e0b9e20e8684131ffdb5577
[ "MIT" ]
39
2018-08-27T11:33:28.000Z
2021-12-13T11:17:31.000Z
src/utils/snapshot.py
TUM-LMF/MTLCC-pytorch
894a470be2fb4b9e2e0b9e20e8684131ffdb5577
[ "MIT" ]
2
2019-02-16T11:40:54.000Z
2020-04-23T08:01:53.000Z
src/utils/snapshot.py
TUM-LMF/MTLCC-pytorch
894a470be2fb4b9e2e0b9e20e8684131ffdb5577
[ "MIT" ]
16
2018-08-29T02:03:31.000Z
2022-03-12T09:41:06.000Z
import torch def save(path, model, optimizer, **kwargs): model_state = None optimizer_state = None if model is not None: model_state = model.state_dict() if optimizer is not None: optimizer_state = optimizer.state_dict() torch.save( dict(model_state=model_state, optimizer_state=optimizer_state, **kwargs), path ) def resume(path, model, optimizer): if torch.cuda.is_available(): snapshot = torch.load(path) else: snapshot = torch.load(path, map_location="cpu") model_state = snapshot.pop('model_state', snapshot) optimizer_state = snapshot.pop('optimizer_state', None) if model is not None and model_state is not None: print("load model") model.load_state_dict(model_state) if optimizer is not None and optimizer_state is not None: optimizer.load_state_dict(optimizer_state) return snapshot
28.69697
61
0.663147
7f590493906211f152f3834baf12c64bd1f02b6d
1,986
py
Python
python/caffe2_benchmarks/models/deep_mnist.py
joehandzik/dlcookbook-dlbs
7c5ca5a6dfa4e2f7b8b4d81c60bd8be343dabd30
[ "Apache-2.0" ]
123
2017-11-28T20:21:24.000Z
2022-03-22T11:21:04.000Z
python/caffe2_benchmarks/models/deep_mnist.py
joehandzik/dlcookbook-dlbs
7c5ca5a6dfa4e2f7b8b4d81c60bd8be343dabd30
[ "Apache-2.0" ]
17
2018-01-05T00:05:13.000Z
2020-09-18T05:12:45.000Z
python/caffe2_benchmarks/models/deep_mnist.py
joehandzik/dlcookbook-dlbs
7c5ca5a6dfa4e2f7b8b4d81c60bd8be343dabd30
[ "Apache-2.0" ]
48
2018-01-04T20:52:51.000Z
2022-03-06T00:47:17.000Z
# (c) Copyright [2017] Hewlett Packard Enterprise Development LP # # 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. """ https://caffe2.ai/docs/SynchronousSGD.html """ from __future__ import absolute_import from caffe2.python import brew from caffe2_benchmarks.models.model import Model class DeepMNIST(Model): """A somewhat deep FCNN.""" implements = 'deep_mnist' def __init__(self, params): Model.check_parameters( params, {'name': 'DeepMNIST', 'input_shape':(784), 'num_classes': 10, 'arg_scope': {'order': 'NCHW'}} ) Model.__init__(self, params) def forward_pass_builder(self, model, loss_scale=1.0): """ This function adds the operators, layers to the network. It should return a list of loss-blobs that are used for computing the loss gradient. This function is also passed an internally calculated loss_scale parameter that is used to scale your loss to normalize for the number of GPUs. Signature: function(model, loss_scale) """ v = 'data' dim_in = self.input_shape[0] for idx, dim_out in enumerate([2500, 2000, 1500, 1000, 500]): v = brew.fc(model, v, 'fc%d' % (idx+1), dim_in=dim_in, dim_out=dim_out) v = brew.relu(model, v, 'relu%d' % (idx+1)) dim_in = dim_out return self.add_head_nodes(model, v, dim_in, 'fc%d' % (idx+2), loss_scale=loss_scale)
39.72
93
0.662638
2427b69bec93ef3bc82d3ad46daa19f43e0c4d1a
2,674
py
Python
cptm/utils/inputgeneration.py
egpbos/cptm
c5f310858c341040b4afd166cf628aeee6845159
[ "Apache-2.0" ]
13
2016-03-14T14:58:04.000Z
2020-11-03T22:48:59.000Z
cptm/utils/inputgeneration.py
egpbos/cptm
c5f310858c341040b4afd166cf628aeee6845159
[ "Apache-2.0" ]
5
2015-10-30T12:34:16.000Z
2017-10-27T04:55:07.000Z
cptm/utils/inputgeneration.py
egpbos/cptm
c5f310858c341040b4afd166cf628aeee6845159
[ "Apache-2.0" ]
3
2016-03-03T10:49:05.000Z
2018-02-03T14:36:59.000Z
"""Helpers to generate input data for cross-perspective topic modeling.""" import os import logging import codecs import re logger = logging.getLogger('inputgeneration') class Perspective(): def __init__(self, name, posTopic, posOpinion): """Initialize inputgeneration Perspective. Parameters: name : str The perspective name. Used as directory name to store the data. posTopic : list of strings List of strings specifying the pos-tags for topic words. posOpinion : list of strings List of strings specifying the pos-tags for opinion words. """ self.name = name self.wordTypes = posTopic + posOpinion self.posTopic = posTopic self.posOpinion = posOpinion self.words = {} for w in self.wordTypes: self.words[w] = [] def __str__(self): len_topic_words, len_opinion_words = self.word_lengths() return 'Perspective: {} - {} topic words; {} opinion words'.format( self.name, len_topic_words, len_opinion_words) def add(self, tag, word): self.words[tag].append(word) def write2file(self, out_dir, file_name): # create dir (if not exists) directory = os.path.join(out_dir, self.name) if not os.path.exists(directory): os.makedirs(directory) # write words to file out_file = os.path.join(directory, file_name) logger.debug('Writing file {} for perspective {}'.format(out_file, self.name)) with codecs.open(out_file, 'wb', 'utf8') as f: for w in self.wordTypes: f.write(u'{}\n'.format(' '.join(self.words[w]))) def word_lengths(self): len_topic_words = sum([len(self.words[w]) for w in self.posTopic]) len_opinion_words = sum([len(self.words[w]) for w in self.posOpinion]) return len_topic_words, len_opinion_words def remove_trailing_digits(word): """Convert words like d66 to d. In the folia files from politicalmashup, words such as d66 have been extracted as two words (d and 66) and only d ended up in the data input files. The folia files were probably created with an old version of frog, because currenly, words like these are parsed correctly. This function can be used when parsing and lemmatizing new text to match the vocabulary used in the old folia files. """ regex = re.compile('^(.+?)(\d+)$', flags=re.UNICODE) m = regex.match(word) if m: return m.group(1) return word
34.727273
79
0.618175
feaad7b597b6126d98a8c190505671c0aa793dba
78,865
py
Python
tests/core/consensus/test_blockchain.py
kd637xx/chia-blockchain
b82f3ba8a2953de12bddf5c5d6a33e443b51bc8b
[ "Apache-2.0" ]
null
null
null
tests/core/consensus/test_blockchain.py
kd637xx/chia-blockchain
b82f3ba8a2953de12bddf5c5d6a33e443b51bc8b
[ "Apache-2.0" ]
null
null
null
tests/core/consensus/test_blockchain.py
kd637xx/chia-blockchain
b82f3ba8a2953de12bddf5c5d6a33e443b51bc8b
[ "Apache-2.0" ]
null
null
null
# flake8: noqa: F811, F401 import asyncio import multiprocessing import time from dataclasses import replace import logging import pytest from blspy import AugSchemeMPL, G2Element from src.consensus.blockchain import ReceiveBlockResult from src.types.classgroup import ClassgroupElement from src.types.end_of_slot_bundle import EndOfSubSlotBundle from src.types.full_block import FullBlock from src.types.slots import InfusedChallengeChainSubSlot from src.types.unfinished_block import UnfinishedBlock from src.types.vdf import VDFInfo, VDFProof from src.util.block_tools import get_vdf_info_and_proof from src.util.errors import Err from src.util.hash import std_hash from src.util.ints import uint64, uint8, int512 from src.util.wallet_tools import WalletTool from tests.recursive_replace import recursive_replace from tests.setup_nodes import test_constants, bt from tests.core.fixtures import empty_blockchain # noqa: F401 from tests.core.fixtures import default_1000_blocks # noqa: F401 from tests.core.fixtures import default_400_blocks # noqa: F401 from tests.core.fixtures import default_10000_blocks # noqa: F401 log = logging.getLogger(__name__) @pytest.fixture(scope="module") def event_loop(): loop = asyncio.get_event_loop() yield loop class TestGenesisBlock: @pytest.mark.asyncio async def test_block_tools_proofs_400(self, default_400_blocks): vdf, proof = get_vdf_info_and_proof( test_constants, ClassgroupElement.get_default_element(), test_constants.FIRST_CC_CHALLENGE, uint64(231) ) if proof.is_valid(test_constants, ClassgroupElement.get_default_element(), vdf) is False: raise Exception("invalid proof") @pytest.mark.asyncio async def test_block_tools_proofs_1000(self, default_1000_blocks): vdf, proof = get_vdf_info_and_proof( test_constants, ClassgroupElement.get_default_element(), test_constants.FIRST_CC_CHALLENGE, uint64(231) ) if proof.is_valid(test_constants, ClassgroupElement.get_default_element(), vdf) is False: raise Exception("invalid proof") @pytest.mark.asyncio async def test_block_tools_proofs_10000(self, default_10000_blocks): vdf, proof = get_vdf_info_and_proof( test_constants, ClassgroupElement.get_default_element(), test_constants.FIRST_CC_CHALLENGE, uint64(231) ) if proof.is_valid(test_constants, ClassgroupElement.get_default_element(), vdf) is False: raise Exception("invalid proof") @pytest.mark.asyncio async def test_non_overflow_genesis(self, empty_blockchain): assert empty_blockchain.get_peak() is None genesis = bt.get_consecutive_blocks(1, force_overflow=False)[0] result, err, _ = await empty_blockchain.receive_block(genesis) assert err is None assert result == ReceiveBlockResult.NEW_PEAK assert empty_blockchain.get_peak().sub_block_height == 0 @pytest.mark.asyncio async def test_overflow_genesis(self, empty_blockchain): genesis = bt.get_consecutive_blocks(1, force_overflow=True)[0] result, err, _ = await empty_blockchain.receive_block(genesis) assert err is None assert result == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_genesis_empty_slots(self, empty_blockchain): genesis = bt.get_consecutive_blocks(1, force_overflow=False, skip_slots=3)[0] result, err, _ = await empty_blockchain.receive_block(genesis) assert err is None assert result == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_overflow_genesis_empty_slots(self, empty_blockchain): genesis = bt.get_consecutive_blocks(1, force_overflow=True, skip_slots=3)[0] result, err, _ = await empty_blockchain.receive_block(genesis) assert err is None assert result == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_genesis_validate_1(self, empty_blockchain): genesis = bt.get_consecutive_blocks(1, force_overflow=False)[0] bad_prev = bytes([1] * 32) genesis = recursive_replace(genesis, "foliage_sub_block.prev_sub_block_hash", bad_prev) result, err, _ = await empty_blockchain.receive_block(genesis) assert err == Err.INVALID_PREV_BLOCK_HASH class TestBlockHeaderValidation: @pytest.mark.asyncio async def test_long_chain(self, empty_blockchain, default_1000_blocks): blocks = default_1000_blocks for block in blocks: if ( len(block.finished_sub_slots) > 0 and block.finished_sub_slots[0].challenge_chain.subepoch_summary_hash is not None ): # Sub/Epoch. Try using a bad ssi and difficulty to test 2m and 2n new_finished_ss = recursive_replace( block.finished_sub_slots[0], "challenge_chain.new_sub_slot_iters", uint64(10000000), ) block_bad = recursive_replace( block, "finished_sub_slots", [new_finished_ss] + block.finished_sub_slots[1:] ) result, err, _ = await empty_blockchain.receive_block(block_bad) assert err == Err.INVALID_NEW_SUB_SLOT_ITERS new_finished_ss_2 = recursive_replace( block.finished_sub_slots[0], "challenge_chain.new_difficulty", uint64(10000000), ) block_bad_2 = recursive_replace( block, "finished_sub_slots", [new_finished_ss_2] + block.finished_sub_slots[1:] ) result, err, _ = await empty_blockchain.receive_block(block_bad_2) assert err == Err.INVALID_NEW_DIFFICULTY # 3c new_finished_ss_3: EndOfSubSlotBundle = recursive_replace( block.finished_sub_slots[0], "challenge_chain.subepoch_summary_hash", bytes([0] * 32), ) new_finished_ss_3 = recursive_replace( new_finished_ss_3, "reward_chain.challenge_chain_sub_slot_hash", new_finished_ss_3.challenge_chain.get_hash(), ) block_bad_3 = recursive_replace( block, "finished_sub_slots", [new_finished_ss_3] + block.finished_sub_slots[1:] ) result, err, _ = await empty_blockchain.receive_block(block_bad_3) assert err == Err.INVALID_SUB_EPOCH_SUMMARY # 3d new_finished_ss_4 = recursive_replace( block.finished_sub_slots[0], "challenge_chain.subepoch_summary_hash", None, ) new_finished_ss_4 = recursive_replace( new_finished_ss_4, "reward_chain.challenge_chain_sub_slot_hash", new_finished_ss_4.challenge_chain.get_hash(), ) block_bad_4 = recursive_replace( block, "finished_sub_slots", [new_finished_ss_4] + block.finished_sub_slots[1:] ) result, err, _ = await empty_blockchain.receive_block(block_bad_4) assert err == Err.INVALID_SUB_EPOCH_SUMMARY or err == Err.INVALID_NEW_SUB_SLOT_ITERS result, err, _ = await empty_blockchain.receive_block(block) assert err is None assert result == ReceiveBlockResult.NEW_PEAK log.info( f"Added block {block.sub_block_height} total iters {block.total_iters} " f"new slot? {len(block.finished_sub_slots)}" ) assert empty_blockchain.get_peak().sub_block_height == len(blocks) - 1 @pytest.mark.asyncio async def test_unfinished_blocks(self, empty_blockchain): blockchain = empty_blockchain blocks = bt.get_consecutive_blocks(2) for block in blocks[:-1]: result, err, _ = await blockchain.receive_block(block) assert result == ReceiveBlockResult.NEW_PEAK block = blocks[-1] unf = UnfinishedBlock( block.finished_sub_slots, block.reward_chain_sub_block.get_unfinished(), block.challenge_chain_sp_proof, block.reward_chain_sp_proof, block.foliage_sub_block, block.foliage_block, block.transactions_info, block.transactions_generator, ) _, err = await blockchain.validate_unfinished_block(unf, False) assert err is None result, err, _ = await blockchain.receive_block(block) blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, force_overflow=True) block = blocks[-1] unf = UnfinishedBlock( block.finished_sub_slots, block.reward_chain_sub_block.get_unfinished(), block.challenge_chain_sp_proof, block.reward_chain_sp_proof, block.foliage_sub_block, block.foliage_block, block.transactions_info, block.transactions_generator, ) _, err = await blockchain.validate_unfinished_block(unf, False) assert err is None @pytest.mark.asyncio async def test_empty_genesis(self, empty_blockchain): blockchain = empty_blockchain for block in bt.get_consecutive_blocks(2, skip_slots=3): result, err, _ = await blockchain.receive_block(block) assert err is None assert result == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_empty_slots_non_genesis(self, empty_blockchain): blockchain = empty_blockchain blocks = bt.get_consecutive_blocks(10) for block in blocks: result, err, _ = await blockchain.receive_block(block) assert err is None assert result == ReceiveBlockResult.NEW_PEAK blocks = bt.get_consecutive_blocks(10, skip_slots=2, block_list_input=blocks) for block in blocks[10:]: result, err, _ = await blockchain.receive_block(block) assert err is None assert blockchain.get_peak().sub_block_height == 19 @pytest.mark.asyncio async def test_one_sb_per_slot(self, empty_blockchain): blockchain = empty_blockchain num_blocks = 20 blocks = [] for i in range(num_blocks): blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=1) result, err, _ = await blockchain.receive_block(blocks[-1]) assert result == ReceiveBlockResult.NEW_PEAK assert blockchain.get_peak().sub_block_height == num_blocks - 1 @pytest.mark.asyncio async def test_one_sb_per_two_slots(self, empty_blockchain): blockchain = empty_blockchain num_blocks = 20 blocks = [] for i in range(num_blocks): # Same thing, but 2 sub-slots per sub-block blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=2) result, err, _ = await blockchain.receive_block(blocks[-1]) assert result == ReceiveBlockResult.NEW_PEAK assert blockchain.get_peak().sub_block_height == num_blocks - 1 @pytest.mark.asyncio async def test_one_sb_per_five_slots(self, empty_blockchain): blockchain = empty_blockchain num_blocks = 10 blocks = [] for i in range(num_blocks): # Same thing, but 5 sub-slots per sub-block blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=5) result, err, _ = await blockchain.receive_block(blocks[-1]) assert result == ReceiveBlockResult.NEW_PEAK assert blockchain.get_peak().sub_block_height == num_blocks - 1 @pytest.mark.asyncio async def test_basic_chain_overflow(self, empty_blockchain): blocks = bt.get_consecutive_blocks(5, force_overflow=True) for block in blocks: result, err, _ = await empty_blockchain.receive_block(block) assert err is None assert result == ReceiveBlockResult.NEW_PEAK assert empty_blockchain.get_peak().sub_block_height == len(blocks) - 1 @pytest.mark.asyncio async def test_one_sb_per_two_slots_force_overflow(self, empty_blockchain): blockchain = empty_blockchain num_blocks = 10 blocks = [] for i in range(num_blocks): blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=2, force_overflow=True) result, err, _ = await blockchain.receive_block(blocks[-1]) assert err is None assert result == ReceiveBlockResult.NEW_PEAK assert blockchain.get_peak().sub_block_height == num_blocks - 1 @pytest.mark.asyncio async def test_invalid_prev(self, empty_blockchain): # 1 blocks = bt.get_consecutive_blocks(2, force_overflow=False) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK block_1_bad = recursive_replace(blocks[-1], "foliage_sub_block.prev_sub_block_hash", bytes([0] * 32)) result, err, _ = await empty_blockchain.receive_block(block_1_bad) assert result == ReceiveBlockResult.DISCONNECTED_BLOCK @pytest.mark.asyncio async def test_invalid_pospace(self, empty_blockchain): # 2 blocks = bt.get_consecutive_blocks(2, force_overflow=False) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK block_1_bad = recursive_replace(blocks[-1], "reward_chain_sub_block.proof_of_space.proof", bytes([0] * 32)) result, err, _ = await empty_blockchain.receive_block(block_1_bad) assert result == ReceiveBlockResult.INVALID_BLOCK assert err == Err.INVALID_POSPACE @pytest.mark.asyncio async def test_invalid_sub_slot_challenge_hash_genesis(self, empty_blockchain): # 2a blocks = bt.get_consecutive_blocks(1, force_overflow=False, skip_slots=1) new_finished_ss = recursive_replace( blocks[0].finished_sub_slots[0], "challenge_chain.challenge_chain_end_of_slot_vdf.challenge", bytes([2] * 32), ) block_0_bad = recursive_replace( blocks[0], "finished_sub_slots", [new_finished_ss] + blocks[0].finished_sub_slots[1:] ) result, err, _ = await empty_blockchain.receive_block(block_0_bad) assert result == ReceiveBlockResult.INVALID_BLOCK assert err == Err.INVALID_PREV_CHALLENGE_SLOT_HASH @pytest.mark.asyncio async def test_invalid_sub_slot_challenge_hash_non_genesis(self, empty_blockchain): # 2b blocks = bt.get_consecutive_blocks(1, force_overflow=False, skip_slots=0) blocks = bt.get_consecutive_blocks(1, force_overflow=False, skip_slots=1, block_list_input=blocks) new_finished_ss = recursive_replace( blocks[1].finished_sub_slots[0], "challenge_chain.challenge_chain_end_of_slot_vdf.challenge", bytes([2] * 32), ) block_1_bad = recursive_replace( blocks[1], "finished_sub_slots", [new_finished_ss] + blocks[1].finished_sub_slots[1:] ) _, _, _ = await empty_blockchain.receive_block(blocks[0]) result, err, _ = await empty_blockchain.receive_block(block_1_bad) assert result == ReceiveBlockResult.INVALID_BLOCK assert err == Err.INVALID_PREV_CHALLENGE_SLOT_HASH @pytest.mark.asyncio async def test_invalid_sub_slot_challenge_hash_empty_ss(self, empty_blockchain): # 2c blocks = bt.get_consecutive_blocks(1, force_overflow=False, skip_slots=0) blocks = bt.get_consecutive_blocks(1, force_overflow=False, skip_slots=2, block_list_input=blocks) new_finished_ss = recursive_replace( blocks[1].finished_sub_slots[-1], "challenge_chain.challenge_chain_end_of_slot_vdf.challenge", bytes([2] * 32), ) block_1_bad = recursive_replace( blocks[1], "finished_sub_slots", blocks[1].finished_sub_slots[:-1] + [new_finished_ss] ) _, _, _ = await empty_blockchain.receive_block(blocks[0]) result, err, _ = await empty_blockchain.receive_block(block_1_bad) assert result == ReceiveBlockResult.INVALID_BLOCK assert err == Err.INVALID_PREV_CHALLENGE_SLOT_HASH @pytest.mark.asyncio async def test_genesis_no_icc(self, empty_blockchain): # 2d blocks = bt.get_consecutive_blocks(1, force_overflow=False, skip_slots=1) new_finished_ss = recursive_replace( blocks[0].finished_sub_slots[0], "infused_challenge_chain", InfusedChallengeChainSubSlot( VDFInfo( bytes([0] * 32), uint64(1200), ClassgroupElement.get_default_element(), ) ), ) block_0_bad = recursive_replace( blocks[0], "finished_sub_slots", [new_finished_ss] + blocks[0].finished_sub_slots[1:] ) result, err, _ = await empty_blockchain.receive_block(block_0_bad) assert result == ReceiveBlockResult.INVALID_BLOCK assert err == Err.SHOULD_NOT_HAVE_ICC @pytest.mark.asyncio async def test_invalid_icc_sub_slot_vdf(self, empty_blockchain): blocks = bt.get_consecutive_blocks(10) for block in blocks: if len(block.finished_sub_slots) > 0 and block.finished_sub_slots[-1].infused_challenge_chain is not None: # Bad iters new_finished_ss = recursive_replace( block.finished_sub_slots[-1], "infused_challenge_chain", InfusedChallengeChainSubSlot( replace( block.finished_sub_slots[ -1 ].infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf, number_of_iterations=10000000, ) ), ) block_bad = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss] ) result, err, _ = await empty_blockchain.receive_block(block_bad) assert err == Err.INVALID_ICC_EOS_VDF # Bad output new_finished_ss_2 = recursive_replace( block.finished_sub_slots[-1], "infused_challenge_chain", InfusedChallengeChainSubSlot( replace( block.finished_sub_slots[ -1 ].infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf, output=ClassgroupElement.get_default_element(), ) ), ) block_bad_2 = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss_2] ) result, err, _ = await empty_blockchain.receive_block(block_bad_2) assert err == Err.INVALID_ICC_EOS_VDF # Bad challenge hash new_finished_ss_3 = recursive_replace( block.finished_sub_slots[-1], "infused_challenge_chain", InfusedChallengeChainSubSlot( replace( block.finished_sub_slots[ -1 ].infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf, challenge=bytes([0] * 32), ) ), ) block_bad_3 = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss_3] ) result, err, _ = await empty_blockchain.receive_block(block_bad_3) assert err == Err.INVALID_ICC_EOS_VDF # Bad proof new_finished_ss_5 = recursive_replace( block.finished_sub_slots[-1], "proofs.infused_challenge_chain_slot_proof", VDFProof(uint8(0), b"1239819023890"), ) block_bad_5 = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss_5] ) result, err, _ = await empty_blockchain.receive_block(block_bad_5) assert err == Err.INVALID_ICC_EOS_VDF result, err, _ = await empty_blockchain.receive_block(block) assert err is None assert result == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_invalid_icc_into_cc(self, empty_blockchain): blockchain = empty_blockchain blocks = bt.get_consecutive_blocks(1) assert (await blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK case_1, case_2 = False, False while not case_1 or not case_2: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=1) block = blocks[-1] if len(block.finished_sub_slots) > 0 and block.finished_sub_slots[-1].infused_challenge_chain is not None: if ( block.finished_sub_slots[-1].reward_chain.deficit == test_constants.MIN_SUB_BLOCKS_PER_CHALLENGE_BLOCK ): # 2g case_1 = True new_finished_ss = recursive_replace( block.finished_sub_slots[-1], "challenge_chain", replace( block.finished_sub_slots[-1].challenge_chain, infused_challenge_chain_sub_slot_hash=bytes([1] * 32), ), ) else: # 2h case_2 = True new_finished_ss = recursive_replace( block.finished_sub_slots[-1], "challenge_chain", replace( block.finished_sub_slots[-1].challenge_chain, infused_challenge_chain_sub_slot_hash=block.finished_sub_slots[ -1 ].infused_challenge_chain.get_hash(), ), ) block_bad = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss] ) result, err, _ = await blockchain.receive_block(block_bad) assert err == Err.INVALID_ICC_HASH_CC # 2i new_finished_ss_bad_rc = recursive_replace( block.finished_sub_slots[-1], "reward_chain", replace(block.finished_sub_slots[-1].reward_chain, infused_challenge_chain_sub_slot_hash=None), ) block_bad = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss_bad_rc] ) result, err, _ = await blockchain.receive_block(block_bad) assert err == Err.INVALID_ICC_HASH_RC elif len(block.finished_sub_slots) > 0 and block.finished_sub_slots[-1].infused_challenge_chain is None: # 2j new_finished_ss_bad_cc = recursive_replace( block.finished_sub_slots[-1], "challenge_chain", replace( block.finished_sub_slots[-1].challenge_chain, infused_challenge_chain_sub_slot_hash=bytes([1] * 32), ), ) block_bad = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss_bad_cc] ) result, err, _ = await blockchain.receive_block(block_bad) assert err == Err.INVALID_ICC_HASH_CC # 2k new_finished_ss_bad_rc = recursive_replace( block.finished_sub_slots[-1], "reward_chain", replace( block.finished_sub_slots[-1].reward_chain, infused_challenge_chain_sub_slot_hash=bytes([1] * 32) ), ) block_bad = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss_bad_rc] ) result, err, _ = await blockchain.receive_block(block_bad) assert err == Err.INVALID_ICC_HASH_RC # Finally, add the block properly result, err, _ = await blockchain.receive_block(block) assert err is None assert result == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_empty_slot_no_ses(self, empty_blockchain): # 2l blockchain = empty_blockchain blocks = bt.get_consecutive_blocks(1) assert (await blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=4) new_finished_ss = recursive_replace( blocks[-1].finished_sub_slots[-1], "challenge_chain", replace(blocks[-1].finished_sub_slots[-1].challenge_chain, subepoch_summary_hash=std_hash(b"0")), ) block_bad = recursive_replace( blocks[-1], "finished_sub_slots", blocks[-1].finished_sub_slots[:-1] + [new_finished_ss] ) result, err, _ = await blockchain.receive_block(block_bad) assert err == Err.INVALID_SUB_EPOCH_SUMMARY_HASH @pytest.mark.asyncio async def test_empty_sub_slots_epoch(self, empty_blockchain): # 2m # Tests adding an empty sub slot after the sub-epoch / epoch. # Also tests overflow block in epoch blocks_base = bt.get_consecutive_blocks(test_constants.EPOCH_SUB_BLOCKS) blocks_1 = bt.get_consecutive_blocks(1, block_list_input=blocks_base, force_overflow=True) blocks_2 = bt.get_consecutive_blocks(1, skip_slots=1, block_list_input=blocks_base, force_overflow=True) blocks_3 = bt.get_consecutive_blocks(1, skip_slots=2, block_list_input=blocks_base, force_overflow=True) blocks_4 = bt.get_consecutive_blocks(1, block_list_input=blocks_base) for block in blocks_base: result, err, _ = await empty_blockchain.receive_block(block) assert err is None assert result == ReceiveBlockResult.NEW_PEAK for block in [blocks_1[-1], blocks_2[-1], blocks_3[-1], blocks_4[-1]]: result, err, _ = await empty_blockchain.receive_block(block) assert err is None @pytest.mark.asyncio async def test_wrong_cc_hash_rc(self, empty_blockchain): # 2o blockchain = empty_blockchain blocks = bt.get_consecutive_blocks(1, skip_slots=1) blocks = bt.get_consecutive_blocks(1, skip_slots=1, block_list_input=blocks) assert (await blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK new_finished_ss = recursive_replace( blocks[-1].finished_sub_slots[-1], "reward_chain", replace(blocks[-1].finished_sub_slots[-1].reward_chain, challenge_chain_sub_slot_hash=bytes([3] * 32)), ) block_1_bad = recursive_replace( blocks[-1], "finished_sub_slots", blocks[-1].finished_sub_slots[:-1] + [new_finished_ss] ) result, err, _ = await blockchain.receive_block(block_1_bad) assert result == ReceiveBlockResult.INVALID_BLOCK assert err == Err.INVALID_CHALLENGE_SLOT_HASH_RC @pytest.mark.asyncio async def test_invalid_cc_sub_slot_vdf(self, empty_blockchain): # 2q blocks = bt.get_consecutive_blocks(10) for block in blocks: if len(block.finished_sub_slots): # Bad iters new_finished_ss = recursive_replace( block.finished_sub_slots[-1], "challenge_chain", recursive_replace( block.finished_sub_slots[-1].challenge_chain, "challenge_chain_end_of_slot_vdf.number_of_iterations", uint64(10000000), ), ) new_finished_ss = recursive_replace( new_finished_ss, "reward_chain.challenge_chain_sub_slot_hash", new_finished_ss.challenge_chain.get_hash(), ) block_bad = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss] ) result, err, _ = await empty_blockchain.receive_block(block_bad) assert err == Err.INVALID_CC_EOS_VDF # Bad output new_finished_ss_2 = recursive_replace( block.finished_sub_slots[-1], "challenge_chain", recursive_replace( block.finished_sub_slots[-1].challenge_chain, "challenge_chain_end_of_slot_vdf.output", ClassgroupElement.get_default_element(), ), ) new_finished_ss_2 = recursive_replace( new_finished_ss_2, "reward_chain.challenge_chain_sub_slot_hash", new_finished_ss_2.challenge_chain.get_hash(), ) block_bad_2 = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss_2] ) result, err, _ = await empty_blockchain.receive_block(block_bad_2) assert err == Err.INVALID_CC_EOS_VDF # Bad challenge hash new_finished_ss_3 = recursive_replace( block.finished_sub_slots[-1], "challenge_chain", recursive_replace( block.finished_sub_slots[-1].challenge_chain, "challenge_chain_end_of_slot_vdf.challenge", bytes([1] * 32), ), ) new_finished_ss_3 = recursive_replace( new_finished_ss_3, "reward_chain.challenge_chain_sub_slot_hash", new_finished_ss_3.challenge_chain.get_hash(), ) block_bad_3 = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss_3] ) result, err, _ = await empty_blockchain.receive_block(block_bad_3) assert err == Err.INVALID_CC_EOS_VDF or err == Err.INVALID_PREV_CHALLENGE_SLOT_HASH # Bad proof new_finished_ss_5 = recursive_replace( block.finished_sub_slots[-1], "proofs.challenge_chain_slot_proof", VDFProof(uint8(0), b"1239819023890"), ) block_bad_5 = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss_5] ) result, err, _ = await empty_blockchain.receive_block(block_bad_5) assert err == Err.INVALID_CC_EOS_VDF result, err, _ = await empty_blockchain.receive_block(block) assert err is None assert result == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_invalid_rc_sub_slot_vdf(self, empty_blockchain): # 2p blocks = bt.get_consecutive_blocks(10) for block in blocks: if len(block.finished_sub_slots): # Bad iters new_finished_ss = recursive_replace( block.finished_sub_slots[-1], "reward_chain", recursive_replace( block.finished_sub_slots[-1].reward_chain, "end_of_slot_vdf.number_of_iterations", uint64(10000000), ), ) block_bad = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss] ) result, err, _ = await empty_blockchain.receive_block(block_bad) assert err == Err.INVALID_RC_EOS_VDF # Bad output new_finished_ss_2 = recursive_replace( block.finished_sub_slots[-1], "reward_chain", recursive_replace( block.finished_sub_slots[-1].reward_chain, "end_of_slot_vdf.output", ClassgroupElement.get_default_element(), ), ) block_bad_2 = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss_2] ) result, err, _ = await empty_blockchain.receive_block(block_bad_2) assert err == Err.INVALID_RC_EOS_VDF # Bad challenge hash new_finished_ss_3 = recursive_replace( block.finished_sub_slots[-1], "reward_chain", recursive_replace( block.finished_sub_slots[-1].reward_chain, "end_of_slot_vdf.challenge", bytes([1] * 32), ), ) block_bad_3 = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss_3] ) result, err, _ = await empty_blockchain.receive_block(block_bad_3) assert err == Err.INVALID_RC_EOS_VDF # Bad proof new_finished_ss_5 = recursive_replace( block.finished_sub_slots[-1], "proofs.reward_chain_slot_proof", VDFProof(uint8(0), b"1239819023890"), ) block_bad_5 = recursive_replace( block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss_5] ) result, err, _ = await empty_blockchain.receive_block(block_bad_5) assert err == Err.INVALID_RC_EOS_VDF result, err, _ = await empty_blockchain.receive_block(block) assert err is None assert result == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_genesis_bad_deficit(self, empty_blockchain): # 2r block = bt.get_consecutive_blocks(1, skip_slots=2)[0] new_finished_ss = recursive_replace( block.finished_sub_slots[-1], "reward_chain", recursive_replace( block.finished_sub_slots[-1].reward_chain, "deficit", test_constants.MIN_SUB_BLOCKS_PER_CHALLENGE_BLOCK - 1, ), ) block_bad = recursive_replace(block, "finished_sub_slots", block.finished_sub_slots[:-1] + [new_finished_ss]) result, err, _ = await empty_blockchain.receive_block(block_bad) assert err == Err.INVALID_DEFICIT @pytest.mark.asyncio async def test_reset_deficit(self, empty_blockchain): # 2s, 2t blockchain = empty_blockchain blocks = bt.get_consecutive_blocks(2) await empty_blockchain.receive_block(blocks[0]) await empty_blockchain.receive_block(blocks[1]) case_1, case_2 = False, False while not case_1 or not case_2: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=1) if len(blocks[-1].finished_sub_slots) > 0: new_finished_ss = recursive_replace( blocks[-1].finished_sub_slots[-1], "reward_chain", recursive_replace( blocks[-1].finished_sub_slots[-1].reward_chain, "deficit", uint8(0), ), ) if blockchain.sub_blocks[blocks[-2].header_hash].deficit == 0: case_1 = True else: case_2 = True block_bad = recursive_replace( blocks[-1], "finished_sub_slots", blocks[-1].finished_sub_slots[:-1] + [new_finished_ss] ) result, err, _ = await empty_blockchain.receive_block(block_bad) assert err == Err.INVALID_DEFICIT or err == Err.INVALID_ICC_HASH_CC result, err, _ = await empty_blockchain.receive_block(blocks[-1]) assert result == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_genesis_has_ses(self, empty_blockchain): # 3a block = bt.get_consecutive_blocks(1, skip_slots=1)[0] new_finished_ss = recursive_replace( block.finished_sub_slots[0], "challenge_chain", recursive_replace( block.finished_sub_slots[0].challenge_chain, "subepoch_summary_hash", bytes([0] * 32), ), ) new_finished_ss = recursive_replace( new_finished_ss, "reward_chain", replace( new_finished_ss.reward_chain, challenge_chain_sub_slot_hash=new_finished_ss.challenge_chain.get_hash() ), ) block_bad = recursive_replace(block, "finished_sub_slots", [new_finished_ss] + block.finished_sub_slots[1:]) result, err, _ = await empty_blockchain.receive_block(block_bad) assert err == Err.INVALID_SUB_EPOCH_SUMMARY_HASH @pytest.mark.asyncio async def test_no_ses_if_no_se(self, empty_blockchain): # 3b blocks = bt.get_consecutive_blocks(1) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK while True: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) if len(blocks[-1].finished_sub_slots) > 0: new_finished_ss: EndOfSubSlotBundle = recursive_replace( blocks[-1].finished_sub_slots[0], "challenge_chain", recursive_replace( blocks[-1].finished_sub_slots[0].challenge_chain, "subepoch_summary_hash", bytes([0] * 32), ), ) new_finished_ss = recursive_replace( new_finished_ss, "reward_chain", replace( new_finished_ss.reward_chain, challenge_chain_sub_slot_hash=new_finished_ss.challenge_chain.get_hash(), ), ) block_bad = recursive_replace( blocks[-1], "finished_sub_slots", [new_finished_ss] + blocks[-1].finished_sub_slots[1:] ) result, err, _ = await empty_blockchain.receive_block(block_bad) assert err == Err.INVALID_SUB_EPOCH_SUMMARY_HASH return await empty_blockchain.receive_block(blocks[-1]) @pytest.mark.asyncio async def test_too_many_sub_blocks(self, empty_blockchain): # 4: TODO pass @pytest.mark.asyncio async def test_bad_pos(self, empty_blockchain): # 5 blocks = bt.get_consecutive_blocks(2) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK block_bad = recursive_replace(blocks[-1], "reward_chain_sub_block.proof_of_space.challenge", std_hash(b"")) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_POSPACE block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.proof_of_space.pool_contract_puzzle_hash", std_hash(b"") ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_POSPACE block_bad = recursive_replace(blocks[-1], "reward_chain_sub_block.proof_of_space.pool_public_key", None) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_POSPACE block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.proof_of_space.plot_public_key", AugSchemeMPL.key_gen(std_hash(b"1231n")).get_g1(), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_POSPACE block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.proof_of_space.size", 32, ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_POSPACE block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.proof_of_space.proof", bytes([1] * int(blocks[-1].reward_chain_sub_block.proof_of_space.size * 64 / 8)), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_POSPACE # TODO: test not passing the plot filter @pytest.mark.asyncio async def test_bad_signage_point_index(self, empty_blockchain): # 6 blocks = bt.get_consecutive_blocks(2) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK with pytest.raises(ValueError): block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.signage_point_index", test_constants.NUM_SPS_SUB_SLOT ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_SP_INDEX with pytest.raises(ValueError): block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.signage_point_index", test_constants.NUM_SPS_SUB_SLOT + 1 ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_SP_INDEX @pytest.mark.asyncio async def test_sp_0_no_sp(self, empty_blockchain): # 7 blocks = [] case_1, case_2 = False, False while not case_1 or not case_2: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) if blocks[-1].reward_chain_sub_block.signage_point_index == 0: case_1 = True block_bad = recursive_replace(blocks[-1], "reward_chain_sub_block.signage_point_index", uint8(1)) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_SP_INDEX else: case_2 = True block_bad = recursive_replace(blocks[-1], "reward_chain_sub_block.signage_point_index", uint8(0)) error_code = (await empty_blockchain.receive_block(block_bad))[1] assert error_code == Err.INVALID_SP_INDEX or error_code == Err.INVALID_POSPACE assert (await empty_blockchain.receive_block(blocks[-1]))[0] == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_epoch_overflows(self, empty_blockchain): # 9. TODO. This is hard to test because it requires modifying the block tools to make these special blocks pass @pytest.mark.asyncio async def test_bad_total_iters(self, empty_blockchain): # 10 blocks = bt.get_consecutive_blocks(2) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.total_iters", blocks[-1].reward_chain_sub_block.total_iters + 1 ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_TOTAL_ITERS @pytest.mark.asyncio async def test_bad_rc_sp_vdf(self, empty_blockchain): # 11 blocks = bt.get_consecutive_blocks(1) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK while True: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) if blocks[-1].reward_chain_sub_block.signage_point_index != 0: block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.reward_chain_sp_vdf.challenge", std_hash(b"1") ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_RC_SP_VDF block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.reward_chain_sp_vdf.output", ClassgroupElement(int512(10), int512(2)), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_RC_SP_VDF block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.reward_chain_sp_vdf.number_of_iterations", uint64(1111111111111), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_RC_SP_VDF block_bad = recursive_replace( blocks[-1], "reward_chain_sp_proof", VDFProof(uint8(0), std_hash(b"")), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_RC_SP_VDF return assert (await empty_blockchain.receive_block(blocks[-1]))[0] == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_bad_rc_sp_sig(self, empty_blockchain): # 12 blocks = bt.get_consecutive_blocks(2) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.reward_chain_sp_signature", G2Element.generator() ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_RC_SIGNATURE @pytest.mark.asyncio async def test_bad_cc_sp_vdf(self, empty_blockchain): # 13. Note: does not validate fully due to proof of space being validated first blocks = bt.get_consecutive_blocks(1) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK while True: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) if blocks[-1].reward_chain_sub_block.signage_point_index != 0: block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.challenge_chain_sp_vdf.challenge", std_hash(b"1") ) assert (await empty_blockchain.receive_block(block_bad))[0] == ReceiveBlockResult.INVALID_BLOCK block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.challenge_chain_sp_vdf.output", ClassgroupElement(int512(10), int512(2)), ) assert (await empty_blockchain.receive_block(block_bad))[0] == ReceiveBlockResult.INVALID_BLOCK block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.challenge_chain_sp_vdf.number_of_iterations", uint64(1111111111111), ) assert (await empty_blockchain.receive_block(block_bad))[0] == ReceiveBlockResult.INVALID_BLOCK block_bad = recursive_replace( blocks[-1], "challenge_chain_sp_proof", VDFProof(uint8(0), std_hash(b"")), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_CC_SP_VDF return assert (await empty_blockchain.receive_block(blocks[-1]))[0] == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_bad_cc_sp_sig(self, empty_blockchain): # 14 blocks = bt.get_consecutive_blocks(2) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.challenge_chain_sp_signature", G2Element.generator() ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_CC_SIGNATURE @pytest.mark.asyncio async def test_is_block(self, empty_blockchain): # 15: TODO pass @pytest.mark.asyncio async def test_bad_foliage_sb_sig(self, empty_blockchain): # 16 blocks = bt.get_consecutive_blocks(2) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK block_bad = recursive_replace( blocks[-1], "foliage_sub_block.foliage_sub_block_signature", G2Element.generator() ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_PLOT_SIGNATURE @pytest.mark.asyncio async def test_bad_foliage_block_sig(self, empty_blockchain): # 17 blocks = bt.get_consecutive_blocks(1) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK while True: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) if blocks[-1].foliage_block is not None: block_bad = recursive_replace( blocks[-1], "foliage_sub_block.foliage_block_signature", G2Element.generator() ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_PLOT_SIGNATURE return assert (await empty_blockchain.receive_block(blocks[-1]))[0] == ReceiveBlockResult.NEW_PEAK @pytest.mark.asyncio async def test_unfinished_reward_chain_sb_hash(self, empty_blockchain): # 18 blocks = bt.get_consecutive_blocks(2) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK block_bad: FullBlock = recursive_replace( blocks[-1], "foliage_sub_block.foliage_sub_block_data.unfinished_reward_block_hash", std_hash(b"2") ) new_m = block_bad.foliage_sub_block.foliage_sub_block_data.get_hash() new_fsb_sig = bt.get_plot_signature(new_m, blocks[-1].reward_chain_sub_block.proof_of_space.plot_public_key) block_bad = recursive_replace(block_bad, "foliage_sub_block.foliage_sub_block_signature", new_fsb_sig) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_URSB_HASH @pytest.mark.asyncio async def test_pool_target_height(self, empty_blockchain): # 19 blocks = bt.get_consecutive_blocks(3) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK assert (await empty_blockchain.receive_block(blocks[1]))[0] == ReceiveBlockResult.NEW_PEAK block_bad: FullBlock = recursive_replace( blocks[-1], "foliage_sub_block.foliage_sub_block_data.pool_target.max_height", 1 ) new_m = block_bad.foliage_sub_block.foliage_sub_block_data.get_hash() new_fsb_sig = bt.get_plot_signature(new_m, blocks[-1].reward_chain_sub_block.proof_of_space.plot_public_key) block_bad = recursive_replace(block_bad, "foliage_sub_block.foliage_sub_block_signature", new_fsb_sig) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.OLD_POOL_TARGET @pytest.mark.asyncio async def test_pool_target_pre_farm(self, empty_blockchain): # 20a blocks = bt.get_consecutive_blocks(1) block_bad: FullBlock = recursive_replace( blocks[-1], "foliage_sub_block.foliage_sub_block_data.pool_target.puzzle_hash", std_hash(b"12") ) new_m = block_bad.foliage_sub_block.foliage_sub_block_data.get_hash() new_fsb_sig = bt.get_plot_signature(new_m, blocks[-1].reward_chain_sub_block.proof_of_space.plot_public_key) block_bad = recursive_replace(block_bad, "foliage_sub_block.foliage_sub_block_signature", new_fsb_sig) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_PREFARM @pytest.mark.asyncio async def test_pool_target_signature(self, empty_blockchain): # 20b blocks = bt.get_consecutive_blocks(3) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK assert (await empty_blockchain.receive_block(blocks[1]))[0] == ReceiveBlockResult.NEW_PEAK block_bad: FullBlock = recursive_replace( blocks[-1], "foliage_sub_block.foliage_sub_block_data.pool_signature", G2Element.generator() ) new_m = block_bad.foliage_sub_block.foliage_sub_block_data.get_hash() new_fsb_sig = bt.get_plot_signature(new_m, blocks[-1].reward_chain_sub_block.proof_of_space.plot_public_key) block_bad = recursive_replace(block_bad, "foliage_sub_block.foliage_sub_block_signature", new_fsb_sig) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_POOL_SIGNATURE @pytest.mark.asyncio async def test_foliage_data_presence(self, empty_blockchain): # 22 blocks = bt.get_consecutive_blocks(1) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK case_1, case_2 = False, False while not case_1 or not case_2: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) if blocks[-1].foliage_block is not None: case_1 = True block_bad: FullBlock = recursive_replace(blocks[-1], "foliage_sub_block.foliage_block_hash", None) else: case_2 = True block_bad: FullBlock = recursive_replace( blocks[-1], "foliage_sub_block.foliage_block_hash", std_hash(b"") ) err_code = (await empty_blockchain.receive_block(block_bad))[1] assert err_code == Err.INVALID_FOLIAGE_BLOCK_PRESENCE or err_code == Err.INVALID_IS_BLOCK await empty_blockchain.receive_block(blocks[-1]) @pytest.mark.asyncio async def test_foliage_block_hash(self, empty_blockchain): # 23 blocks = bt.get_consecutive_blocks(1) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK case_1, case_2 = False, False while not case_1 or not case_2: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) if blocks[-1].foliage_block is not None: block_bad: FullBlock = recursive_replace( blocks[-1], "foliage_sub_block.foliage_block_hash", std_hash(b"2") ) new_m = block_bad.foliage_sub_block.foliage_block_hash new_fbh_sig = bt.get_plot_signature( new_m, blocks[-1].reward_chain_sub_block.proof_of_space.plot_public_key ) block_bad = recursive_replace(block_bad, "foliage_sub_block.foliage_block_signature", new_fbh_sig) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_FOLIAGE_BLOCK_HASH return await empty_blockchain.receive_block(blocks[-1]) @pytest.mark.asyncio async def test_genesis_bad_prev_block(self, empty_blockchain): # 24a blocks = bt.get_consecutive_blocks(1) block_bad: FullBlock = recursive_replace(blocks[-1], "foliage_block.prev_block_hash", std_hash(b"2")) block_bad: FullBlock = recursive_replace( block_bad, "foliage_sub_block.foliage_block_hash", block_bad.foliage_block.get_hash() ) new_m = block_bad.foliage_sub_block.foliage_block_hash new_fbh_sig = bt.get_plot_signature(new_m, blocks[-1].reward_chain_sub_block.proof_of_space.plot_public_key) block_bad = recursive_replace(block_bad, "foliage_sub_block.foliage_block_signature", new_fbh_sig) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_PREV_BLOCK_HASH @pytest.mark.asyncio async def test_bad_prev_block_non_genesis(self, empty_blockchain): # 24b blocks = bt.get_consecutive_blocks(1) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK while True: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) if blocks[-1].foliage_block is not None: block_bad: FullBlock = recursive_replace(blocks[-1], "foliage_block.prev_block_hash", std_hash(b"2")) block_bad: FullBlock = recursive_replace( block_bad, "foliage_sub_block.foliage_block_hash", block_bad.foliage_block.get_hash() ) new_m = block_bad.foliage_sub_block.foliage_block_hash new_fbh_sig = bt.get_plot_signature( new_m, blocks[-1].reward_chain_sub_block.proof_of_space.plot_public_key ) block_bad = recursive_replace(block_bad, "foliage_sub_block.foliage_block_signature", new_fbh_sig) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_PREV_BLOCK_HASH return await empty_blockchain.receive_block(blocks[-1]) @pytest.mark.asyncio async def test_bad_filter_hash(self, empty_blockchain): # 25 blocks = bt.get_consecutive_blocks(1) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK while True: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) if blocks[-1].foliage_block is not None: block_bad: FullBlock = recursive_replace(blocks[-1], "foliage_block.filter_hash", std_hash(b"2")) block_bad: FullBlock = recursive_replace( block_bad, "foliage_sub_block.foliage_block_hash", block_bad.foliage_block.get_hash() ) new_m = block_bad.foliage_sub_block.foliage_block_hash new_fbh_sig = bt.get_plot_signature( new_m, blocks[-1].reward_chain_sub_block.proof_of_space.plot_public_key ) block_bad = recursive_replace(block_bad, "foliage_sub_block.foliage_block_signature", new_fbh_sig) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_TRANSACTIONS_FILTER_HASH return await empty_blockchain.receive_block(blocks[-1]) @pytest.mark.asyncio async def test_bad_timestamp(self, empty_blockchain): # 26 blocks = bt.get_consecutive_blocks(1) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK while True: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) if blocks[-1].foliage_block is not None: block_bad: FullBlock = recursive_replace( blocks[-1], "foliage_block.timestamp", blocks[0].foliage_block.timestamp - 10 ) block_bad: FullBlock = recursive_replace( block_bad, "foliage_sub_block.foliage_block_hash", block_bad.foliage_block.get_hash() ) new_m = block_bad.foliage_sub_block.foliage_block_hash new_fbh_sig = bt.get_plot_signature( new_m, blocks[-1].reward_chain_sub_block.proof_of_space.plot_public_key ) block_bad = recursive_replace(block_bad, "foliage_sub_block.foliage_block_signature", new_fbh_sig) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.TIMESTAMP_TOO_FAR_IN_PAST block_bad: FullBlock = recursive_replace( blocks[-1], "foliage_block.timestamp", blocks[0].foliage_block.timestamp + 10000000 ) block_bad: FullBlock = recursive_replace( block_bad, "foliage_sub_block.foliage_block_hash", block_bad.foliage_block.get_hash() ) new_m = block_bad.foliage_sub_block.foliage_block_hash new_fbh_sig = bt.get_plot_signature( new_m, blocks[-1].reward_chain_sub_block.proof_of_space.plot_public_key ) block_bad = recursive_replace(block_bad, "foliage_sub_block.foliage_block_signature", new_fbh_sig) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.TIMESTAMP_TOO_FAR_IN_FUTURE return await empty_blockchain.receive_block(blocks[-1]) @pytest.mark.asyncio async def test_sub_block_height(self, empty_blockchain): # 27 blocks = bt.get_consecutive_blocks(2) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK block_bad: FullBlock = recursive_replace(blocks[-1], "reward_chain_sub_block.sub_block_height", 2) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_HEIGHT @pytest.mark.asyncio async def test_sub_block_height_genesis(self, empty_blockchain): # 27 blocks = bt.get_consecutive_blocks(1) block_bad: FullBlock = recursive_replace(blocks[-1], "reward_chain_sub_block.sub_block_height", 1) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_PREV_BLOCK_HASH @pytest.mark.asyncio async def test_weight(self, empty_blockchain): # 28 blocks = bt.get_consecutive_blocks(2) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK block_bad: FullBlock = recursive_replace(blocks[-1], "reward_chain_sub_block.weight", 22131) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_WEIGHT @pytest.mark.asyncio async def test_weight_genesis(self, empty_blockchain): # 28 blocks = bt.get_consecutive_blocks(1) block_bad: FullBlock = recursive_replace(blocks[-1], "reward_chain_sub_block.weight", 0) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_WEIGHT @pytest.mark.asyncio async def test_bad_cc_ip_vdf(self, empty_blockchain): # 29 blocks = bt.get_consecutive_blocks(1) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.challenge_chain_ip_vdf.challenge", std_hash(b"1") ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_CC_IP_VDF block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.challenge_chain_ip_vdf.output", ClassgroupElement(int512(10), int512(2)), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_CC_IP_VDF block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.challenge_chain_ip_vdf.number_of_iterations", uint64(1111111111111), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_CC_IP_VDF block_bad = recursive_replace( blocks[-1], "challenge_chain_ip_proof", VDFProof(uint8(0), std_hash(b"")), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_CC_IP_VDF @pytest.mark.asyncio async def test_bad_rc_ip_vdf(self, empty_blockchain): # 30 blocks = bt.get_consecutive_blocks(1) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.reward_chain_ip_vdf.challenge", std_hash(b"1") ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_RC_IP_VDF block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.reward_chain_ip_vdf.output", ClassgroupElement(int512(10), int512(2)), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_RC_IP_VDF block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.reward_chain_ip_vdf.number_of_iterations", uint64(1111111111111), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_RC_IP_VDF block_bad = recursive_replace( blocks[-1], "reward_chain_ip_proof", VDFProof(uint8(0), std_hash(b"")), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_RC_IP_VDF @pytest.mark.asyncio async def test_bad_icc_ip_vdf(self, empty_blockchain): # 31 blocks = bt.get_consecutive_blocks(1) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.infused_challenge_chain_ip_vdf.challenge", std_hash(b"1") ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_ICC_VDF assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_ICC_VDF block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.infused_challenge_chain_ip_vdf.output", ClassgroupElement(int512(10), int512(2)), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_ICC_VDF block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.infused_challenge_chain_ip_vdf.number_of_iterations", uint64(1111111111111), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_ICC_VDF block_bad = recursive_replace( blocks[-1], "infused_challenge_chain_ip_proof", VDFProof(uint8(0), std_hash(b"")), ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_ICC_VDF @pytest.mark.asyncio async def test_reward_block_hash(self, empty_blockchain): # 32 blocks = bt.get_consecutive_blocks(2) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK block_bad: FullBlock = recursive_replace(blocks[-1], "foliage_sub_block.reward_block_hash", std_hash(b"")) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_REWARD_BLOCK_HASH @pytest.mark.asyncio async def test_reward_block_hash_2(self, empty_blockchain): # 33 blocks = bt.get_consecutive_blocks(1) block_bad: FullBlock = recursive_replace(blocks[0], "reward_chain_sub_block.is_block", False) block_bad: FullBlock = recursive_replace( block_bad, "foliage_sub_block.reward_block_hash", block_bad.reward_chain_sub_block.get_hash() ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_FOLIAGE_BLOCK_PRESENCE assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK # Test one which should not be a block while True: blocks = bt.get_consecutive_blocks(1, block_list_input=blocks) if not blocks[-1].is_block(): block_bad: FullBlock = recursive_replace(blocks[-1], "reward_chain_sub_block.is_block", True) block_bad: FullBlock = recursive_replace( block_bad, "foliage_sub_block.reward_block_hash", block_bad.reward_chain_sub_block.get_hash() ) assert (await empty_blockchain.receive_block(block_bad))[1] == Err.INVALID_FOLIAGE_BLOCK_PRESENCE return assert (await empty_blockchain.receive_block(blocks[-1]))[0] == ReceiveBlockResult.NEW_PEAK class TestBodyValidation: @pytest.mark.asyncio async def test_not_block_but_has_data(self, empty_blockchain): # TODO pass class TestReorgs: @pytest.mark.asyncio async def test_basic_reorg(self, empty_blockchain): b = empty_blockchain blocks = bt.get_consecutive_blocks(15) for block in blocks: assert (await b.receive_block(block))[0] == ReceiveBlockResult.NEW_PEAK assert b.get_peak().sub_block_height == 14 blocks_reorg_chain = bt.get_consecutive_blocks(7, blocks[:10], seed=b"2") for reorg_block in blocks_reorg_chain: result, error_code, fork_height = await b.receive_block(reorg_block) if reorg_block.sub_block_height < 10: assert result == ReceiveBlockResult.ALREADY_HAVE_BLOCK elif reorg_block.sub_block_height < 14: assert result == ReceiveBlockResult.ADDED_AS_ORPHAN elif reorg_block.sub_block_height >= 15: assert result == ReceiveBlockResult.NEW_PEAK assert error_code is None assert b.get_peak().sub_block_height == 16 @pytest.mark.asyncio async def test_long_reorg(self, empty_blockchain, default_10000_blocks): # Reorg longer than a difficulty adjustment # Also tests higher weight chain but lower height b = empty_blockchain num_blocks_chain_1 = 3 * test_constants.EPOCH_SUB_BLOCKS + test_constants.MAX_SUB_SLOT_SUB_BLOCKS + 10 num_blocks_chain_2_start = test_constants.EPOCH_SUB_BLOCKS - 20 num_blocks_chain_2 = 3 * test_constants.EPOCH_SUB_BLOCKS + test_constants.MAX_SUB_SLOT_SUB_BLOCKS + 8 assert num_blocks_chain_1 < 10000 blocks = default_10000_blocks[:num_blocks_chain_1] for block in blocks: assert (await b.receive_block(block))[0] == ReceiveBlockResult.NEW_PEAK chain_1_height = b.get_peak().sub_block_height chain_1_weight = b.get_peak().weight assert chain_1_height == (num_blocks_chain_1 - 1) # These blocks will have less time between them (timestamp) and therefore will make difficulty go up # This means that the weight will grow faster, and we can get a heavier chain with lower height blocks_reorg_chain = bt.get_consecutive_blocks( num_blocks_chain_2 - num_blocks_chain_2_start, blocks[:num_blocks_chain_2_start], seed=b"2", time_per_sub_block=8, ) found_orphan = False for reorg_block in blocks_reorg_chain: result, error_code, fork_height = await b.receive_block(reorg_block) if reorg_block.sub_block_height < num_blocks_chain_2_start: assert result == ReceiveBlockResult.ALREADY_HAVE_BLOCK if reorg_block.weight <= chain_1_weight: if result == ReceiveBlockResult.ADDED_AS_ORPHAN: found_orphan = True assert error_code is None assert result == ReceiveBlockResult.ADDED_AS_ORPHAN or result == ReceiveBlockResult.ALREADY_HAVE_BLOCK elif reorg_block.weight > chain_1_weight: assert reorg_block.sub_block_height < chain_1_height assert result == ReceiveBlockResult.NEW_PEAK assert error_code is None assert found_orphan assert b.get_peak().weight > chain_1_weight assert b.get_peak().sub_block_height < chain_1_height @pytest.mark.asyncio async def test_reorg_from_genesis(self, empty_blockchain): b = empty_blockchain WALLET_A = WalletTool() WALLET_A_PUZZLE_HASHES = [WALLET_A.get_new_puzzlehash() for _ in range(5)] blocks = bt.get_consecutive_blocks(15) for block in blocks: assert (await b.receive_block(block))[0] == ReceiveBlockResult.NEW_PEAK assert b.get_peak().sub_block_height == 14 # Reorg to alternate chain that is 1 height longer found_orphan = False blocks_reorg_chain = bt.get_consecutive_blocks(16, [], seed=b"2") for reorg_block in blocks_reorg_chain: result, error_code, fork_height = await b.receive_block(reorg_block) if reorg_block.sub_block_height < 14: if result == ReceiveBlockResult.ADDED_AS_ORPHAN: found_orphan = True assert result == ReceiveBlockResult.ADDED_AS_ORPHAN or result == ReceiveBlockResult.ALREADY_HAVE_BLOCK elif reorg_block.sub_block_height >= 15: assert result == ReceiveBlockResult.NEW_PEAK assert error_code is None # Back to original chain blocks_reorg_chain_2 = bt.get_consecutive_blocks(3, blocks, seed=b"3") result, error_code, fork_height = await b.receive_block(blocks_reorg_chain_2[-3]) assert result == ReceiveBlockResult.ADDED_AS_ORPHAN result, error_code, fork_height = await b.receive_block(blocks_reorg_chain_2[-2]) assert result == ReceiveBlockResult.NEW_PEAK result, error_code, fork_height = await b.receive_block(blocks_reorg_chain_2[-1]) assert result == ReceiveBlockResult.NEW_PEAK assert found_orphan assert b.get_peak().sub_block_height == 17 @pytest.mark.asyncio async def test_reorg_transaction(self, empty_blockchain): b = empty_blockchain wallet_a = WalletTool() WALLET_A_PUZZLE_HASHES = [wallet_a.get_new_puzzlehash() for _ in range(5)] coinbase_puzzlehash = WALLET_A_PUZZLE_HASHES[0] receiver_puzzlehash = WALLET_A_PUZZLE_HASHES[1] blocks = bt.get_consecutive_blocks(10, farmer_reward_puzzle_hash=coinbase_puzzlehash) blocks = bt.get_consecutive_blocks( 2, blocks, farmer_reward_puzzle_hash=coinbase_puzzlehash, guarantee_block=True ) spend_block = blocks[10] spend_coin = None for coin in list(spend_block.get_included_reward_coins()): if coin.puzzle_hash == coinbase_puzzlehash: spend_coin = coin spend_bundle = wallet_a.generate_signed_transaction(1000, receiver_puzzlehash, spend_coin) blocks = bt.get_consecutive_blocks( 2, blocks, farmer_reward_puzzle_hash=coinbase_puzzlehash, transaction_data=spend_bundle, guarantee_block=True, ) blocks_fork = bt.get_consecutive_blocks( 1, blocks[:12], farmer_reward_puzzle_hash=coinbase_puzzlehash, seed=b"123", guarantee_block=True ) blocks_fork = bt.get_consecutive_blocks( 2, blocks_fork, farmer_reward_puzzle_hash=coinbase_puzzlehash, transaction_data=spend_bundle, guarantee_block=True, seed=b"1245", ) for block in blocks: result, error_code, _ = await b.receive_block(block) assert error_code is None and result == ReceiveBlockResult.NEW_PEAK for block in blocks_fork: result, error_code, _ = await b.receive_block(block) assert error_code is None class TestPreValidation: @pytest.mark.asyncio async def test_pre_validation_fails_bad_blocks(self, empty_blockchain): blocks = bt.get_consecutive_blocks(2) assert (await empty_blockchain.receive_block(blocks[0]))[0] == ReceiveBlockResult.NEW_PEAK block_bad = recursive_replace( blocks[-1], "reward_chain_sub_block.total_iters", blocks[-1].reward_chain_sub_block.total_iters + 1 ) res = await empty_blockchain.pre_validate_blocks_multiprocessing([blocks[0], block_bad]) assert res[0].error is None assert res[1].error is not None @pytest.mark.asyncio async def test_pre_validation(self, empty_blockchain, default_1000_blocks): blocks = default_1000_blocks[:100] start = time.time() n_at_a_time = min(multiprocessing.cpu_count(), 32) times_pv = [] times_rb = [] for i in range(0, len(blocks), n_at_a_time): end_i = min(i + n_at_a_time, len(blocks)) blocks_to_validate = blocks[i:end_i] start_pv = time.time() res = await empty_blockchain.pre_validate_blocks_multiprocessing(blocks_to_validate) end_pv = time.time() times_pv.append(end_pv - start_pv) assert res is not None for n in range(end_i - i): assert res[n] is not None assert res[n].error is None block = blocks_to_validate[n] start_rb = time.time() result, err, _ = await empty_blockchain.receive_block(block, res[n]) end_rb = time.time() times_rb.append(end_rb - start_rb) assert err is None assert result == ReceiveBlockResult.NEW_PEAK log.info( f"Added block {block.sub_block_height} total iters {block.total_iters} " f"new slot? {len(block.finished_sub_slots)}, time {end_rb - start_rb}" ) end = time.time() log.info(f"Total time: {end - start} seconds") log.info(f"Average pv: {sum(times_pv)/(len(blocks)/n_at_a_time)}") log.info(f"Average rb: {sum(times_rb)/(len(blocks))}")
48.088415
120
0.63416
592d342df6c9858c4c94c87ee163aac0c7eacb74
11,556
py
Python
hsequeces_bench.py
bankbiz/Key.Net
5ba46614821e94be1b36d97721bd6c2e5fff9e20
[ "BSD-3-Clause-Clear" ]
162
2019-09-26T09:03:31.000Z
2022-03-29T08:51:44.000Z
keypoint/hsequeces_bench.py
semnan-university-ai/Key.Net
887f595cb7b87e0551d52e34441f61546a9aee97
[ "MIT" ]
14
2019-10-30T07:36:12.000Z
2022-03-23T03:22:19.000Z
keypoint/hsequeces_bench.py
semnan-university-ai/Key.Net
887f595cb7b87e0551d52e34441f61546a9aee97
[ "MIT" ]
36
2019-10-15T10:14:51.000Z
2021-12-08T13:02:28.000Z
import os import argparse import numpy as np import pickle from tqdm import tqdm import HSequences_bench.tools.aux_tools as aux import HSequences_bench.tools.geometry_tools as geo_tools import HSequences_bench.tools.repeatability_tools as rep_tools import HSequences_bench.tools.matching_tools as match_tools from HSequences_bench.tools.HSequences_reader import HSequences_dataset from HSequences_bench.tools.opencv_matcher import OpencvBruteForceMatcher def hsequences_metrics(): parser = argparse.ArgumentParser(description='HSequences Compute Repeatability') parser.add_argument('--data-dir', type=str, default='hpatches-sequences-release/', help='The root path to HSequences dataset.') parser.add_argument('--results-bench-dir', type=str, default='HSequences_bench/results/', help='The output path to save the results.') parser.add_argument('--detector-name', type=str, default='KeyNet_default', help='The name of the detector to compute metrics.') parser.add_argument('--results-dir', type=str, default='extracted_features/', help='The path to the extracted points.') parser.add_argument('--split', type=str, default='view', help='The name of the HPatches (HSequences) split. Use full, debug_view, debug_illum, view or illum.') parser.add_argument('--split-path', type=str, default='HSequences_bench/splits.json', help='The path to the split json file.') parser.add_argument('--top-k-points', type=int, default=1000, help='The number of top points to use for evaluation. Set to None to use all points') parser.add_argument('--overlap', type=float, default=0.6, help='The overlap threshold for a correspondence to be considered correct.') parser.add_argument('--pixel-threshold', type=int, default=5, help='The distance of pixels for a matching correspondence to be considered correct.') parser.add_argument('--dst-to-src-evaluation', type=bool, default=True, help='Order to apply homography to points. Use True for dst to src, False otherwise.') parser.add_argument('--order-coord', type=str, default='xysr', help='The coordinate order that follows the extracted points. Use either xysr or yxsr.') args = parser.parse_args() print(args.detector_name + ': ' + args.split) aux.check_directory(args.results_bench_dir) # create the dataloader data_loader = HSequences_dataset(args.data_dir, args.split, args.split_path) results = aux.create_overlapping_results(args.detector_name, args.overlap) # matching method matcher = OpencvBruteForceMatcher('l2') count_seq = 0 # load data and compute the keypoints for sample_id, sample_data in enumerate(data_loader.extract_hsequences()): sequence = sample_data['sequence_name'] count_seq += 1 image_src = sample_data['im_src'] images_dst = sample_data['images_dst'] h_src_2_dst = sample_data['h_src_2_dst'] h_dst_2_src = sample_data['h_dst_2_src'] print('\nComputing ' + sequence + ' sequence {0} / {1} \n'.format(count_seq, len(data_loader.sequences))) for idx_im in tqdm(range(len(images_dst))): # create the mask to filter out the points outside of the common areas mask_src, mask_dst = geo_tools.create_common_region_masks(h_dst_2_src[idx_im], image_src.shape, images_dst[idx_im].shape) # compute the files paths src_pts_filename = os.path.join(args.results_dir, args.detector_name, 'hpatches-sequences-release', '{}/1.ppm.kpt.npy'.format(sample_data['sequence_name'])) src_dsc_filename = os.path.join(args.results_dir, args.detector_name, 'hpatches-sequences-release', '{}/1.ppm.dsc.npy'.format(sample_data['sequence_name'])) dst_pts_filename = os.path.join(args.results_dir, args.detector_name, 'hpatches-sequences-release', '{}/{}.ppm.kpt.npy'.format(sample_data['sequence_name'], idx_im+2)) dst_dsc_filename = os.path.join(args.results_dir, args.detector_name, 'hpatches-sequences-release', '{}/{}.ppm.dsc.npy'.format(sample_data['sequence_name'], idx_im+2)) if not os.path.isfile(src_pts_filename): print("Could not find the file: " + src_pts_filename) return False if not os.path.isfile(src_dsc_filename): print("Could not find the file: " + src_dsc_filename) return False if not os.path.isfile(dst_pts_filename): print("Could not find the file: " + dst_pts_filename) return False if not os.path.isfile(dst_dsc_filename): print("Could not find the file: " + dst_dsc_filename) return False # load the points src_pts = np.load(src_pts_filename) src_dsc = np.load(src_dsc_filename) dst_pts = np.load(dst_pts_filename) dst_dsc = np.load(dst_dsc_filename) if args.order_coord == 'xysr': src_pts = np.asarray(list(map(lambda x: [x[1], x[0], x[2], x[3]], src_pts))) dst_pts = np.asarray(list(map(lambda x: [x[1], x[0], x[2], x[3]], dst_pts))) # Check Common Points src_idx = rep_tools.check_common_points(src_pts, mask_src) src_pts = src_pts[src_idx] src_dsc = src_dsc[src_idx] dst_idx = rep_tools.check_common_points(dst_pts, mask_dst) dst_pts = dst_pts[dst_idx] dst_dsc = dst_dsc[dst_idx] # Select top K points if args.top_k_points: src_idx = rep_tools.select_top_k(src_pts, args.top_k_points) src_pts = src_pts[src_idx] src_dsc = src_dsc[src_idx] dst_idx = rep_tools.select_top_k(dst_pts, args.top_k_points) dst_pts = dst_pts[dst_idx] dst_dsc = dst_dsc[dst_idx] src_pts = np.asarray(list(map(lambda x: [x[1], x[0], x[2], x[3]], src_pts))) dst_pts = np.asarray(list(map(lambda x: [x[1], x[0], x[2], x[3]], dst_pts))) src_to_dst_pts = geo_tools.apply_homography_to_points( src_pts, h_src_2_dst[idx_im]) dst_to_src_pts = geo_tools.apply_homography_to_points( dst_pts, h_dst_2_src[idx_im]) if args.dst_to_src_evaluation: points_src = src_pts points_dst = dst_to_src_pts else: points_src = src_to_dst_pts points_dst = dst_pts # compute repeatability repeatability_results = rep_tools.compute_repeatability(points_src, points_dst, overlap_err=1-args.overlap, dist_match_thresh=args.pixel_threshold) # match descriptors matches = matcher.match(src_dsc, dst_dsc) matches_np = aux.convert_opencv_matches_to_numpy(matches) matches_inv = matcher.match(dst_dsc, src_dsc) matches_inv_np = aux.convert_opencv_matches_to_numpy(matches_inv) mask = matches_np[:, 0] == matches_inv_np[matches_np[:, 1], 1] matches_np = matches_np[mask] match_score, match_score_corr, num_matches = {}, {}, {} # compute matching based on pixel distance for th_i in range(1, 11): match_score_i, match_score_corr_i, num_matches_i = match_tools.compute_matching_based_distance(points_src, points_dst, matches_np, repeatability_results['total_num_points'], pixel_threshold=th_i, possible_matches=repeatability_results['possible_matches']) match_score[str(th_i)] = match_score_i match_score_corr[str(th_i)] = match_score_corr_i num_matches[str(th_i)] = num_matches_i mma = np.mean([match_score[str(idx)] for idx in match_score]) results['rep_single_scale'].append( repeatability_results['rep_single_scale']) results['rep_multi_scale'].append( repeatability_results['rep_multi_scale']) results['num_points_single_scale'].append( repeatability_results['num_points_single_scale']) results['num_points_multi_scale'].append( repeatability_results['num_points_multi_scale']) results['error_overlap_single_scale'].append( repeatability_results['error_overlap_single_scale']) results['error_overlap_multi_scale'].append( repeatability_results['error_overlap_multi_scale']) results['mma'].append(match_score[str(args.pixel_threshold)]) results['mma_corr'].append(match_score_corr[str(args.pixel_threshold)]) results['num_matches'].append(num_matches[str(args.pixel_threshold)]) results['num_mutual_corresp'].append(len(matches_np)) results['avg_mma'].append(mma) results['num_features'].append(repeatability_results['total_num_points']) # average the results rep_single = np.array(results['rep_single_scale']).mean() rep_multi = np.array(results['rep_multi_scale']).mean() error_overlap_s = np.array(results['error_overlap_single_scale']).mean() error_overlap_m = np.array(results['error_overlap_multi_scale']).mean() mma = np.array(results['mma']).mean() mma_corr = np.array(results['mma_corr']).mean() num_matches = np.array(results['num_matches']).mean() num_mutual_corresp = np.array(results['num_mutual_corresp']).mean() avg_mma = np.array(results['avg_mma']).mean() num_features = np.array(results['num_features']).mean() # Matching Score: Matching Score taking into account all features that have been # detected in any of the two images. # Matching Score (possible matches): Matching Score only taking into account those features that have been # detected in both images. # MMA Score is computed based on the Matching Score (all detected features) print('\n## Overlap @{0}:\n \ #### Rep. Multi: {1:.4f}\n \ #### Rep. Single: {2:.4f}\n \ #### Overlap Multi: {3:.4f}\n \ #### Overlap Single: {4:.4f}\n \ #### MMA: {5:.4f}\n \ #### MMA (possible matches): {6:.4f}\n \ #### Num matches: {7:.4f}\n \ #### Num Mutual Correspondences: {8:.4f}\n \ #### Avg. over Threshold MMA: {9:.4f}\n \ #### Num Feats: {10:.4f}'.format( args.overlap, rep_multi, rep_single, error_overlap_s, error_overlap_m, mma, mma_corr, num_matches, num_mutual_corresp, avg_mma, num_features)) # Store data (serialize) output_file_path = os.path.join(args.results_bench_dir, '{0}_{1}.pickle' .format(args.detector_name, args.split)) with open(output_file_path, 'wb') as handle: pickle.dump(results, handle, protocol=pickle.HIGHEST_PROTOCOL) if __name__ == '__main__': hsequences_metrics()
47.360656
146
0.624351
5bae3e62b32ead986ab1ddb7763be7ffd4563d98
1,246
py
Python
setup.py
ahmadiesa-abu/cloudify-kubernetes-plugin
3f5363e82f12bb97dafee178c972491898f54680
[ "Apache-2.0" ]
null
null
null
setup.py
ahmadiesa-abu/cloudify-kubernetes-plugin
3f5363e82f12bb97dafee178c972491898f54680
[ "Apache-2.0" ]
null
null
null
setup.py
ahmadiesa-abu/cloudify-kubernetes-plugin
3f5363e82f12bb97dafee178c972491898f54680
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2017-2019 Cloudify Platform Ltd. 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 setuptools import setup setup( name='cloudify-kubernetes-plugin', version='2.6.5', author='Cloudify Platform Ltd.', author_email='hello@cloudify.co', description='Plugin provides Kubernetes management possibility', packages=['cloudify_kubernetes', 'cloudify_kubernetes.k8s'], license='LICENSE', install_requires=[ 'cloudify-python-importer==0.1', 'cloudify-common==4.5.5', 'kubernetes==10.0.1', 'pyyaml>=3.12', 'pyasn1>=0.1.7', 'pyasn1-modules>=0.0.5,<0.2.1', 'oauth2client', # used only in GCPServiceAccountAuthentication ] )
34.611111
74
0.698234
65841c48a969f11c93a2932f27057380f030a1f0
1,830
py
Python
venv/Lib/site-packages/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileSampling.py
richung99/digitizePlots
6b408c820660a415a289726e3223e8f558d3e18b
[ "MIT" ]
585
2015-01-12T16:06:47.000Z
2022-03-26T14:51:08.000Z
nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileSampling.py
tamires-consulting/nipype
b7879d75a63b6500b2e7d2c3eba5aa7670339274
[ "Apache-2.0" ]
2,329
2015-01-01T09:56:41.000Z
2022-03-30T14:24:49.000Z
nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileSampling.py
tamires-consulting/nipype
b7879d75a63b6500b2e7d2c3eba5aa7670339274
[ "Apache-2.0" ]
487
2015-01-20T01:04:52.000Z
2022-03-21T21:22:47.000Z
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ..developer import JistLaminarProfileSampling def test_JistLaminarProfileSampling_inputs(): input_map = dict( args=dict( argstr="%s", ), environ=dict( nohash=True, usedefault=True, ), inCortex=dict( argstr="--inCortex %s", extensions=None, ), inIntensity=dict( argstr="--inIntensity %s", extensions=None, ), inProfile=dict( argstr="--inProfile %s", extensions=None, ), null=dict( argstr="--null %s", ), outProfile2=dict( argstr="--outProfile2 %s", hash_files=False, ), outProfilemapped=dict( argstr="--outProfilemapped %s", hash_files=False, ), xDefaultMem=dict( argstr="-xDefaultMem %d", ), xMaxProcess=dict( argstr="-xMaxProcess %d", usedefault=True, ), xPrefExt=dict( argstr="--xPrefExt %s", ), ) inputs = JistLaminarProfileSampling.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value def test_JistLaminarProfileSampling_outputs(): output_map = dict( outProfile2=dict( extensions=None, ), outProfilemapped=dict( extensions=None, ), ) outputs = JistLaminarProfileSampling.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): assert getattr(outputs.traits()[key], metakey) == value
26.521739
67
0.533333
9677eae2ae1c192f3bb5a8e3f2446930f7a144b3
7,790
py
Python
pysnmp/ARISTA-CONFIG-COPY-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
11
2021-02-02T16:27:16.000Z
2021-08-31T06:22:49.000Z
pysnmp/ARISTA-CONFIG-COPY-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
75
2021-02-24T17:30:31.000Z
2021-12-08T00:01:18.000Z
pysnmp/ARISTA-CONFIG-COPY-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module ARISTA-CONFIG-COPY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ARISTA-CONFIG-COPY-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:09:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # aristaProducts, aristaModules, aristaMibs = mibBuilder.importSymbols("ARISTA-SMI-MIB", "aristaProducts", "aristaModules", "aristaMibs") ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint") ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance") Counter32, ModuleIdentity, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, Counter64, NotificationType, Unsigned32, IpAddress, MibIdentifier, Bits, TimeTicks, iso, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "ModuleIdentity", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "Counter64", "NotificationType", "Unsigned32", "IpAddress", "MibIdentifier", "Bits", "TimeTicks", "iso", "ObjectIdentity") TextualConvention, RowStatus, DisplayString, DateAndTime = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "DisplayString", "DateAndTime") aristaConfigCopyMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 30065, 3, 7)) aristaConfigCopyMIB.setRevisions(('2014-08-15 00:00', '2013-02-14 00:00',)) if mibBuilder.loadTexts: aristaConfigCopyMIB.setLastUpdated('201408150000Z') if mibBuilder.loadTexts: aristaConfigCopyMIB.setOrganization('Arista Networks, Inc.') class ConfigCopyState(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4)) namedValues = NamedValues(("inactive", 0), ("scheduled", 1), ("running", 2), ("completed", 3), ("failed", 4)) class ConfigCopyFailureCause(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2)) namedValues = NamedValues(("none", 0), ("unknown", 1), ("timeout", 2)) aristaConfigCopyCommandTable = MibTable((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1), ) if mibBuilder.loadTexts: aristaConfigCopyCommandTable.setStatus('current') aristaConfigCopyCommandEntry = MibTableRow((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1, 1), ).setIndexNames((0, "ARISTA-CONFIG-COPY-MIB", "aristaConfigCopyName"), (0, "ARISTA-CONFIG-COPY-MIB", "aristaConfigCopyId")) if mibBuilder.loadTexts: aristaConfigCopyCommandEntry.setStatus('current') aristaConfigCopyName = MibTableColumn((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))) if mibBuilder.loadTexts: aristaConfigCopyName.setStatus('current') aristaConfigCopyId = MibTableColumn((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1, 1, 2), Unsigned32()) if mibBuilder.loadTexts: aristaConfigCopyId.setStatus('current') aristaConfigCopySourceUri = MibTableColumn((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readcreate") if mibBuilder.loadTexts: aristaConfigCopySourceUri.setStatus('current') aristaConfigCopyDestUri = MibTableColumn((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readcreate") if mibBuilder.loadTexts: aristaConfigCopyDestUri.setStatus('current') aristaConfigCopyState = MibTableColumn((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1, 1, 5), ConfigCopyState()).setMaxAccess("readonly") if mibBuilder.loadTexts: aristaConfigCopyState.setStatus('current') aristaConfigCopyTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1, 1, 6), Unsigned32().clone(60)).setMaxAccess("readcreate") if mibBuilder.loadTexts: aristaConfigCopyTimeout.setStatus('current') aristaConfigCopyTimeStarted = MibTableColumn((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1, 1, 7), DateAndTime()).setMaxAccess("readonly") if mibBuilder.loadTexts: aristaConfigCopyTimeStarted.setStatus('current') aristaConfigCopyTimeCompleted = MibTableColumn((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1, 1, 8), DateAndTime()).setMaxAccess("readonly") if mibBuilder.loadTexts: aristaConfigCopyTimeCompleted.setStatus('current') aristaConfigCopyFailureCause = MibTableColumn((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1, 1, 9), ConfigCopyFailureCause()).setMaxAccess("readonly") if mibBuilder.loadTexts: aristaConfigCopyFailureCause.setStatus('current') aristaConfigCopyFailureMessage = MibTableColumn((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1, 1, 10), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: aristaConfigCopyFailureMessage.setStatus('current') aristaConfigCopyRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 30065, 3, 7, 1, 1, 11), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: aristaConfigCopyRowStatus.setStatus('current') aristaConfigCopyConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 30065, 3, 7, 2)) aristaConfigCopyCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 30065, 3, 7, 2, 1)) aristaConfigCopyGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 30065, 3, 7, 2, 2)) aristaConfigCopyCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 30065, 3, 7, 2, 1, 1)).setObjects(("ARISTA-CONFIG-COPY-MIB", "aristaConfigCopyObjectsGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): aristaConfigCopyCompliance = aristaConfigCopyCompliance.setStatus('current') aristaConfigCopyObjectsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 30065, 3, 7, 2, 2, 1)).setObjects(("ARISTA-CONFIG-COPY-MIB", "aristaConfigCopySourceUri"), ("ARISTA-CONFIG-COPY-MIB", "aristaConfigCopyDestUri"), ("ARISTA-CONFIG-COPY-MIB", "aristaConfigCopyState"), ("ARISTA-CONFIG-COPY-MIB", "aristaConfigCopyTimeout"), ("ARISTA-CONFIG-COPY-MIB", "aristaConfigCopyTimeStarted"), ("ARISTA-CONFIG-COPY-MIB", "aristaConfigCopyTimeCompleted"), ("ARISTA-CONFIG-COPY-MIB", "aristaConfigCopyFailureCause"), ("ARISTA-CONFIG-COPY-MIB", "aristaConfigCopyFailureMessage"), ("ARISTA-CONFIG-COPY-MIB", "aristaConfigCopyRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): aristaConfigCopyObjectsGroup = aristaConfigCopyObjectsGroup.setStatus('current') mibBuilder.exportSymbols("ARISTA-CONFIG-COPY-MIB", aristaConfigCopySourceUri=aristaConfigCopySourceUri, aristaConfigCopyObjectsGroup=aristaConfigCopyObjectsGroup, aristaConfigCopyFailureMessage=aristaConfigCopyFailureMessage, ConfigCopyState=ConfigCopyState, aristaConfigCopyDestUri=aristaConfigCopyDestUri, aristaConfigCopyTimeStarted=aristaConfigCopyTimeStarted, aristaConfigCopyTimeCompleted=aristaConfigCopyTimeCompleted, aristaConfigCopyTimeout=aristaConfigCopyTimeout, aristaConfigCopyName=aristaConfigCopyName, aristaConfigCopyConformance=aristaConfigCopyConformance, PYSNMP_MODULE_ID=aristaConfigCopyMIB, aristaConfigCopyCommandTable=aristaConfigCopyCommandTable, aristaConfigCopyRowStatus=aristaConfigCopyRowStatus, aristaConfigCopyCompliance=aristaConfigCopyCompliance, aristaConfigCopyGroups=aristaConfigCopyGroups, aristaConfigCopyCompliances=aristaConfigCopyCompliances, aristaConfigCopyMIB=aristaConfigCopyMIB, aristaConfigCopyCommandEntry=aristaConfigCopyCommandEntry, aristaConfigCopyId=aristaConfigCopyId, ConfigCopyFailureCause=ConfigCopyFailureCause, aristaConfigCopyState=aristaConfigCopyState, aristaConfigCopyFailureCause=aristaConfigCopyFailureCause)
118.030303
1,173
0.783312
19391e510f1d4c983df94b15ea0b6a7366930d67
1,036
py
Python
problem_4.py
YoussefAli99/Problems-vs-Algorithms
081022d196ec0185374868a4654ec8795cd1cbe3
[ "MIT" ]
null
null
null
problem_4.py
YoussefAli99/Problems-vs-Algorithms
081022d196ec0185374868a4654ec8795cd1cbe3
[ "MIT" ]
null
null
null
problem_4.py
YoussefAli99/Problems-vs-Algorithms
081022d196ec0185374868a4654ec8795cd1cbe3
[ "MIT" ]
null
null
null
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ z,o = 0,0 t = len(input_list) - 1 while o <= t: if input_list[o] == 0: input_list[o], input_list[z] = input_list[z], input_list[o] z += 1 o += 1 elif input_list[o] == 1: o += 1 elif input_list[o] == 2: input_list[o], input_list[t] = input_list[t], input_list[o] t -= 1 return input_list def test_function(test_case): sorted_array = sort_012(test_case) print(sorted_array) if sorted_array == sorted(test_case): print("Pass") else: print("Fail") test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2]) test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1]) test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) test_function([0]) test_function([])
28
94
0.530888
e600abd8b90788d1401b155cee468ad6e556ea1b
2,335
py
Python
Projects_in_Python/Message- I Love You/love.py
vivekagarwal2349/Mini_Python_Projects
96fa28d851cddefa5d9a63823b1a9b04ad6c3e04
[ "MIT" ]
null
null
null
Projects_in_Python/Message- I Love You/love.py
vivekagarwal2349/Mini_Python_Projects
96fa28d851cddefa5d9a63823b1a9b04ad6c3e04
[ "MIT" ]
null
null
null
Projects_in_Python/Message- I Love You/love.py
vivekagarwal2349/Mini_Python_Projects
96fa28d851cddefa5d9a63823b1a9b04ad6c3e04
[ "MIT" ]
null
null
null
#here we are importing the required stuffs - from turtle import color, back, left, forward, right, exitonclick import turtle color("black") back(450) color("orange") # let us start creating the words left(90) forward(100) back(100) right(90) color("black") forward(100) left(90) color("orange") forward(100) back(100) right(90) #we are adjusting the cursor in such a way where in the cursor will write i love you in the given code. color("orange") forward(50) color("black") forward(50) color("orange") forward(50) back(50) left(90) forward(100) right(90) forward(50) right(90) forward(100) left(90) color("black") forward(100) color("orange") left(120) forward(110) back(110) right(60) forward(110) back(110) right(60) color("black") forward(100) # if we observe carefully, there are only two colors, one is black other one is orange. color("orange") forward(50) back(50) left(90) forward(100) right(90) forward(50) back(50) right(90) forward(50) left(90) forward(50) back(50) right(90) forward(50) left(90) forward(50) color("black") forward(150) color("orange") left(90) forward(50) left(45) forward(75) back(75) right(90) forward(75) back(75) left(45) # we are at the middle of the word back(50) right(90) color("black") forward(100) color("orange") forward(50) back(50) left(90) forward(100) right(90) forward(50) right(90) forward(100) left(90) color("black") forward(100) color("orange") back(50) left(90) forward(100) back(100) right(90) forward(50) left(90) forward(107) color("black") pen = turtle.Turtle() # we are done with the cursor part. def curve(): for i in range(200): pen.right(1) pen.forward(1) # what if there is a heart in between the 3 words ?? def heart(): #interesting right? now, let us give the points where we need the heart symbol to be visible pen.fillcolor('red') pen.begin_fill() pen.left(140) pen.forward(250) curve() pen.left(120) curve() pen.forward(112) pen.end_fill() heart() def txt(x="" ): pen.up() pen.setpos(-70, 60) pen.down() pen.color('lightgreen') pen.write(x, font=("Verdana", 10, "")) # that's it we are done. txt() pen.ht() exitonclick()
15.671141
104
0.6394
239ddaf4723f9d579e4b033891462be6213efdc4
698
py
Python
venv/Scripts/rst2html.py
muatahunt/django_cityloc_pkg_muatahunt
68074cc3d96ef183b350c1b6492a7c0f7c2524b8
[ "MIT" ]
null
null
null
venv/Scripts/rst2html.py
muatahunt/django_cityloc_pkg_muatahunt
68074cc3d96ef183b350c1b6492a7c0f7c2524b8
[ "MIT" ]
null
null
null
venv/Scripts/rst2html.py
muatahunt/django_cityloc_pkg_muatahunt
68074cc3d96ef183b350c1b6492a7c0f7c2524b8
[ "MIT" ]
null
null
null
#!C:\Users\Name\Desktop\Nucamp\Python\3-DevOps\week4\github_packaging\django_cityloc_pkg_muatahunt\venv\Scripts\python.exe # $Id: rst2html.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing HTML. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates (X)HTML documents from standalone reStructuredText ' 'sources. ' + default_description) publish_cmdline(writer_name='html', description=description)
29.083333
122
0.755014
1485ecc01b16979a783502985855a829802807bd
17,691
py
Python
scipy/linalg/basic.py
jasonmccampbell/scipy-refactor
52708e04bca51e7043248d56383780b1e51e0d8f
[ "BSD-3-Clause" ]
8
2015-10-07T00:37:32.000Z
2022-01-21T17:02:33.000Z
scipy/linalg/basic.py
enthought/scipy-refactor
52708e04bca51e7043248d56383780b1e51e0d8f
[ "BSD-3-Clause" ]
null
null
null
scipy/linalg/basic.py
enthought/scipy-refactor
52708e04bca51e7043248d56383780b1e51e0d8f
[ "BSD-3-Clause" ]
8
2015-05-09T14:23:57.000Z
2018-11-15T05:56:00.000Z
# # Author: Pearu Peterson, March 2002 # # w/ additions by Travis Oliphant, March 2002 __all__ = ['solve', 'solve_triangular', 'solveh_banded', 'solve_banded', 'inv', 'det', 'lstsq', 'pinv', 'pinv2'] from numpy import asarray, zeros, sum, conjugate, dot, transpose, \ asarray_chkfinite, single import numpy from flinalg import get_flinalg_funcs from lapack import get_lapack_funcs from misc import LinAlgError, _datacopied from scipy.linalg import calc_lwork from funcinfo import get_func_info import decomp_svd # Linear equations def solve(a, b, sym_pos=False, lower=False, overwrite_a=False, overwrite_b=False, debug=False): """Solve the equation a x = b for x Parameters ---------- a : array, shape (M, M) b : array, shape (M,) or (M, N) sym_pos : boolean Assume a is symmetric and positive definite lower : boolean Use only data contained in the lower triangle of a, if sym_pos is true. Default is to use upper triangle. overwrite_a : boolean Allow overwriting data in a (may enhance performance) overwrite_b : boolean Allow overwriting data in b (may enhance performance) Returns ------- x : array, shape (M,) or (M, N) depending on b Solution to the system a x = b Raises LinAlgError if a is singular """ a1, b1 = map(asarray_chkfinite,(a,b)) if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError('expected square matrix') if a1.shape[0] != b1.shape[0]: raise ValueError('incompatible dimensions') overwrite_a = overwrite_a or _datacopied(a1, a) overwrite_b = overwrite_b or _datacopied(b1, b) if debug: print 'solve:overwrite_a=',overwrite_a print 'solve:overwrite_b=',overwrite_b if sym_pos: posv, = get_lapack_funcs(('posv',), (a1,b1)) c, x, info = posv(a1, b1, lower=lower, overwrite_a=overwrite_a, overwrite_b=overwrite_b) else: gesv, = get_lapack_funcs(('gesv',), (a1,b1)) lu, piv, x, info = gesv(a1, b1, overwrite_a=overwrite_a, overwrite_b=overwrite_b) if info == 0: return x if info > 0: raise LinAlgError("singular matrix") raise ValueError('illegal value in %d-th argument of internal gesv|posv' % -info) def solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False, overwrite_b=False, debug=False): """Solve the equation `a x = b` for `x`, assuming a is a triangular matrix. Parameters ---------- a : array, shape (M, M) b : array, shape (M,) or (M, N) lower : boolean Use only data contained in the lower triangle of a. Default is to use upper triangle. trans : {0, 1, 2, 'N', 'T', 'C'} Type of system to solve: ======== ========= trans system ======== ========= 0 or 'N' a x = b 1 or 'T' a^T x = b 2 or 'C' a^H x = b ======== ========= unit_diagonal : boolean If True, diagonal elements of A are assumed to be 1 and will not be referenced. overwrite_b : boolean Allow overwriting data in b (may enhance performance) Returns ------- x : array, shape (M,) or (M, N) depending on b Solution to the system a x = b Raises ------ LinAlgError If a is singular """ a1, b1 = map(asarray_chkfinite,(a,b)) if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError('expected square matrix') if a1.shape[0] != b1.shape[0]: raise ValueError('incompatible dimensions') overwrite_b = overwrite_b or _datacopied(b1, b) if debug: print 'solve:overwrite_b=',overwrite_b trans = {'N': 0, 'T': 1, 'C': 2}.get(trans, trans) trtrs, = get_lapack_funcs(('trtrs',), (a1,b1)) x, info = trtrs(a1, b1, overwrite_b=overwrite_b, lower=lower, trans=trans, unitdiag=unit_diagonal) if info == 0: return x if info > 0: raise LinAlgError("singular matrix: resolution failed at diagonal %s" % (info-1)) raise ValueError('illegal value in %d-th argument of internal trtrs') def solve_banded((l, u), ab, b, overwrite_ab=False, overwrite_b=False, debug=False): """Solve the equation a x = b for x, assuming a is banded matrix. The matrix a is stored in ab using the matrix diagonal orded form:: ab[u + i - j, j] == a[i,j] Example of ab (shape of a is (6,6), u=1, l=2):: * a01 a12 a23 a34 a45 a00 a11 a22 a33 a44 a55 a10 a21 a32 a43 a54 * a20 a31 a42 a53 * * Parameters ---------- (l, u) : (integer, integer) Number of non-zero lower and upper diagonals ab : array, shape (l+u+1, M) Banded matrix b : array, shape (M,) or (M, K) Right-hand side overwrite_ab : boolean Discard data in ab (may enhance performance) overwrite_b : boolean Discard data in b (may enhance performance) Returns ------- x : array, shape (M,) or (M, K) The solution to the system a x = b """ a1, b1 = map(asarray_chkfinite, (ab, b)) # Validate shapes. if a1.shape[-1] != b1.shape[0]: raise ValueError("shapes of ab and b are not compatible.") if l + u + 1 != a1.shape[0]: raise ValueError("invalid values for the number of lower and upper diagonals:" " l+u+1 (%d) does not equal ab.shape[0] (%d)" % (l+u+1, ab.shape[0])) overwrite_b = overwrite_b or _datacopied(b1, b) gbsv, = get_lapack_funcs(('gbsv',), (a1, b1)) a2 = zeros((2*l+u+1, a1.shape[1]), dtype=get_func_info(gbsv).dtype) a2[l:,:] = a1 lu, piv, x, info = gbsv(l, u, a2, b1, overwrite_ab=True, overwrite_b=overwrite_b) if info == 0: return x if info > 0: raise LinAlgError("singular matrix") raise ValueError('illegal value in %d-th argument of internal gbsv' % -info) def solveh_banded(ab, b, overwrite_ab=False, overwrite_b=False, lower=False): """Solve equation a x = b. a is Hermitian positive-definite banded matrix. The matrix a is stored in ab either in lower diagonal or upper diagonal ordered form: ab[u + i - j, j] == a[i,j] (if upper form; i <= j) ab[ i - j, j] == a[i,j] (if lower form; i >= j) Example of ab (shape of a is (6,6), u=2):: upper form: * * a02 a13 a24 a35 * a01 a12 a23 a34 a45 a00 a11 a22 a33 a44 a55 lower form: a00 a11 a22 a33 a44 a55 a10 a21 a32 a43 a54 * a20 a31 a42 a53 * * Cells marked with * are not used. Parameters ---------- ab : array, shape (u + 1, M) Banded matrix b : array, shape (M,) or (M, K) Right-hand side overwrite_ab : boolean Discard data in ab (may enhance performance) overwrite_b : boolean Discard data in b (may enhance performance) lower : boolean Is the matrix in the lower form. (Default is upper form) Returns ------- x : array, shape (M,) or (M, K) The solution to the system a x = b """ ab, b = map(asarray_chkfinite, (ab, b)) # Validate shapes. if ab.shape[-1] != b.shape[0]: raise ValueError("shapes of ab and b are not compatible.") pbsv, = get_lapack_funcs(('pbsv',), (ab, b)) c, x, info = pbsv(ab, b, lower=lower, overwrite_ab=overwrite_ab, overwrite_b=overwrite_b) if info > 0: raise LinAlgError("%d-th leading minor not positive definite" % info) if info < 0: raise ValueError('illegal value in %d-th argument of internal pbsv' % -info) return x # matrix inversion def inv(a, overwrite_a=False): """ Compute the inverse of a matrix. Parameters ---------- a : array_like Square matrix to be inverted. overwrite_a : bool, optional Discard data in `a` (may improve performance). Default is False. Returns ------- ainv : ndarray Inverse of the matrix `a`. Raises ------ LinAlgError : If `a` is singular. ValueError : If `a` is not square, or not 2-dimensional. Examples -------- >>> a = np.array([[1., 2.], [3., 4.]]) >>> sp.linalg.inv(a) array([[-2. , 1. ], [ 1.5, -0.5]]) >>> np.dot(a, sp.linalg.inv(a)) array([[ 1., 0.], [ 0., 1.]]) """ a1 = asarray_chkfinite(a) if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError('expected square matrix') overwrite_a = overwrite_a or _datacopied(a1, a) #XXX: I found no advantage or disadvantage of using finv. ## finv, = get_flinalg_funcs(('inv',),(a1,)) ## if finv is not None: ## a_inv,info = finv(a1,overwrite_a=overwrite_a) ## if info==0: ## return a_inv ## if info>0: raise LinAlgError, "singular matrix" ## if info<0: raise ValueError,\ ## 'illegal value in %d-th argument of internal inv.getrf|getri'%(-info) getrf, getri = get_lapack_funcs(('getrf','getri'), (a1,)) getrf_info = get_func_info(getrf) getri_info = get_func_info(getri) #XXX: C ATLAS versions of getrf/i have rowmajor=1, this could be # exploited for further optimization. But it will be probably # a mess. So, a good testing site is required before trying # to do that. if (getrf_info.module_name[:7] == 'clapack' != getri_info.module_name[:7]): # ATLAS 3.2.1 has getrf but not getri. lu, piv, info = getrf(transpose(a1), rowmajor=0, overwrite_a=overwrite_a) lu = transpose(lu) else: lu, piv, info = getrf(a1, overwrite_a=overwrite_a) if info == 0: if getri_info.module_name[:7] == 'flapack': lwork = calc_lwork.getri(getri_info.prefix, a1.shape[0]) lwork = lwork[1] # XXX: the following line fixes curious SEGFAULT when # benchmarking 500x500 matrix inverse. This seems to # be a bug in LAPACK ?getri routine because if lwork is # minimal (when using lwork[0] instead of lwork[1]) then # all tests pass. Further investigation is required if # more such SEGFAULTs occur. lwork = int(1.01 * lwork) inv_a, info = getri(lu, piv, lwork=lwork, overwrite_lu=1) else: # clapack inv_a, info = getri(lu, piv, overwrite_lu=1) if info > 0: raise LinAlgError("singular matrix") if info < 0: raise ValueError('illegal value in %d-th argument of internal ' 'getrf|getri' % -info) return inv_a ### Determinant def det(a, overwrite_a=False): """Compute the determinant of a matrix Parameters ---------- a : array, shape (M, M) Returns ------- det : float or complex Determinant of a Notes ----- The determinant is computed via LU factorization, LAPACK routine z/dgetrf. """ a1 = asarray_chkfinite(a) if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError('expected square matrix') overwrite_a = overwrite_a or _datacopied(a1, a) fdet, = get_flinalg_funcs(('det',), (a1,)) a_det, info = fdet(a1, overwrite_a=overwrite_a) if info < 0: raise ValueError('illegal value in %d-th argument of internal ' 'det.getrf' % -info) return a_det ### Linear Least Squares def lstsq(a, b, cond=None, overwrite_a=False, overwrite_b=False): """ Compute least-squares solution to equation Ax = b. Compute a vector x such that the 2-norm ``|b - A x|`` is minimized. Parameters ---------- a : array, shape (M, N) Left hand side matrix (2-D array). b : array, shape (M,) or (M, K) Right hand side matrix or vector (1-D or 2-D array). cond : float, optional Cutoff for 'small' singular values; used to determine effective rank of a. Singular values smaller than ``rcond * largest_singular_value`` are considered zero. overwrite_a : bool, optional Discard data in `a` (may enhance performance). Default is False. overwrite_b : bool, optional Discard data in `b` (may enhance performance). Default is False. Returns ------- x : array, shape (N,) or (N, K) depending on shape of b Least-squares solution. residues : ndarray, shape () or (1,) or (K,) Sums of residues, squared 2-norm for each column in ``b - a x``. If rank of matrix a is < N or > M this is an empty array. If b was 1-D, this is an (1,) shape array, otherwise the shape is (K,). rank : int Effective rank of matrix `a`. s : array, shape (min(M,N),) Singular values of `a`. The condition number of a is ``abs(s[0]/s[-1])``. Raises ------ LinAlgError : If computation does not converge. See Also -------- optimize.nnls : linear least squares with non-negativity constraint """ a1, b1 = map(asarray_chkfinite, (a, b)) if len(a1.shape) != 2: raise ValueError('expected matrix') m, n = a1.shape if len(b1.shape) == 2: nrhs = b1.shape[1] else: nrhs = 1 if m != b1.shape[0]: raise ValueError('incompatible dimensions') gelss, = get_lapack_funcs(('gelss',), (a1, b1)) gelss_info = get_func_info(gelss) if n > m: # need to extend b matrix as it will be filled with # a larger solution matrix b2 = zeros((n, nrhs), dtype=gelss_info.dtype) if len(b1.shape) == 2: b2[:m,:] = b1 else: b2[:m,0] = b1 b1 = b2 overwrite_a = overwrite_a or _datacopied(a1, a) overwrite_b = overwrite_b or _datacopied(b1, b) if gelss_info.module_name[:7] == 'flapack': lwork = calc_lwork.gelss(gelss_info.prefix, m, n, nrhs)[1] v, x, s, rank, info = gelss(a1, b1, cond=cond, lwork=lwork, overwrite_a=overwrite_a, overwrite_b=overwrite_b) else: raise NotImplementedError('calling gelss from %s' % get_func_info(gelss).module_name) if info > 0: raise LinAlgError("SVD did not converge in Linear Least Squares") if info < 0: raise ValueError('illegal value in %d-th argument of internal gelss' % -info) resids = asarray([], dtype=x.dtype) if n < m: x1 = x[:n] if rank == n: resids = sum(abs(x[n:])**2, axis=0) x = x1 return x, resids, rank, s def pinv(a, cond=None, rcond=None): """Compute the (Moore-Penrose) pseudo-inverse of a matrix. Calculate a generalized inverse of a matrix using a least-squares solver. Parameters ---------- a : array, shape (M, N) Matrix to be pseudo-inverted cond, rcond : float Cutoff for 'small' singular values in the least-squares solver. Singular values smaller than rcond*largest_singular_value are considered zero. Returns ------- B : array, shape (N, M) Raises LinAlgError if computation does not converge Examples -------- >>> from numpy import * >>> a = random.randn(9, 6) >>> B = linalg.pinv(a) >>> allclose(a, dot(a, dot(B, a))) True >>> allclose(B, dot(B, dot(a, B))) True """ a = asarray_chkfinite(a) b = numpy.identity(a.shape[0], dtype=a.dtype) if rcond is not None: cond = rcond return lstsq(a, b, cond=cond)[0] def pinv2(a, cond=None, rcond=None): """Compute the (Moore-Penrose) pseudo-inverse of a matrix. Calculate a generalized inverse of a matrix using its singular-value decomposition and including all 'large' singular values. Parameters ---------- a : array, shape (M, N) Matrix to be pseudo-inverted cond, rcond : float or None Cutoff for 'small' singular values. Singular values smaller than rcond*largest_singular_value are considered zero. If None or -1, suitable machine precision is used. Returns ------- B : array, shape (N, M) Raises LinAlgError if SVD computation does not converge Examples -------- >>> from numpy import * >>> a = random.randn(9, 6) >>> B = linalg.pinv2(a) >>> allclose(a, dot(a, dot(B, a))) True >>> allclose(B, dot(B, dot(a, B))) True """ a = asarray_chkfinite(a) u, s, vh = decomp_svd.svd(a) t = u.dtype.char if rcond is not None: cond = rcond if cond in [None,-1]: eps = numpy.finfo(float).eps feps = numpy.finfo(single).eps _array_precision = {'f': 0, 'd': 1, 'F': 0, 'D': 1} cond = {0: feps*1e3, 1: eps*1e6}[_array_precision[t]] m, n = a.shape cutoff = cond*numpy.maximum.reduce(s) psigma = zeros((m, n), t) for i in range(len(s)): if s[i] > cutoff: psigma[i,i] = 1.0/conjugate(s[i]) #XXX: use lapack/blas routines for dot return transpose(conjugate(dot(dot(u,psigma),vh)))
32.224044
93
0.567916
08f48f78e32c8607808e34b785c090af34ff0e63
5,172
py
Python
flexget/plugins/sites/cpasbien.py
davidcollom/Flexget
cd763e04afdf6da8f1673dd567a42d55d4cb3b6c
[ "MIT" ]
1
2021-03-24T11:54:01.000Z
2021-03-24T11:54:01.000Z
flexget/plugins/sites/cpasbien.py
davidcollom/Flexget
cd763e04afdf6da8f1673dd567a42d55d4cb3b6c
[ "MIT" ]
null
null
null
flexget/plugins/sites/cpasbien.py
davidcollom/Flexget
cd763e04afdf6da8f1673dd567a42d55d4cb3b6c
[ "MIT" ]
null
null
null
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from future.moves.urllib.parse import quote_plus import logging import re from flexget import plugin from flexget.entry import Entry from flexget.event import event from flexget.utils import requests from flexget.utils.soup import get_soup from flexget.utils.search import normalize_unicode from flexget.utils.tools import parse_filesize log = logging.getLogger('search_cpasbien') session = requests.Session() class SearchCPASBIEN(object): schema = { 'type': 'object', 'properties': { 'category': { 'type': 'string', 'enum': ['films', 'series', 'musique', 'films-french', '720p', 'series-francaise', 'films-dvdrip', 'all', 'films-vostfr', '1080p', 'series-vostfr', 'ebook'] }, }, 'required': ['category'], 'additionalProperties': False } @plugin.internet(log) def search(self, task, entry, config): """CPASBIEN search plugin Config example: tv_search_cpasbien: discover: what: - trakt_list: username: xxxxxxx api_key: xxxxxxx series: watchlist from: - cpasbien: category: "series-vostfr" interval: 1 day ignore_estimations: yes Category is ONE of: all films series musique films-french 1080p 720p series-francaise films-dvdrip films-vostfr series-vostfr ebook """ base_url = 'http://www.cpasbien.io' entries = set() for search_string in entry.get('search_strings', [entry['title']]): search_string = search_string.replace(' ', '-').lower() search_string = search_string.replace('(', '') search_string = search_string.replace(')', '') query = normalize_unicode(search_string) query_url_fragment = quote_plus(query.encode('utf-8')) # http://www.cpasbien.pe/recherche/ncis.html if config['category'] == 'all': str_url = (base_url, 'recherche', query_url_fragment) url = '/'.join(str_url) else: category_url_fragment = '%s' % config['category'] str_url = (base_url, 'recherche', category_url_fragment, query_url_fragment) url = '/'.join(str_url) log.debug('search url: %s' % url + '.html') # GET URL f = task.requests.get(url + '.html').content soup = get_soup(f) if soup.findAll(text=re.compile(' 0 torrents')): log.debug('search returned no results') else: nextpage = 0 while (nextpage >= 0): if (nextpage > 0): newurl = url + '/page-' + str(nextpage) log.debug('-----> NEXT PAGE : %s' % newurl) f1 = task.requests.get(newurl).content soup = get_soup(f1) for result in soup.findAll('div', attrs={'class': re.compile('ligne')}): entry = Entry() link = result.find('a', attrs={'href': re.compile('dl-torrent')}) entry['title'] = link.contents[0] # REWRITE URL page_link = link.get('href') link_rewrite = page_link.split('/') # get last value in array remove .html and replace by .torrent endlink = link_rewrite[-1] str_url = (base_url, '/telechargement/', endlink[:-5], '.torrent') entry['url'] = ''.join(str_url) log.debug('Title: %s | DL LINK: %s' % (entry['title'], entry['url'])) entry['torrent_seeds'] = (int(result.find('span', attrs={'class': re.compile('seed')}).text)) entry['torrent_leeches'] = (int(result.find('div', attrs={'class': re.compile('down')}).text)) size = result.find('div', attrs={'class': re.compile('poid')}).text entry['content_size'] = parse_filesize(size, si=False) if (entry['torrent_seeds'] > 0): entries.add(entry) else: log.debug('0 SEED, not adding entry') if soup.find(text=re.compile('Suiv')): nextpage += 1 else: nextpage = -1 return entries @event('plugin.register') def register_plugin(): plugin.register(SearchCPASBIEN, 'cpasbien', groups=['search'], api_ver=2)
38.311111
118
0.49478
a7332523db26dfe9c695ddb1723177bb76c57101
111
py
Python
Bases/Practice/Solution/TicTacToe/Player.py
PierreAnken/TrainingPython
a788090d335d8d940838d17e68f263ba4aa013d4
[ "MIT" ]
null
null
null
Bases/Practice/Solution/TicTacToe/Player.py
PierreAnken/TrainingPython
a788090d335d8d940838d17e68f263ba4aa013d4
[ "MIT" ]
null
null
null
Bases/Practice/Solution/TicTacToe/Player.py
PierreAnken/TrainingPython
a788090d335d8d940838d17e68f263ba4aa013d4
[ "MIT" ]
1
2021-12-07T10:53:43.000Z
2021-12-07T10:53:43.000Z
class Player: def __init__(self, name: str, sign: str): self.name = name self.sign = sign
18.5
45
0.576577
2e184de571210a4e4dcfab2bd59b86a9f19df7b3
167
py
Python
reformat_gherkin/ast_node/doc_string.py
rayjolt/reformat-gherkin
4869bd5b3a904283171f8a49849d53e8e9e81c18
[ "MIT" ]
null
null
null
reformat_gherkin/ast_node/doc_string.py
rayjolt/reformat-gherkin
4869bd5b3a904283171f8a49849d53e8e9e81c18
[ "MIT" ]
null
null
null
reformat_gherkin/ast_node/doc_string.py
rayjolt/reformat-gherkin
4869bd5b3a904283171f8a49849d53e8e9e81c18
[ "MIT" ]
null
null
null
from ._base import prepare from .location import LocationMixin @prepare class DocString(LocationMixin): content: str def __iter__(self): yield self
15.181818
35
0.724551
e89cafdde490cb1a0cb94bd31e995a45ddf87570
174
py
Python
104-maximum-depth-of-binary-tree/104-maximum-depth-of-binary-tree.py
Atri10/Leet-code---Atri_Patel
49fc59b9147a44ab04a66128fbb2ef259b5f7b7c
[ "MIT" ]
1
2021-10-10T20:21:18.000Z
2021-10-10T20:21:18.000Z
104-maximum-depth-of-binary-tree/104-maximum-depth-of-binary-tree.py
Atri10/Leet-code---Atri_Patel
49fc59b9147a44ab04a66128fbb2ef259b5f7b7c
[ "MIT" ]
null
null
null
104-maximum-depth-of-binary-tree/104-maximum-depth-of-binary-tree.py
Atri10/Leet-code---Atri_Patel
49fc59b9147a44ab04a66128fbb2ef259b5f7b7c
[ "MIT" ]
null
null
null
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if not root:return 0 return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
43.5
72
0.678161
29c541cfb13bfb1add79b7909c4b1aab18641aab
12,721
py
Python
python/paddle/distributed/fleet/utils/recompute.py
ucsk/Paddle
1d4566592287d84b39f7f3cab2f00e9d3f993d92
[ "Apache-2.0" ]
2
2022-01-04T10:51:58.000Z
2022-01-10T12:29:08.000Z
python/paddle/distributed/fleet/utils/recompute.py
ucsk/Paddle
1d4566592287d84b39f7f3cab2f00e9d3f993d92
[ "Apache-2.0" ]
1
2020-09-08T01:45:28.000Z
2020-09-08T01:45:28.000Z
python/paddle/distributed/fleet/utils/recompute.py
ucsk/Paddle
1d4566592287d84b39f7f3cab2f00e9d3f993d92
[ "Apache-2.0" ]
5
2021-12-10T11:20:06.000Z
2022-02-18T05:18:12.000Z
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import paddle from paddle.fluid import core from paddle.autograd import PyLayer from paddle.fluid import framework import contextlib import logging logger = logging.getLogger(__name__) formatter = logging.Formatter( fmt='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') ch = logging.StreamHandler() ch.setFormatter(formatter) logger.addHandler(ch) __all__ = [] def detach_variable(inputs): out = [] for inp in inputs: if not isinstance(inp, core.VarBase): out.append(inp) continue x = inp.detach() x.stop_gradient = inp.stop_gradient out.append(x) return tuple(out) def check_recompute_necessary(inputs): if not any(input_.stop_gradient == False for input_ in inputs if isinstance(input_, paddle.Tensor)): logger.warn( "[Recompute]: None of the inputs to current recompute block need grad, " "therefore there is NO need to recompute this block in backward !") @contextlib.contextmanager def swith_rng_state(rng_state): orig_cuda_rng_state = paddle.get_cuda_rng_state() paddle.set_cuda_rng_state(rng_state) try: yield finally: paddle.set_cuda_rng_state(orig_cuda_rng_state) class RecomputeFunction(PyLayer): @staticmethod def forward(ctx, run_function, preserve_rng_state, *args): check_recompute_necessary(args) # store for recomputing ctx.run_function = run_function ctx.preserve_rng_state = preserve_rng_state # NOTE the number of outputs of backward() should be equal to the number of tensors in forward()'s input # the order of tensors in backward()'s output should be the same as tensors in forward()'s input # None tensor inputs will be filtered in backward inputs. # save input for backward ctx.inputs = [] ctx.tensor_indices = [] tensor_inputs = [] for i, arg in enumerate(args): if paddle.is_tensor(arg): tensor_inputs.append(arg) ctx.tensor_indices.append(i) ctx.inputs.append(None) else: ctx.inputs.append(arg) ctx.save_for_backward(*tensor_inputs) # NOTE recompute with restore RNG only support one senario where one process for one cuda gpu. # one process with multiple gpu and mix-gpu-cpu senarios are not support if ctx.preserve_rng_state: cur_device = paddle.get_device() if 'gpu:' not in cur_device: raise RuntimeError( "Recompute with RNG perserve is not support current device: {}.". format(cur_device)) ctx.fw_cuda_rng_state = paddle.get_cuda_rng_state() # TODO support AMP tracer = framework._dygraph_tracer() ctx.is_fw_autocast = False if tracer._amp_level == core.AmpLevel.O0 else True if tracer._amp_level == core.AmpLevel.O2: ctx.amp_level = 'O2' elif tracer._amp_level in (core.AmpLevel.O1, core.AmpLevel.O0): ctx.amp_level = 'O1' else: raise ValueError("unsupported amp level: {}".format( tracer._amp_level)) ctx.amp_white_list, ctx.amp_black_list = tracer._get_amp_op_list() with paddle.no_grad(): outputs = run_function(*args) return outputs @staticmethod def backward(ctx, *args): with paddle.fluid.dygraph.guard(): # TODO need to check the recompute calling is vaild or not # Restore inputs inputs = list(ctx.inputs) tensor_indices = ctx.tensor_indices tensors = ctx.saved_tensor() for i, idx in enumerate(tensor_indices): inputs[idx] = tensors[i] # paddle.enable_grad() tracer = framework._dygraph_tracer() tracer._has_grad = True # NOTE support AMP # need restore auto_cast state as well as w/b list if ctx.preserve_rng_state: with swith_rng_state(ctx.fw_cuda_rng_state): with paddle.amp.auto_cast( enable=ctx.is_fw_autocast, custom_white_list=ctx.amp_white_list, custom_black_list=ctx.amp_black_list, level=ctx.amp_level): detached_inputs = detach_variable(tuple(inputs)) outputs = ctx.run_function(*detached_inputs) else: with paddle.amp.auto_cast( enable=ctx.is_fw_autocast, custom_white_list=ctx.amp_white_list, custom_black_list=ctx.amp_black_list, level=ctx.amp_level): detached_inputs = detach_variable(tuple(inputs)) outputs = ctx.run_function(*detached_inputs) if isinstance(outputs, core.VarBase): outputs = (outputs, ) assert len(outputs) == len(args) # run backward() with only tensor that requires grad forward_outputs_with_grad = [] # NOTE In Transformer-like network, if user put the attention mask into the recompute segment output, # pylayer will force the stop_gradient of attention mask to be False, which will make the number of # tensor that need grad does not match. # the following backward_inputs_with_grad is used to avoid this case. backward_inputs_with_grad = [] for i in range(len(outputs)): if isinstance(outputs[i], core.VarBase) and not outputs[i].stop_gradient: forward_outputs_with_grad.append(outputs[i]) backward_inputs_with_grad.append(args[i]) if len(forward_outputs_with_grad) == 0: raise RuntimeError( "none of output has requires_grad=True, this recompute() is not necessary" ) # actually backward paddle.autograd.backward(forward_outputs_with_grad, backward_inputs_with_grad) grads = list(inp._grad_ivar() for inp in detached_inputs if isinstance(inp, core.VarBase)) return grads def recompute(function, *args, **kwargs): """ recompute intermediate activations to save then memory. Parameters: function(paddle.nn.Sequential): layer of sequence of layers that describes part of forward pass of the model whose intermediate activations will be released to save memory in forward stage and will be recomputed in backward stage for gradient calculation. *args(Tensor): inputs to the function. **kwargs(Dict): Kwargs should only contain the key-value pair of preserve_rng_state, which is used to indicate whether to save the forward rng. If it is True, then the last forward rng value will be restored when the forward recalculation of backpropagation is performed. The default preserve_rng_state is True. Returns: Output of function on args. Examples: .. code-block:: python import numpy as np import paddle from paddle.distributed.fleet.utils import recompute import random # required: gpu def get_fc_block(block_idx, input_size, is_last=False): block_name = "block_" + str(block_idx) block = paddle.nn.Sequential( (block_name + "_fc_0", paddle.nn.Linear(input_size, input_size, bias_attr=False)), (block_name + "_dropout", paddle.nn.Dropout(p=0.5)), (block_name + "_relu_1", paddle.nn.ReLU()), (block_name + "_fc_1", paddle.nn.Linear(input_size, input_size, bias_attr=False)), (block_name + "_relu_2", paddle.nn.ReLU()), ) if is_last: block.add_sublayer( block_name + "_fc_2", paddle.nn.Linear( input_size, 1, bias_attr=False ) ) else: block.add_sublayer( block_name + "_fc_2", paddle.nn.Linear(input_size, input_size, bias_attr=False) ) return block class Naive_fc_net(paddle.nn.Layer): def __init__(self, input_size=10, recompute_blocks=[1, 3], recompute_kwargs={}): super(Naive_fc_net, self).__init__() self.recompute_blocks = recompute_blocks self.recompute_kwargs = recompute_kwargs self.runfunc0 = get_fc_block(0, input_size, is_last=False) self.runfunc1 = get_fc_block(1, input_size, is_last=False) self.runfunc2 = get_fc_block(2, input_size, is_last=False) self.runfunc3 = get_fc_block(3, input_size, is_last=False) self.runfunc4 = get_fc_block(4, input_size, is_last=True) self.total_func = [self.runfunc0, self.runfunc1, self.runfunc2, self.runfunc3, self.runfunc4] def forward(self, inputs): nums = len(self.total_func) for i in range(nums): if i in self.recompute_blocks: inputs = recompute(self.total_func[i], inputs, **{"preserve_rng_state": True}) else: inputs = self.total_func[i](inputs) return inputs def run_model(cuda_state, recompute_block=[], recompute_kwargs={}): gen = paddle.seed(10) gen.manual_seed(10) np.random.seed(10) random.seed(10) if cuda_state: paddle.set_cuda_rng_state(cuda_state) batch_size, input_size = 1, 10 model = Naive_fc_net( input_size, recompute_blocks=recompute_block, recompute_kwargs=recompute_kwargs) optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) loss_ = [] param_ = [] grad_ = [] for _ in range(5): x_data = np.random.randn(batch_size, input_size).astype(np.float32) x = paddle.to_tensor(x_data) y_pred = model(x) loss = y_pred.mean() loss_.append(np.asarray(loss).tolist()) loss.backward() optimizer.step() param_.append(np.asarray(model.parameters()[9]).tolist()) grad_.append(np.asarray(model.parameters()[3]._grad_ivar()).tolist()) optimizer.clear_grad() return loss_, param_, grad_ cuda_state = paddle.get_cuda_rng_state() # without recompute loss_ref, param_ref, grad_ref = run_model( cuda_state, recompute_block=[] ) loss, param, grad = run_model(cuda_state, recompute_block=[1, 2]) print("normal_loss: {}, recompute_loss: {}".format(loss_ref, loss)) # The result of the recompute_loss should be the same as the normal_loss. """ # Hack to mix *args with **kwargs in a python 2.7-compliant way preserve = kwargs.pop('preserve_rng_state', True) if kwargs: raise ValueError("Unexpected keyword arguments: " + ",".join( arg for arg in kwargs)) return RecomputeFunction.apply(function, preserve, *args)
41.571895
118
0.57975
ebb45d136800e7f29e236c0c0336318158b9c6f1
327
py
Python
lagom/agents/__init__.py
lkylych/lagom
64777be7f09136072a671c444b5b3fbbcb1b2f18
[ "MIT" ]
null
null
null
lagom/agents/__init__.py
lkylych/lagom
64777be7f09136072a671c444b5b3fbbcb1b2f18
[ "MIT" ]
null
null
null
lagom/agents/__init__.py
lkylych/lagom
64777be7f09136072a671c444b5b3fbbcb1b2f18
[ "MIT" ]
null
null
null
from .base_agent import BaseAgent from .random_agent import RandomAgent from .reinforce_agent import REINFORCEAgent from .actor_critic_agent import ActorCriticAgent #from lagom.agents.a2c_agent import A2CAgent #from lagom.agents.reinforce_agent import REINFORCEAgent #rom lagom.agents.actor_critic_agent import ActorCriticAgent
46.714286
60
0.877676
11fa402140c4eca3a6b55eaf1ef14756db1a68de
1,554
py
Python
A_source_code/generalcode/trunk/hydraulic_load.py
vanHoek-dgnm/CARBON-DISC
3ecd5f4efba5e032d43679ee977064d6b25154a9
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
A_source_code/generalcode/trunk/hydraulic_load.py
vanHoek-dgnm/CARBON-DISC
3ecd5f4efba5e032d43679ee977064d6b25154a9
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
A_source_code/generalcode/trunk/hydraulic_load.py
vanHoek-dgnm/CARBON-DISC
3ecd5f4efba5e032d43679ee977064d6b25154a9
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
# ****************************************************** ## Revision "$LastChangedDate: 2018-06-01 15:05:44 +0200 (Fri, 01 Jun 2018) $" ## Date "$LastChangedRevision: 1 $" ## Author "$LastChangedBy: arthurbeusen $" ## URL "$HeadURL: https://pbl.sliksvn.com/generalcode/trunk/hydraulic_load.py $" ## Copyright 2017, PBL Netherlands Environmental Assessment Agency and Utrecht University. ## Reuse permitted under Gnu Public License, GPL v3. # ****************************************************** import os import ascraster def calculate(params,mask,residence_time_grid,lake_icell_dict): ''' This function calculates the hydraulic load in the water bodies. ''' # Depth water of waterbody in metres (result of residence time function) depth_grid = ascraster.Asciigrid(ascii_file=os.path.join(params.outputdir,"depth_waterbody_grid.asc"),\ mask=mask,numtype=float) hydraulic_load_grid = ascraster.duplicategrid(residence_time_grid) hydraulic_load_grid.add_values(hydraulic_load_grid.length *[0.0]) for icell in range(hydraulic_load_grid.length): depth = depth_grid.get_data(icell,0.0) resi_time = residence_time_grid.get_data(icell,0.0) try: Hl = depth/resi_time except ZeroDivisionError: Hl = 0.0 hydraulic_load_grid.set_data(icell,Hl) # Write hydraulic load to output file: hydraulic_load_grid.write_ascii_file(os.path.join(params.outputdir,"hydraulic_load.asc")) return hydraulic_load_grid
42
107
0.657658
f3647a856685abe6be6d6c0d90eed286e115d19e
610
py
Python
pymatgen/phasediagram/__init__.py
ltalirz/pymatgen
894cdb2ec7b9bd74f0ac3cdad40d144203ccdcf6
[ "MIT" ]
null
null
null
pymatgen/phasediagram/__init__.py
ltalirz/pymatgen
894cdb2ec7b9bd74f0ac3cdad40d144203ccdcf6
[ "MIT" ]
null
null
null
pymatgen/phasediagram/__init__.py
ltalirz/pymatgen
894cdb2ec7b9bd74f0ac3cdad40d144203ccdcf6
[ "MIT" ]
null
null
null
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ The phasediagram package implements the analysis tools to perform phase stability analyses, including the constructing of phase diagrams, determination of decomposition products, etc. The package is designed to be fairly modular and standalone. """ __author__ = "Shyue" __date__ = "Mar 28 2013" import warnings warnings.warn("pymatgen.phasediagram and submodules has been moved to " "pymatgen.analysis.phase_diagram This stub will be " "removed in pmg 2018.01.01.")
32.105263
79
0.74918
657eb74a7a5970e9183a0dcc4462c6385ec32fb3
352
py
Python
pysoup/display/__init__.py
illBeRoy/pysoup
742fd6630e1be27c275cb8dc6ee94412472cb20b
[ "MIT" ]
4
2016-02-21T12:40:44.000Z
2019-06-13T13:23:19.000Z
pysoup/display/__init__.py
illBeRoy/pysoup
742fd6630e1be27c275cb8dc6ee94412472cb20b
[ "MIT" ]
null
null
null
pysoup/display/__init__.py
illBeRoy/pysoup
742fd6630e1be27c275cb8dc6ee94412472cb20b
[ "MIT" ]
1
2020-07-16T12:22:12.000Z
2020-07-16T12:22:12.000Z
import pysoup.display.interactive_display import pysoup.display.silent_display class DisplayAdapter(object): @staticmethod def create_interactive_display(): return pysoup.display.interactive_display.InteractiveDisplay() @staticmethod def create_silent_display(): return pysoup.display.silent_display.SilentDisplay()
25.142857
70
0.78125
bd7c783ddd41806d08f2eeeb5802c9822ec903b4
2,915
py
Python
src/models/FeatExtractNet.py
sunshuofeng/Bi3D
aa4a4bf739017d0a9bf0149a6df891f3b97752cb
[ "BSD-Source-Code" ]
null
null
null
src/models/FeatExtractNet.py
sunshuofeng/Bi3D
aa4a4bf739017d0a9bf0149a6df891f3b97752cb
[ "BSD-Source-Code" ]
null
null
null
src/models/FeatExtractNet.py
sunshuofeng/Bi3D
aa4a4bf739017d0a9bf0149a6df891f3b97752cb
[ "BSD-Source-Code" ]
null
null
null
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from __future__ import print_function import torch import torch.nn as nn import math from bi_models.PSMNet import conv2d from bi_models.PSMNet import conv2d_relu from bi_models.PSMNet import FeatExtractNetSPP __all__ = ["featextractnetspp", "featextractnethr"] """ Feature extraction network. Generates 16D features at the image resolution. Used for final refinement. """ class FeatExtractNetHR(nn.Module): def __init__(self, out_planes=16): super(FeatExtractNetHR, self).__init__() self.conv1 = nn.Sequential( conv2d_relu(3, out_planes, kernel_size=3, stride=1, pad=1, dilation=1), conv2d_relu(out_planes, out_planes, kernel_size=3, stride=1, pad=1, dilation=1), nn.Conv2d(out_planes, out_planes, kernel_size=1, padding=0, stride=1, bias=False), ) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2.0 / n)) elif isinstance(m, nn.Conv3d): n = m.kernel_size[0] * m.kernel_size[1] * m.kernel_size[2] * m.out_channels m.weight.data.normal_(0, math.sqrt(2.0 / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.BatchNorm3d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.bias.data.zero_() return def forward(self, input): output = self.conv1(input) return output def featextractnethr(options, data=None): print("==> USING FeatExtractNetHR") for key in options: if "featextractnethr" in key: print("{} : {}".format(key, options[key])) model = FeatExtractNetHR(out_planes=options["featextractnethr_out_planes"]) if data is not None: model.load_state_dict(data["state_dict"]) return model """ Feature extraction network. Generates 32D features at 3x less resolution. Uses Spatial Pyramid Pooling inspired by PSMNet. """ def featextractnetspp(options, data=None): print("==> USING FeatExtractNetSPP") for key in options: if "feat" in key: print("{} : {}".format(key, options[key])) model = FeatExtractNetSPP() if data is not None: model.load_state_dict(data["state_dict"]) return model
29.744898
94
0.656604
7bb9a43b4a986f022cefd5da35c7deec19972bc8
1,017
py
Python
2021/day3/main.py
g-ford/advent-of-code
b706680df004cc1072551626816ce871300760f1
[ "MIT" ]
null
null
null
2021/day3/main.py
g-ford/advent-of-code
b706680df004cc1072551626816ce871300760f1
[ "MIT" ]
null
null
null
2021/day3/main.py
g-ford/advent-of-code
b706680df004cc1072551626816ce871300760f1
[ "MIT" ]
null
null
null
from operator import ge, lt from utils import log_time, to_dec, transpose def parse_line(l): return list(map(int, l.strip())) @log_time def part_a(input): transposed = transpose(input) mid = len(input) // 2 gamma = [int(sum(c) > mid) for c in transposed] epsilon = [abs(x - 1) for x in gamma] return to_dec(gamma) * to_dec(epsilon) def filter_rating(ratings, op, index=0): if len(ratings) == 1: return ratings[0] mid = len(ratings) / 2 transpose = list(zip(*ratings))[index] bit = int(op(sum(transpose), mid)) filtered = [x for x in ratings if x[index] == bit] return filter_rating(filtered, op, index + 1) @log_time def part_b(input): o2_filtered = filter_rating(input, ge) co2_filtered = filter_rating(input, lt) return to_dec(o2_filtered) * to_dec(co2_filtered) input = list(map(parse_line, open('day3/input.txt').readlines())) result_a = part_a(input) result_b = part_b(input) print("Part A:", result_a) print("Part B:", result_b)
23.113636
65
0.6647
7581139e3890799b2af7c684fd5c2e63c33f385f
385,398
py
Python
ns3/ns-3.26/src/visualizer/bindings/modulegen__gcc_LP64.py
Aedemon/clusim
7f09cdb79b5f02cf0fed1bd44842981941f29f32
[ "Apache-2.0" ]
7
2017-08-11T06:06:47.000Z
2022-02-27T07:34:33.000Z
ns3/ns-3.26/src/visualizer/bindings/modulegen__gcc_LP64.py
Aedemon/clusim
7f09cdb79b5f02cf0fed1bd44842981941f29f32
[ "Apache-2.0" ]
3
2017-08-11T03:04:59.000Z
2017-09-11T14:01:14.000Z
ns3/ns-3.26/src/visualizer/bindings/modulegen__gcc_LP64.py
Aedemon/clusim
7f09cdb79b5f02cf0fed1bd44842981941f29f32
[ "Apache-2.0" ]
3
2017-08-08T13:36:30.000Z
2018-07-04T09:49:41.000Z
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True pybindgen.settings.error_handler = ErrorHandler() import sys def module_init(): root_module = Module('ns.visualizer', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress', import_from_module='ns.network') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress', import_from_module='ns.network') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## pyviz.h (module 'visualizer'): ns3::PyViz [class] module.add_class('PyViz') ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureMode [enumeration] module.add_enum('PacketCaptureMode', ['PACKET_CAPTURE_DISABLED', 'PACKET_CAPTURE_FILTER_HEADERS_OR', 'PACKET_CAPTURE_FILTER_HEADERS_AND'], outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample [struct] module.add_class('LastPacketsSample', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics [struct] module.add_class('NetDeviceStatistics', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics [struct] module.add_class('NodeStatistics', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions [struct] module.add_class('PacketCaptureOptions', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample [struct] module.add_class('PacketDropSample', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample [struct] module.add_class('PacketSample', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample [struct] module.add_class('RxPacketSample', parent=root_module['ns3::PyViz::PacketSample'], outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample [struct] module.add_class('TransmissionSample', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample [struct] module.add_class('TxPacketSample', parent=root_module['ns3::PyViz::PacketSample'], outer_class=root_module['ns3::PyViz']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## simulator.h (module 'core'): ns3::Simulator [enumeration] module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::SupportLevel [enumeration] module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] module.add_enum('DscpType', ['DscpDefault', 'DSCP_CS1', 'DSCP_AF11', 'DSCP_AF12', 'DSCP_AF13', 'DSCP_CS2', 'DSCP_AF21', 'DSCP_AF22', 'DSCP_AF23', 'DSCP_CS3', 'DSCP_AF31', 'DSCP_AF32', 'DSCP_AF33', 'DSCP_CS4', 'DSCP_AF41', 'DSCP_AF42', 'DSCP_AF43', 'DSCP_CS5', 'DSCP_EF', 'DSCP_CS6', 'DSCP_CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration] module.add_enum('EcnType', ['ECN_NotECT', 'ECN_ECT1', 'ECN_ECT0', 'ECN_CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NetDeviceQueue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NetDeviceQueue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::QueueItem', 'ns3::empty', 'ns3::DefaultDeleter<ns3::QueueItem>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketPriority [enumeration] module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::Ipv6MulticastFilterMode [enumeration] module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::SocketIpTosTag [class] module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketPriorityTag [class] module.add_class('SocketPriorityTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## channel.h (module 'network'): ns3::Channel [class] module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor [class] module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor']) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker [class] module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## ipv4.h (module 'internet'): ns3::Ipv4 [class] module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class] module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class] module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class] module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class] module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## net-device.h (module 'network'): ns3::NetDeviceQueue [class] module.add_class('NetDeviceQueue', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface [class] module.add_class('NetDeviceQueueInterface', import_from_module='ns.network', parent=root_module['ns3::Object']) ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## net-device.h (module 'network'): ns3::QueueItem [class] module.add_class('QueueItem', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) ## net-device.h (module 'network'): ns3::QueueItem::Uint8Values [enumeration] module.add_enum('Uint8Values', ['IP_DSFIELD'], outer_class=root_module['ns3::QueueItem'], import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) module.add_container('std::vector< ns3::PyViz::RxPacketSample >', 'ns3::PyViz::RxPacketSample', container_type=u'vector') module.add_container('std::vector< ns3::PyViz::TxPacketSample >', 'ns3::PyViz::TxPacketSample', container_type=u'vector') module.add_container('std::vector< ns3::PyViz::PacketSample >', 'ns3::PyViz::PacketSample', container_type=u'vector') module.add_container('std::set< ns3::TypeId >', 'ns3::TypeId', container_type=u'set') module.add_container('std::vector< ns3::PyViz::TransmissionSample >', 'ns3::PyViz::TransmissionSample', container_type=u'vector') module.add_container('std::vector< ns3::PyViz::PacketDropSample >', 'ns3::PyViz::PacketDropSample', container_type=u'vector') module.add_container('std::vector< ns3::PyViz::NetDeviceStatistics >', 'ns3::PyViz::NetDeviceStatistics', container_type=u'vector') module.add_container('std::vector< std::string >', 'std::string', container_type=u'vector') module.add_container('std::set< unsigned int >', 'unsigned int', container_type=u'set') module.add_container('std::vector< ns3::PyViz::NodeStatistics >', 'ns3::PyViz::NodeStatistics', container_type=u'vector') module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type=u'vector') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type=u'map') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) ## Register a nested module for the namespace TracedValueCallback nested_module = module.add_cpp_namespace('TracedValueCallback') register_types_ns3_TracedValueCallback(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_TracedValueCallback(module): root_module = module.get_root() typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *', u'ns3::TracedValueCallback::Time') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) **', u'ns3::TracedValueCallback::Time*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *&', u'ns3::TracedValueCallback::Time&') def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3PyViz_methods(root_module, root_module['ns3::PyViz']) register_Ns3PyVizLastPacketsSample_methods(root_module, root_module['ns3::PyViz::LastPacketsSample']) register_Ns3PyVizNetDeviceStatistics_methods(root_module, root_module['ns3::PyViz::NetDeviceStatistics']) register_Ns3PyVizNodeStatistics_methods(root_module, root_module['ns3::PyViz::NodeStatistics']) register_Ns3PyVizPacketCaptureOptions_methods(root_module, root_module['ns3::PyViz::PacketCaptureOptions']) register_Ns3PyVizPacketDropSample_methods(root_module, root_module['ns3::PyViz::PacketDropSample']) register_Ns3PyVizPacketSample_methods(root_module, root_module['ns3::PyViz::PacketSample']) register_Ns3PyVizRxPacketSample_methods(root_module, root_module['ns3::PyViz::RxPacketSample']) register_Ns3PyVizTransmissionSample_methods(root_module, root_module['ns3::PyViz::TransmissionSample']) register_Ns3PyVizTxPacketSample_methods(root_module, root_module['ns3::PyViz::TxPacketSample']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor']) register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute']) register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route']) register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NetDeviceQueue_methods(root_module, root_module['ns3::NetDeviceQueue']) register_Ns3NetDeviceQueueInterface_methods(root_module, root_module['ns3::NetDeviceQueueInterface']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3QueueItem_methods(root_module, root_module['ns3::QueueItem']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetRemainingSize() const [member function] cls.add_method('GetRemainingSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function] cls.add_method('Adjust', 'void', [param('int32_t', 'adjustment')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Inet6SocketAddress_methods(root_module, cls): ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor] cls.add_constructor([param('char const *', 'ipv6')]) ## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function] cls.add_method('ConvertFrom', 'ns3::Inet6SocketAddress', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function] cls.add_method('GetIpv6', 'ns3::Ipv6Address', [], is_const=True) ## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetIpv6', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3InetSocketAddress_methods(root_module, cls): ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor] cls.add_constructor([param('char const *', 'ipv4')]) ## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::InetSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function] cls.add_method('GetIpv4', 'ns3::Ipv4Address', [], is_const=True) ## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet-socket-address.h (module 'network'): uint8_t ns3::InetSocketAddress::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ipv4Address', 'address')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] cls.add_method('GetLocal', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] cls.add_method('GetMask', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] cls.add_method('IsSecondary', 'bool', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] cls.add_method('SetBroadcast', 'void', [param('ns3::Ipv4Address', 'broadcast')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv4Address', 'local')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] cls.add_method('SetMask', 'void', [param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] cls.add_method('SetPrimary', 'void', []) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] cls.add_method('SetSecondary', 'void', []) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], deprecated=True, is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 21 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PyViz_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::PyViz(ns3::PyViz const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PyViz() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample ns3::PyViz::GetLastPackets(uint32_t nodeId) const [member function] cls.add_method('GetLastPackets', 'ns3::PyViz::LastPacketsSample', [param('uint32_t', 'nodeId')], is_const=True) ## pyviz.h (module 'visualizer'): std::vector<ns3::PyViz::NodeStatistics,std::allocator<ns3::PyViz::NodeStatistics> > ns3::PyViz::GetNodesStatistics() const [member function] cls.add_method('GetNodesStatistics', 'std::vector< ns3::PyViz::NodeStatistics >', [], is_const=True) ## pyviz.h (module 'visualizer'): std::vector<ns3::PyViz::PacketDropSample,std::allocator<ns3::PyViz::PacketDropSample> > ns3::PyViz::GetPacketDropSamples() const [member function] cls.add_method('GetPacketDropSamples', 'std::vector< ns3::PyViz::PacketDropSample >', [], is_const=True) ## pyviz.h (module 'visualizer'): std::vector<std::string, std::allocator<std::string> > ns3::PyViz::GetPauseMessages() const [member function] cls.add_method('GetPauseMessages', 'std::vector< std::string >', [], is_const=True) ## pyviz.h (module 'visualizer'): std::vector<ns3::PyViz::TransmissionSample,std::allocator<ns3::PyViz::TransmissionSample> > ns3::PyViz::GetTransmissionSamples() const [member function] cls.add_method('GetTransmissionSamples', 'std::vector< ns3::PyViz::TransmissionSample >', [], is_const=True) ## pyviz.h (module 'visualizer'): static void ns3::PyViz::LineClipping(double boundsX1, double boundsY1, double boundsX2, double boundsY2, double & lineX1, double & lineY1, double & lineX2, double & lineY2) [member function] cls.add_method('LineClipping', 'void', [param('double', 'boundsX1'), param('double', 'boundsY1'), param('double', 'boundsX2'), param('double', 'boundsY2'), param('double &', 'lineX1', direction=3), param('double &', 'lineY1', direction=3), param('double &', 'lineX2', direction=3), param('double &', 'lineY2', direction=3)], is_static=True) ## pyviz.h (module 'visualizer'): static void ns3::PyViz::Pause(std::string const & message) [member function] cls.add_method('Pause', 'void', [param('std::string const &', 'message')], is_static=True) ## pyviz.h (module 'visualizer'): void ns3::PyViz::RegisterCsmaLikeDevice(std::string const & deviceTypeName) [member function] cls.add_method('RegisterCsmaLikeDevice', 'void', [param('std::string const &', 'deviceTypeName')]) ## pyviz.h (module 'visualizer'): void ns3::PyViz::RegisterDropTracePath(std::string const & tracePath) [member function] cls.add_method('RegisterDropTracePath', 'void', [param('std::string const &', 'tracePath')]) ## pyviz.h (module 'visualizer'): void ns3::PyViz::RegisterPointToPointLikeDevice(std::string const & deviceTypeName) [member function] cls.add_method('RegisterPointToPointLikeDevice', 'void', [param('std::string const &', 'deviceTypeName')]) ## pyviz.h (module 'visualizer'): void ns3::PyViz::RegisterWifiLikeDevice(std::string const & deviceTypeName) [member function] cls.add_method('RegisterWifiLikeDevice', 'void', [param('std::string const &', 'deviceTypeName')]) ## pyviz.h (module 'visualizer'): void ns3::PyViz::SetNodesOfInterest(std::set<unsigned int, std::less<unsigned int>, std::allocator<unsigned int> > nodes) [member function] cls.add_method('SetNodesOfInterest', 'void', [param('std::set< unsigned int >', 'nodes')]) ## pyviz.h (module 'visualizer'): void ns3::PyViz::SetPacketCaptureOptions(uint32_t nodeId, ns3::PyViz::PacketCaptureOptions options) [member function] cls.add_method('SetPacketCaptureOptions', 'void', [param('uint32_t', 'nodeId'), param('ns3::PyViz::PacketCaptureOptions', 'options')]) ## pyviz.h (module 'visualizer'): void ns3::PyViz::SimulatorRunUntil(ns3::Time time) [member function] cls.add_method('SimulatorRunUntil', 'void', [param('ns3::Time', 'time')]) return def register_Ns3PyVizLastPacketsSample_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::LastPacketsSample() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::LastPacketsSample(ns3::PyViz::LastPacketsSample const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::LastPacketsSample const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::lastDroppedPackets [variable] cls.add_instance_attribute('lastDroppedPackets', 'std::vector< ns3::PyViz::PacketSample >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::lastReceivedPackets [variable] cls.add_instance_attribute('lastReceivedPackets', 'std::vector< ns3::PyViz::RxPacketSample >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::lastTransmittedPackets [variable] cls.add_instance_attribute('lastTransmittedPackets', 'std::vector< ns3::PyViz::TxPacketSample >', is_const=False) return def register_Ns3PyVizNetDeviceStatistics_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::NetDeviceStatistics(ns3::PyViz::NetDeviceStatistics const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::NetDeviceStatistics const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::NetDeviceStatistics() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::receivedBytes [variable] cls.add_instance_attribute('receivedBytes', 'uint64_t', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::receivedPackets [variable] cls.add_instance_attribute('receivedPackets', 'uint32_t', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::transmittedBytes [variable] cls.add_instance_attribute('transmittedBytes', 'uint64_t', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::transmittedPackets [variable] cls.add_instance_attribute('transmittedPackets', 'uint32_t', is_const=False) return def register_Ns3PyVizNodeStatistics_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics::NodeStatistics() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics::NodeStatistics(ns3::PyViz::NodeStatistics const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::NodeStatistics const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics::nodeId [variable] cls.add_instance_attribute('nodeId', 'uint32_t', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics::statistics [variable] cls.add_instance_attribute('statistics', 'std::vector< ns3::PyViz::NetDeviceStatistics >', is_const=False) return def register_Ns3PyVizPacketCaptureOptions_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::PacketCaptureOptions() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::PacketCaptureOptions(ns3::PyViz::PacketCaptureOptions const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::PacketCaptureOptions const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::headers [variable] cls.add_instance_attribute('headers', 'std::set< ns3::TypeId >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::mode [variable] cls.add_instance_attribute('mode', 'ns3::PyViz::PacketCaptureMode', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::numLastPackets [variable] cls.add_instance_attribute('numLastPackets', 'uint32_t', is_const=False) return def register_Ns3PyVizPacketDropSample_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample::PacketDropSample() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample::PacketDropSample(ns3::PyViz::PacketDropSample const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::PacketDropSample const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample::bytes [variable] cls.add_instance_attribute('bytes', 'uint32_t', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample::transmitter [variable] cls.add_instance_attribute('transmitter', 'ns3::Ptr< ns3::Node >', is_const=False) return def register_Ns3PyVizPacketSample_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::PacketSample() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::PacketSample(ns3::PyViz::PacketSample const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::PacketSample const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::device [variable] cls.add_instance_attribute('device', 'ns3::Ptr< ns3::NetDevice >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::packet [variable] cls.add_instance_attribute('packet', 'ns3::Ptr< ns3::Packet >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::time [variable] cls.add_instance_attribute('time', 'ns3::Time', is_const=False) return def register_Ns3PyVizRxPacketSample_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample::RxPacketSample() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample::RxPacketSample(ns3::PyViz::RxPacketSample const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::RxPacketSample const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample::from [variable] cls.add_instance_attribute('from', 'ns3::Mac48Address', is_const=False) return def register_Ns3PyVizTransmissionSample_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::TransmissionSample() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::TransmissionSample(ns3::PyViz::TransmissionSample const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::TransmissionSample const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::bytes [variable] cls.add_instance_attribute('bytes', 'uint32_t', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::channel [variable] cls.add_instance_attribute('channel', 'ns3::Ptr< ns3::Channel >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::receiver [variable] cls.add_instance_attribute('receiver', 'ns3::Ptr< ns3::Node >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::transmitter [variable] cls.add_instance_attribute('transmitter', 'ns3::Ptr< ns3::Node >', is_const=False) return def register_Ns3PyVizTxPacketSample_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample::TxPacketSample() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample::TxPacketSample(ns3::PyViz::TxPacketSample const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::TxPacketSample const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample::to [variable] cls.add_instance_attribute('to', 'ns3::Mac48Address', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'delay')], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3TimeWithUnit_methods(root_module, cls): cls.add_output_stream_operator() ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')], deprecated=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function] cls.add_method('GetSize', 'std::size_t', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name, ns3::TypeId::TraceSourceInformation * info) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name'), param('ns3::TypeId::TraceSourceInformation *', 'info')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function] cls.add_method('SetSize', 'ns3::TypeId', [param('std::size_t', 'size')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t uid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'uid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable] cls.add_instance_attribute('callback', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor] cls.add_constructor([param('long double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable] cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Ipv4Header_methods(root_module, cls): ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor] cls.add_constructor([]) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function] cls.add_method('DscpTypeToString', 'std::string', [param('ns3::Ipv4Header::DscpType', 'dscp')], is_const=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function] cls.add_method('EcnTypeToString', 'std::string', [param('ns3::Ipv4Header::EcnType', 'ecn')], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function] cls.add_method('EnableChecksum', 'void', []) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function] cls.add_method('GetDscp', 'ns3::Ipv4Header::DscpType', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function] cls.add_method('GetEcn', 'ns3::Ipv4Header::EcnType', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function] cls.add_method('GetFragmentOffset', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function] cls.add_method('GetIdentification', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function] cls.add_method('GetPayloadSize', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function] cls.add_method('IsChecksumOk', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function] cls.add_method('IsDontFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'destination')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function] cls.add_method('SetDontFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function] cls.add_method('SetDscp', 'void', [param('ns3::Ipv4Header::DscpType', 'dscp')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function] cls.add_method('SetEcn', 'void', [param('ns3::Ipv4Header::EcnType', 'ecn')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function] cls.add_method('SetFragmentOffset', 'void', [param('uint16_t', 'offsetBytes')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function] cls.add_method('SetIdentification', 'void', [param('uint16_t', 'identification')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function] cls.add_method('SetLastFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function] cls.add_method('SetMayFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function] cls.add_method('SetPayloadSize', 'void', [param('uint16_t', 'size')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function] cls.add_method('SetProtocol', 'void', [param('uint8_t', 'num')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'source')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): bool ns3::Object::IsInitialized() const [member function] cls.add_method('IsInitialized', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4Route > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter< ns3::NetDeviceQueue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount(ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter< ns3::QueueItem > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Socket_methods(root_module, cls): ## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor] cls.add_constructor([param('ns3::Socket const &', 'arg0')]) ## socket.h (module 'network'): ns3::Socket::Socket() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind() [member function] cls.add_method('Bind', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function] cls.add_method('BindToNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'netdevice')], is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Close() [member function] cls.add_method('Close', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function] cls.add_method('GetBoundNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function] cls.add_method('GetIpTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function] cls.add_method('GetIpTtl', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function] cls.add_method('GetIpv6HopLimit', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function] cls.add_method('GetIpv6Tclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetPeerName(ns3::Address & address) const [member function] cls.add_method('GetPeerName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): static uint8_t ns3::Socket::IpTos2Priority(uint8_t ipTos) [member function] cls.add_method('IpTos2Priority', 'uint8_t', [param('uint8_t', 'ipTos')], is_static=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address, ns3::Socket::Ipv6MulticastFilterMode filterMode, std::vector<ns3::Ipv6Address,std::allocator<ns3::Ipv6Address> > sourceAddresses) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address'), param('ns3::Socket::Ipv6MulticastFilterMode', 'filterMode'), param('std::vector< ns3::Ipv6Address >', 'sourceAddresses')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6LeaveGroup() [member function] cls.add_method('Ipv6LeaveGroup', 'void', [], is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function] cls.add_method('IsIpRecvTos', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function] cls.add_method('IsIpRecvTtl', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function] cls.add_method('IsIpv6RecvHopLimit', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function] cls.add_method('IsIpv6RecvTclass', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function] cls.add_method('SetAcceptCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')]) ## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function] cls.add_method('SetCloseCallbacks', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')]) ## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function] cls.add_method('SetConnectCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')]) ## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function] cls.add_method('SetDataSentCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function] cls.add_method('SetIpRecvTos', 'void', [param('bool', 'ipv4RecvTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function] cls.add_method('SetIpRecvTtl', 'void', [param('bool', 'ipv4RecvTtl')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function] cls.add_method('SetIpTos', 'void', [param('uint8_t', 'ipTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function] cls.add_method('SetIpTtl', 'void', [param('uint8_t', 'ipTtl')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function] cls.add_method('SetIpv6HopLimit', 'void', [param('uint8_t', 'ipHopLimit')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function] cls.add_method('SetIpv6RecvHopLimit', 'void', [param('bool', 'ipv6RecvHopLimit')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function] cls.add_method('SetIpv6RecvTclass', 'void', [param('bool', 'ipv6RecvTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function] cls.add_method('SetIpv6Tclass', 'void', [param('int', 'ipTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function] cls.add_method('SetRecvCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function] cls.add_method('SetRecvPktInfo', 'void', [param('bool', 'flag')]) ## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function] cls.add_method('SetSendCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')]) ## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function] cls.add_method('IsManualIpTtl', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function] cls.add_method('IsManualIpv6HopLimit', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function] cls.add_method('IsManualIpv6Tclass', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function] cls.add_method('NotifyNewConnectionCreated', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_Ns3SocketIpTosTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3SocketIpTtlTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hopLimit')]) return def register_Ns3SocketIpv6TclassTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function] cls.add_method('GetTclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function] cls.add_method('SetTclass', 'void', [param('uint8_t', 'tclass')]) return def register_Ns3SocketPriorityTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag(ns3::SocketPriorityTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketPriorityTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketPriorityTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketPriorityTag::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::SocketPriorityTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketPriorityTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): std::string ns3::CallbackImplBase::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3Channel_methods(root_module, cls): ## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor] cls.add_constructor([param('ns3::Channel const &', 'arg0')]) ## channel.h (module 'network'): ns3::Channel::Channel() [constructor] cls.add_constructor([]) ## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3EmptyAttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor(ns3::EmptyAttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object'), param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker(ns3::EmptyAttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3Ipv4_methods(root_module, cls): ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')]) ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor] cls.add_constructor([]) ## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): static ns3::TypeId ns3::Ipv4::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsForwarding(uint32_t interface) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsUp(uint32_t interface) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'interface'), param('bool', 'val')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'interface'), param('uint16_t', 'metric')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SourceAddressSelection(uint32_t interface, ns3::Ipv4Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv4Address', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'dest')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4L3Protocol_methods(root_module, cls): ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::Ipv4L3Protocol() [constructor] cls.add_constructor([]) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::AddAddress(uint32_t i, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'i'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4L3Protocol::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Interface> ns3::Ipv4L3Protocol::GetInterface(uint32_t i) const [member function] cls.add_method('GetInterface', 'ns3::Ptr< ns3::Ipv4Interface >', [param('uint32_t', 'i')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForAddress(ns3::Ipv4Address addr) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'addr')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForPrefix(ns3::Ipv4Address addr, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'addr'), param('ns3::Ipv4Mask', 'mask')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMetric(uint32_t i) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMtu(uint32_t i) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4L3Protocol::GetNetDevice(uint32_t i) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4L3Protocol::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4L3Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsForwarding(uint32_t i) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUnicast(ns3::Ipv4Address ad) const [member function] cls.add_method('IsUnicast', 'bool', [param('ns3::Ipv4Address', 'ad')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUp(uint32_t i) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interfaceIndex, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDefaultTtl(uint8_t ttl) [member function] cls.add_method('SetDefaultTtl', 'void', [param('uint8_t', 'ttl')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDown(uint32_t i) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetForwarding(uint32_t i, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'i'), param('bool', 'val')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetMetric(uint32_t i, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'i'), param('uint16_t', 'metric')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetUp(uint32_t i) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SourceAddressSelection(uint32_t interface, ns3::Ipv4Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv4Address', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'dest')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::PROT_NUMBER [variable] cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], visibility='private', is_virtual=True) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv4MulticastRoute_methods(root_module, cls): ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function] cls.add_method('GetGroup', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function] cls.add_method('GetOutputTtlMap', 'std::map< unsigned int, unsigned int >', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function] cls.add_method('GetParent', 'uint32_t', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function] cls.add_method('SetGroup', 'void', [param('ns3::Ipv4Address const', 'group')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv4Address const', 'origin')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function] cls.add_method('SetOutputTtl', 'void', [param('uint32_t', 'oif'), param('uint32_t', 'ttl')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function] cls.add_method('SetParent', 'void', [param('uint32_t', 'iif')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable] cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable] cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True) return def register_Ns3Ipv4Route_methods(root_module, cls): cls.add_output_stream_operator() ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function] cls.add_method('GetGateway', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'dest')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function] cls.add_method('SetGateway', 'void', [param('ns3::Ipv4Address', 'gw')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'src')]) return def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls): ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor] cls.add_constructor([]) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')]) ## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void,ns3::Ptr<ns3::Ipv4Route>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::Socket::SocketErrno,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NetDeviceQueue_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue(ns3::NetDeviceQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueue const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::Ptr<ns3::QueueLimits> ns3::NetDeviceQueue::GetQueueLimits() [member function] cls.add_method('GetQueueLimits', 'ns3::Ptr< ns3::QueueLimits >', []) ## net-device.h (module 'network'): bool ns3::NetDeviceQueue::IsStopped() const [member function] cls.add_method('IsStopped', 'bool', [], is_const=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::NotifyQueuedBytes(uint32_t bytes) [member function] cls.add_method('NotifyQueuedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::NotifyTransmittedBytes(uint32_t bytes) [member function] cls.add_method('NotifyTransmittedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::ResetQueueLimits() [member function] cls.add_method('ResetQueueLimits', 'void', []) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetQueueLimits(ns3::Ptr<ns3::QueueLimits> ql) [member function] cls.add_method('SetQueueLimits', 'void', [param('ns3::Ptr< ns3::QueueLimits >', 'ql')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetWakeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetWakeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Wake() [member function] cls.add_method('Wake', 'void', [], is_virtual=True) return def register_Ns3NetDeviceQueueInterface_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface(ns3::NetDeviceQueueInterface const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueueInterface const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::CreateTxQueues() [member function] cls.add_method('CreateTxQueues', 'void', []) ## net-device.h (module 'network'): uint8_t ns3::NetDeviceQueueInterface::GetNTxQueues() const [member function] cls.add_method('GetNTxQueues', 'uint8_t', [], is_const=True) ## net-device.h (module 'network'): ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::NetDeviceQueueInterface::GetSelectQueueCallback() const [member function] cls.add_method('GetSelectQueueCallback', 'ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::NetDeviceQueue> ns3::NetDeviceQueueInterface::GetTxQueue(uint8_t i) const [member function] cls.add_method('GetTxQueue', 'ns3::Ptr< ns3::NetDeviceQueue >', [param('uint8_t', 'i')], is_const=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDeviceQueueInterface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetSelectQueueCallback(ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetSelectQueueCallback', 'void', [param('ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetTxQueuesN(uint8_t numTxQueues) [member function] cls.add_method('SetTxQueuesN', 'void', [param('uint8_t', 'numTxQueues')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): ns3::Time ns3::Node::GetLocalTime() const [member function] cls.add_method('GetLocalTime', 'ns3::Time', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) ## packet.h (module 'network'): std::string ns3::Packet::ToString() const [member function] cls.add_method('ToString', 'std::string', [], is_const=True) return def register_Ns3QueueItem_methods(root_module, cls): cls.add_output_stream_operator() ## net-device.h (module 'network'): ns3::QueueItem::QueueItem(ns3::Ptr<ns3::Packet> p) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p')]) ## net-device.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::QueueItem::GetPacket() const [member function] cls.add_method('GetPacket', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## net-device.h (module 'network'): uint32_t ns3::QueueItem::GetPacketSize() const [member function] cls.add_method('GetPacketSize', 'uint32_t', [], is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::QueueItem::GetUint8Value(ns3::QueueItem::Uint8Values field, uint8_t & value) const [member function] cls.add_method('GetUint8Value', 'bool', [param('ns3::QueueItem::Uint8Values', 'field'), param('uint8_t &', 'value')], is_const=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::QueueItem::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def register_functions_ns3_TracedValueCallback(module, root_module): return def main(): out = FileCodeSink(sys.stdout) root_module = module_init() register_types(root_module) register_methods(root_module) register_functions(root_module) root_module.generate(out) if __name__ == '__main__': main()
64.233
934
0.624277
7d93b75165a7e8b230cab1db0603290b95648605
20,627
py
Python
mmdet/core/evaluation/eval_hooks.py
opencv/mmdetection
6a7dfa5b954d6bbad7f8d33db8268b0fafc7d555
[ "Apache-2.0" ]
24
2020-04-15T14:54:44.000Z
2020-08-12T12:45:57.000Z
mmdet/core/evaluation/eval_hooks.py
opencv/mmdetection
6a7dfa5b954d6bbad7f8d33db8268b0fafc7d555
[ "Apache-2.0" ]
46
2020-04-10T12:01:59.000Z
2020-09-04T06:25:56.000Z
mmdet/core/evaluation/eval_hooks.py
opencv/mmdetection
6a7dfa5b954d6bbad7f8d33db8268b0fafc7d555
[ "Apache-2.0" ]
11
2020-04-16T17:55:29.000Z
2020-08-25T11:13:58.000Z
# Copyright (C) 2018-2021 OpenMMLab # SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # # Is based on # * https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/hooks/evaluation.py import os import os.path as osp import torch.distributed as dist import warnings from math import inf from mmcv.runner import Hook from mmcv.utils import is_seq_of from torch.nn.modules.batchnorm import _BatchNorm from torch.utils.data import DataLoader class EvalHook(Hook): """Non-Distributed evaluation hook. This hook will regularly perform evaluation in a given interval when performing in non-distributed environment. Args: dataloader (DataLoader): A PyTorch dataloader, whose dataset has implemented ``evaluate`` function. start (int | None, optional): Evaluation starting epoch. It enables evaluation before the training starts if ``start`` <= the resuming epoch. If None, whether to evaluate is merely decided by ``interval``. Default: None. interval (int): Evaluation interval. Default: 1. by_epoch (bool): Determine perform evaluation by epoch or by iteration. If set to True, it will perform by epoch. Otherwise, by iteration. default: True. save_best (str, optional): If a metric is specified, it would measure the best checkpoint during evaluation. The information about best checkpoint would be saved in ``runner.meta['hook_msgs']`` to keep best score value and best checkpoint path, which will be also loaded when resume checkpoint. Options are the evaluation metrics on the test dataset. e.g., ``bbox_mAP``, ``segm_mAP`` for bbox detection and instance segmentation. ``AR@100`` for proposal recall. If ``save_best`` is ``auto``, the first key of the returned ``OrderedDict`` result will be used. Default: None. rule (str | None, optional): Comparison rule for best score. If set to None, it will infer a reasonable rule. Keys such as 'acc', 'top' .etc will be inferred by 'greater' rule. Keys contain 'loss' will be inferred by 'less' rule. Options are 'greater', 'less', None. Default: None. test_fn (callable, optional): test a model with samples from a dataloader, and return the test results. If ``None``, the default test function ``mmcv.engine.single_gpu_test`` will be used. (default: ``None``) greater_keys (List[str] | None, optional): Metric keys that will be inferred by 'greater' comparison rule. If ``None``, _default_greater_keys will be used. (default: ``None``) less_keys (List[str] | None, optional): Metric keys that will be inferred by 'less' comparison rule. If ``None``, _default_less_keys will be used. (default: ``None``) **eval_kwargs: Evaluation arguments fed into the evaluate function of the dataset. Notes: If new arguments are added for EvalHook, tools/test.py, tools/eval_metric.py may be affected. """ # Since the key for determine greater or less is related to the downstream # tasks, downstream repos may need to overwrite the following inner # variable accordingly. rule_map = {'greater': lambda x, y: x > y, 'less': lambda x, y: x < y} init_value_map = {'greater': -inf, 'less': inf} _default_greater_keys = ['mAP', 'AR', 'mIoU'] _default_less_keys = ['loss'] def __init__(self, dataloader, start=None, interval=1, by_epoch=True, save_best=None, rule=None, test_fn=None, greater_keys=None, less_keys=None, best_ckpt_path=None, **eval_kwargs): if not isinstance(dataloader, DataLoader): raise TypeError(f'dataloader must be a pytorch DataLoader, ' f'but got {type(dataloader)}') if interval <= 0: raise ValueError(f'interval must be a positive number, ' f'but got {interval}') assert isinstance(by_epoch, bool), '``by_epoch`` should be a boolean' if start is not None and start < 0: warnings.warn( f'The evaluation start epoch {start} is smaller than 0, ' f'use 0 instead', UserWarning) start = 0 self.dataloader = dataloader self.interval = interval self.start = start self.by_epoch = by_epoch assert isinstance(save_best, str) or save_best is None, \ '""save_best"" should be a str or None ' \ f'rather than {type(save_best)}' self.save_best = save_best self.eval_kwargs = eval_kwargs self.initial_flag = True if test_fn is None: from mmdet.apis import single_gpu_test self.test_fn = single_gpu_test else: self.test_fn = test_fn if greater_keys is None: self.greater_keys = self._default_greater_keys else: if not isinstance(greater_keys, (list, tuple)): greater_keys = (greater_keys, ) assert is_seq_of(greater_keys, str) self.greater_keys = greater_keys if less_keys is None: self.less_keys = self._default_less_keys else: if not isinstance(less_keys, (list, tuple)): less_keys = (less_keys, ) assert is_seq_of(less_keys, str) self.less_keys = less_keys if self.save_best is not None: self.best_ckpt_path = best_ckpt_path self._init_rule(rule, self.save_best) def _init_rule(self, rule, key_indicator): """Initialize rule, key_indicator, comparison_func, and best score. Here is the rule to determine which rule is used for key indicator when the rule is not specific (note that the key indicator matching is case-insensitive): 1. If the key indicator is in ``self.greater_keys``, the rule will be specified as 'greater'. 2. Or if the key indicator is in ``self.less_keys``, the rule will be specified as 'less'. 3. Or if the key indicator is equal to the substring in any one item in ``self.greater_keys``, the rule will be specified as 'greater'. 4. Or if the key indicator is equal to the substring in any one item in ``self.less_keys``, the rule will be specified as 'less'. Args: rule (str | None): Comparison rule for best score. key_indicator (str | None): Key indicator to determine the comparison rule. """ if rule not in self.rule_map and rule is not None: raise KeyError(f'rule must be greater, less or None, ' f'but got {rule}.') if rule is None: if key_indicator != 'auto': # `_lc` here means we use the lower case of keys for # case-insensitive matching key_indicator_lc = key_indicator.lower() greater_keys = [key.lower() for key in self.greater_keys] less_keys = [key.lower() for key in self.less_keys] if key_indicator_lc in greater_keys: rule = 'greater' elif key_indicator_lc in less_keys: rule = 'less' elif any(key in key_indicator_lc for key in greater_keys): rule = 'greater' elif any(key in key_indicator_lc for key in less_keys): rule = 'less' else: raise ValueError(f'Cannot infer the rule for key ' f'{key_indicator}, thus a specific rule ' f'must be specified.') self.rule = rule self.key_indicator = key_indicator if self.rule is not None: self.compare_func = self.rule_map[self.rule] def before_run(self, runner): if self.save_best is not None: if runner.meta is None: warnings.warn('runner.meta is None. Creating an empty one.') runner.meta = dict() runner.meta.setdefault('hook_msgs', dict()) self.best_ckpt_path = runner.meta['hook_msgs'].get( 'best_ckpt', None) def before_train_iter(self, runner): """Evaluate the model only at the start of training by iteration.""" if self.by_epoch or not self.initial_flag: return if self.start is not None and runner.iter >= self.start: self.after_train_iter(runner) self.initial_flag = False def before_train_epoch(self, runner): """Evaluate the model only at the start of training by epoch.""" if not (self.by_epoch and self.initial_flag): return if self.start is not None and runner.epoch >= self.start: self.after_train_epoch(runner) self.initial_flag = False def after_train_iter(self, runner): """Called after every training iter to evaluate the results.""" if not self.by_epoch: self._do_evaluate(runner) def after_train_epoch(self, runner): """Called after every training epoch to evaluate the results.""" if self.by_epoch: self._do_evaluate(runner) def _do_evaluate(self, runner): """perform evaluation and save ckpt.""" if not self._should_evaluate(runner): return from mmdet.apis import single_gpu_test results = single_gpu_test(runner.model, self.dataloader, show=False) runner.log_buffer.output['eval_iter_num'] = len(self.dataloader) key_score = self.evaluate(runner, results) if self.save_best: self._save_ckpt(runner, key_score) def _should_evaluate(self, runner): """Judge whether to perform evaluation. Here is the rule to judge whether to perform evaluation: 1. It will not perform evaluation during the epoch/iteration interval, which is determined by ``self.interval``. 2. It will not perform evaluation if the start time is larger than current time. 3. It will not perform evaluation when current time is larger than the start time but during epoch/iteration interval. Returns: bool: The flag indicating whether to perform evaluation. """ if self.by_epoch: current = runner.epoch check_time = self.every_n_epochs else: current = runner.iter check_time = self.every_n_iters if self.start is None: if not check_time(runner, self.interval): # No evaluation during the interval. return False elif (current + 1) < self.start: # No evaluation if start is larger than the current time. return False else: # Evaluation only at epochs/iters 3, 5, 7... # if start==3 and interval==2 if (current + 1 - self.start) % self.interval: return False return True def _save_ckpt(self, runner, key_score): """Save the best checkpoint. It will compare the score according to the compare function, write related information (best score, best checkpoint path) and save the best checkpoint into ``work_dir``. """ if self.by_epoch: current = f'epoch_{runner.epoch + 1}' cur_type, cur_time = 'epoch', runner.epoch + 1 else: current = f'iter_{runner.iter + 1}' cur_type, cur_time = 'iter', runner.iter + 1 best_score = runner.meta['hook_msgs'].get( 'best_score', self.init_value_map[self.rule]) if self.compare_func(key_score, best_score): best_score = key_score runner.meta['hook_msgs']['best_score'] = best_score if self.best_ckpt_path and osp.isfile(self.best_ckpt_path): os.remove(self.best_ckpt_path) best_ckpt_name = f'best_{self.key_indicator}_{current}.pth' self.best_ckpt_path = osp.join(runner.work_dir, best_ckpt_name) runner.meta['hook_msgs']['best_ckpt'] = self.best_ckpt_path runner.save_checkpoint( runner.work_dir, best_ckpt_name, create_symlink=False) runner.logger.info( f'Now best checkpoint is saved as {best_ckpt_name}.') runner.logger.info( f'Best {self.key_indicator} is {best_score:0.4f} ' f'at {cur_time} {cur_type}.') def evaluate(self, runner, results): """Evaluate the results. Args: runner (:obj:`mmcv.Runner`): The underlined training runner. results (list): Output results. """ eval_res = self.dataloader.dataset.evaluate( results, logger=runner.logger, **self.eval_kwargs) for name, val in eval_res.items(): runner.log_buffer.output[name] = val # TODO: Log is cleared in Logger.after_train_iter before ReduceOnPlateau could get the metric setattr(runner, name, val) runner.log_buffer.ready = True if self.save_best is not None: if self.key_indicator == 'auto': # infer from eval_results self._init_rule(self.rule, list(eval_res.keys())[0]) return eval_res.get(self.key_indicator, 0.0) return None class DistEvalHook(EvalHook): """Distributed evaluation hook. This hook will regularly perform evaluation in a given interval when performing in distributed environment. Args: dataloader (DataLoader): A PyTorch dataloader, whose dataset has implemented ``evaluate`` function. start (int | None, optional): Evaluation starting epoch. It enables evaluation before the training starts if ``start`` <= the resuming epoch. If None, whether to evaluate is merely decided by ``interval``. Default: None. interval (int): Evaluation interval. Default: 1. by_epoch (bool): Determine perform evaluation by epoch or by iteration. If set to True, it will perform by epoch. Otherwise, by iteration. default: True. save_best (str, optional): If a metric is specified, it would measure the best checkpoint during evaluation. The information about best checkpoint would be saved in ``runner.meta['hook_msgs']`` to keep best score value and best checkpoint path, which will be also loaded when resume checkpoint. Options are the evaluation metrics on the test dataset. e.g., ``bbox_mAP``, ``segm_mAP`` for bbox detection and instance segmentation. ``AR@100`` for proposal recall. If ``save_best`` is ``auto``, the first key of the returned ``OrderedDict`` result will be used. Default: None. rule (str | None, optional): Comparison rule for best score. If set to None, it will infer a reasonable rule. Keys such as 'acc', 'top' .etc will be inferred by 'greater' rule. Keys contain 'loss' will be inferred by 'less' rule. Options are 'greater', 'less', None. Default: None. test_fn (callable, optional): test a model with samples from a dataloader in a multi-gpu manner, and return the test results. If ``None``, the default test function ``mmcv.engine.multi_gpu_test`` will be used. (default: ``None``) tmpdir (str | None): Temporary directory to save the results of all processes. Default: None. gpu_collect (bool): Whether to use gpu or cpu to collect results. Default: False. broadcast_bn_buffer (bool): Whether to broadcast the buffer(running_mean and running_var) of rank 0 to other rank before evaluation. Default: True. **eval_kwargs: Evaluation arguments fed into the evaluate function of the dataset. """ def __init__(self, dataloader, start=None, interval=1, by_epoch=True, save_best=None, rule=None, test_fn=None, greater_keys=None, less_keys=None, broadcast_bn_buffer=True, tmpdir=None, gpu_collect=False, **eval_kwargs): if test_fn is None: from mmdet.apis import multi_gpu_test test_fn = multi_gpu_test super().__init__( dataloader, start=start, interval=interval, by_epoch=by_epoch, save_best=save_best, rule=rule, test_fn=test_fn, greater_keys=greater_keys, less_keys=less_keys, **eval_kwargs) self.broadcast_bn_buffer = broadcast_bn_buffer self.tmpdir = tmpdir self.gpu_collect = gpu_collect def broadcast(self, data): broadcast_obj = [data] if dist.is_initialized(): dist.broadcast_object_list(broadcast_obj, src=0) return broadcast_obj[0] def _do_evaluate(self, runner): """perform evaluation and save ckpt.""" # Synchronization of BatchNorm's buffer (running_mean # and running_var) is not supported in the DDP of pytorch, # which may cause the inconsistent performance of models in # different ranks, so we broadcast BatchNorm's buffers # of rank 0 to other ranks to avoid this. if self.broadcast_bn_buffer: model = runner.model for name, module in model.named_modules(): if isinstance(module, _BatchNorm) and module.track_running_stats: dist.broadcast(module.running_var, 0) dist.broadcast(module.running_mean, 0) if not self._should_evaluate(runner): return tmpdir = self.tmpdir if tmpdir is None: tmpdir = osp.join(runner.work_dir, '.eval_hook') from mmdet.apis import multi_gpu_test results = multi_gpu_test( runner.model, self.dataloader, tmpdir=tmpdir, gpu_collect=self.gpu_collect) broadcast_data = None if runner.rank == 0: print('\n') runner.log_buffer.output['eval_iter_num'] = len(self.dataloader) key_score = self.evaluate(runner, results) # TODO: Log is cleared in Logger.after_train_iter before ReduceOnPlateau could get the metric for name, val in runner.log_buffer.output.items(): setattr(runner, name, val) if self.save_best: self._save_ckpt(runner, key_score) if self.save_best == 'auto': broadcast_data = runner.log_buffer.output[ self.key_indicator] else: broadcast_data = runner.log_buffer.output[self.save_best] score = self.broadcast(broadcast_data) if runner.rank != 0 and self.save_best: setattr(runner, self.save_best, score) class EvalPlusBeforeRunHook(EvalHook): """Evaluation hook, adds evaluation before training. """ def before_run(self, runner): super().before_run(runner) from mmdet.apis import single_gpu_test results = single_gpu_test(runner.model, self.dataloader, show=False) self.evaluate(runner, results) class DistEvalPlusBeforeRunHook(EvalPlusBeforeRunHook, DistEvalHook): """Distributed evaluation hook, adds evaluation before training. """ def before_run(self, runner): from mmdet.apis import multi_gpu_test results = multi_gpu_test( runner.model, self.dataloader, tmpdir=osp.join(runner.work_dir, '.eval_hook'), gpu_collect=self.gpu_collect) if runner.rank == 0: print('\n') self.evaluate(runner, results)
42.442387
105
0.602608
70b31579fb7a81e51c07058fd91c64e633bedc5f
599
py
Python
addons/bi_hr_payroll/models/hr_employee.py
nathanbangwa243/house-location
fa38203b2c92dd97f253fc3b4354af228f1b0338
[ "MIT" ]
1
2021-11-17T18:49:44.000Z
2021-11-17T18:49:44.000Z
addons/bi_hr_payroll/models/hr_employee.py
nathanbangwa243/house-location
fa38203b2c92dd97f253fc3b4354af228f1b0338
[ "MIT" ]
null
null
null
addons/bi_hr_payroll/models/hr_employee.py
nathanbangwa243/house-location
fa38203b2c92dd97f253fc3b4354af228f1b0338
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Part of BrowseInfo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class HrEmployee(models.Model): _inherit = 'hr.employee' _description = 'Employee' slip_ids = fields.One2many('hr.payslip', 'employee_id', string='Payslips', readonly=True) payslip_count = fields.Integer(compute='_compute_payslip_count', string='Payslip Count', groups="bi_hr_payroll.group_hr_payroll_user") def _compute_payslip_count(self): for employee in self: employee.payslip_count = len(employee.slip_ids)
35.235294
138
0.72621
c49869593f4ded53c42023304e6098f3cc065118
731
py
Python
dataset_script/analysis_predict.py
TITC/bert
bed2ff5dc4cdf2f01599cfdcb9862f6016bf44f6
[ "Apache-2.0" ]
null
null
null
dataset_script/analysis_predict.py
TITC/bert
bed2ff5dc4cdf2f01599cfdcb9862f6016bf44f6
[ "Apache-2.0" ]
null
null
null
dataset_script/analysis_predict.py
TITC/bert
bed2ff5dc4cdf2f01599cfdcb9862f6016bf44f6
[ "Apache-2.0" ]
null
null
null
in_csv = '/content/bert/tmp/predict/test_results.tsv' file1 = open(in_csv, 'r') Lines_predict = file1.readlines() number_lines = sum(1 for row in (open(in_csv))) in_csv = '/content/bert/datasets/chinese_dictionary-master/ant_syn_datasets/test.tsv' file1 = open(in_csv, 'r') Lines_test = file1.readlines() correct = 0 for i in range(number_lines): cur_test = Lines_test[i+1].replace('\n', '') cur_pre = Lines_predict[i] cur_pre = cur_pre.replace('\n', '').split("\t") max_prob = max([float(ele) for ele in cur_pre]) predict = cur_pre.index(str(max_prob)) cur_test = cur_test.split('\t') if predict == int(cur_test[0]): correct += 1 else: print(cur_test) print(correct/number_lines)
31.782609
85
0.677155
5b3ea335d97d318e9ebd0514855f1d47ab5a194c
9,641
py
Python
research/object_detection/models/retinanet_feature_extractor.py
y-kallel/models
4d073d82d988d0147cb2d17b4390e8fab1f46e6d
[ "Apache-2.0" ]
null
null
null
research/object_detection/models/retinanet_feature_extractor.py
y-kallel/models
4d073d82d988d0147cb2d17b4390e8fab1f46e6d
[ "Apache-2.0" ]
null
null
null
research/object_detection/models/retinanet_feature_extractor.py
y-kallel/models
4d073d82d988d0147cb2d17b4390e8fab1f46e6d
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 The TensorFlow 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. # ============================================================================== """RetinaNet feature extractors based on Resnet v1. See https://arxiv.org/abs/1708.02002 for details. """ import tensorflow as tf from object_detection.meta_architectures import ssd_meta_arch from object_detection.utils import context_manager from object_detection.utils import ops from object_detection.utils import shape_utils from object_detection.models.retinanet import retinanet_fpn RESNET_ARCH_BLOCK = {"resnet50": [3, 4, 6, 3], "resnet101": [3, 4, 23, 3]} class RetinaNetFeatureExtractor(ssd_meta_arch.SSDFeatureExtractor): """SSD FPN feature extractor based on Resnet v1 architecture.""" def __init__(self, is_training, depth_multiplier, min_depth, conv_hyperparams_fn, pad_to_multiple, backbone, fpn_scope_name, min_level=3, max_level=7, additional_layer_depth=256, reuse_weights=None, use_explicit_padding=False, use_depthwise=False, override_base_feature_extractor_hyperparams=False): """RetinaNet feature extractor. Args: is_training: whether the network is in training mode. depth_multiplier: float depth multiplier for feature extractor. min_depth: minimum feature extractor depth. pad_to_multiple: the nearest multiple to zero pad the input height and width dimensions to. fpn_scope_name: scope name under which to construct the feature pyramid network. additional_layer_depth: additional feature map layer channel depth. reuse_weights: Whether to reuse variables. Default is None. use_explicit_padding: Whether to use explicit padding when extracting features. Default is False. UNUSED currently. use_depthwise: Whether to use depthwise convolutions. UNUSED currently. override_base_feature_extractor_hyperparams: Whether to override hyperparameters of the base feature extractor with the one from `conv_hyperparams_fn`. Raises: ValueError: On supplying invalid arguments for unused arguments. """ super(RetinaNetFeatureExtractor, self).__init__( is_training=is_training, depth_multiplier=depth_multiplier, min_depth=min_depth, conv_hyperparams_fn=conv_hyperparams_fn, pad_to_multiple=pad_to_multiple, reuse_weights=reuse_weights, use_explicit_padding=use_explicit_padding, use_depthwise=use_depthwise, override_base_feature_extractor_hyperparams= override_base_feature_extractor_hyperparams) if self._use_explicit_padding is True: raise ValueError('Explicit padding is not a valid option.') self._backbone = backbone self._fpn_scope_name = fpn_scope_name self._min_level = min_level self._max_level = max_level self._additional_layer_depth = additional_layer_depth def preprocess(self, resized_inputs): """SSD preprocessing. VGG style channel mean subtraction as described here: https://gist.github.com/ksimonyan/211839e770f7b538e2d8#file-readme-mdnge. Note that if the number of channels is not equal to 3, the mean subtraction will be skipped and the original resized_inputs will be returned. Args: resized_inputs: a [batch, height, width, channels] float tensor representing a batch of images. Returns: preprocessed_inputs: a [batch, height, width, channels] float tensor representing a batch of images. """ if resized_inputs.shape.as_list()[3] == 3: channel_means = [123.68, 116.779, 103.939] return resized_inputs - [[channel_means]] else: return resized_inputs def extract_features(self, preprocessed_inputs): """Extract features from preprocessed inputs. Args: preprocessed_inputs: a [batch, height, width, channels] float tensor representing a batch of images. Returns: feature_maps: a list of tensors where the ith tensor has shape [batch, height_i, width_i, depth_i] """ preprocessed_inputs = shape_utils.check_min_image_dim( 129, preprocessed_inputs) with tf.variable_scope( self._fpn_scope_name, reuse=self._reuse_weights) as scope: if self._backbone in list(RESNET_ARCH_BLOCK.keys()): block_layers = RESNET_ARCH_BLOCK[self._backbone] else: raise ValueError("Unknown backbone found! Only resnet50 or resnet101 is allowed!") image_features = retinanet_fpn(inputs=preprocessed_inputs, block_layers=block_layers, depth=self._additional_layer_depth, is_training=self._is_training) return [image_features[x] for x in range(self._min_level, self._max_level+1)] class RetinaNet50FeatureExtractor(RetinaNetFeatureExtractor): """Resnet 50 RetinaNet feature extractor.""" def __init__(self, is_training, depth_multiplier, min_depth, conv_hyperparams_fn, pad_to_multiple, backbone='resnet50', additional_layer_depth=256, reuse_weights=None, use_explicit_padding=False, use_depthwise=False, override_base_feature_extractor_hyperparams=False): """ Args: is_training: whether the network is in training mode. depth_multiplier: float depth multiplier for feature extractor. UNUSED currently. min_depth: minimum feature extractor depth. UNUSED Currently. pad_to_multiple: the nearest multiple to zero pad the input height and width dimensions to. additional_layer_depth: additional feature map layer channel depth. reuse_weights: Whether to reuse variables. Default is None. use_explicit_padding: Whether to use explicit padding when extracting features. Default is False. UNUSED currently. use_depthwise: Whether to use depthwise convolutions. UNUSED currently. override_base_feature_extractor_hyperparams: Whether to override hyperparameters of the base feature extractor with the one from `conv_hyperparams_fn`. """ super(RetinaNet50FeatureExtractor, self).__init__( is_training=is_training, depth_multiplier=depth_multiplier, min_depth=min_depth, conv_hyperparams_fn=conv_hyperparams_fn, pad_to_multiple=pad_to_multiple, backbone='resnet50', fpn_scope_name='retinanet50', additional_layer_depth=additional_layer_depth, reuse_weights=reuse_weights, use_explicit_padding=use_explicit_padding, use_depthwise=use_depthwise, override_base_feature_extractor_hyperparams= override_base_feature_extractor_hyperparams) class RetinaNet101FeatureExtractor(RetinaNetFeatureExtractor): """Resnet 101 RetinaNet feature extractor.""" def __init__(self, is_training, depth_multiplier, min_depth, conv_hyperparams_fn, pad_to_multiple, backbone='resnet101', additional_layer_depth=256, reuse_weights=None, use_explicit_padding=False, use_depthwise=False, override_base_feature_extractor_hyperparams=False): """ Args: is_training: whether the network is in training mode. depth_multiplier: float depth multiplier for feature extractor. UNUSED currently. min_depth: minimum feature extractor depth. UNUSED Currently. pad_to_multiple: the nearest multiple to zero pad the input height and width dimensions to. additional_layer_depth: additional feature map layer channel depth. reuse_weights: Whether to reuse variables. Default is None. use_explicit_padding: Whether to use explicit padding when extracting features. Default is False. UNUSED currently. use_depthwise: Whether to use depthwise convolutions. UNUSED currently. override_base_feature_extractor_hyperparams: Whether to override hyperparameters of the base feature extractor with the one from `conv_hyperparams_fn`. """ super(RetinaNet101FeatureExtractor, self).__init__( is_training=is_training, depth_multiplier=depth_multiplier, min_depth=min_depth, conv_hyperparams_fn=conv_hyperparams_fn, pad_to_multiple=pad_to_multiple, backbone='resnet101', fpn_scope_name='retinanet101', additional_layer_depth=additional_layer_depth, reuse_weights=reuse_weights, use_explicit_padding=use_explicit_padding, use_depthwise=use_depthwise, override_base_feature_extractor_hyperparams= override_base_feature_extractor_hyperparams)
43.624434
92
0.695467
246720425b71f6f9968abd5573e054fe3530dbbb
1,943
py
Python
csc301-winter-2020/assignments/assignment2/coverage_grader.py
shibshib/gitomator-classroom
7d3c504063ebf8cb34de3872f78baf86fdbeec52
[ "MIT" ]
null
null
null
csc301-winter-2020/assignments/assignment2/coverage_grader.py
shibshib/gitomator-classroom
7d3c504063ebf8cb34de3872f78baf86fdbeec52
[ "MIT" ]
null
null
null
csc301-winter-2020/assignments/assignment2/coverage_grader.py
shibshib/gitomator-classroom
7d3c504063ebf8cb34de3872f78baf86fdbeec52
[ "MIT" ]
null
null
null
import xmltodict import json import argparse from loguru import logger import os COV_GRADE_FILE = "coverage_grade.txt" def evaluate_line_rate(line_rate): logger.info("Evaluating line rate of {}".format(line_rate)) grade = 0 if line_rate > 90: grade = 35 elif line_rate > 80 and line_rate < 90: grade = 30 elif line_rate > 70 and line_rate < 80: grade = 25 elif line_rate > 60 and line_rate < 70: grade = 20 return grade def extract_folderpath(filepath): return os.path.dirname(os.path.abspath(filepath)) def generate_json_file(xml_file, json_file): with open(xml_file) as in_file: xml = in_file.read() with open(json_file, 'w+') as out_file: json_coverage = xmltodict.parse(xml) json.dump(xmltodict.parse(xml), out_file) return json_coverage def analyze_tests_coverage(coverage_grade_file_location, coverage): grade_file = "{}/{}".format(coverage_grade_file_location, COV_GRADE_FILE) coverage = coverage['coverage'] if coverage: line_rate = coverage.get("@line-rate") grade = evaluate_line_rate(float(line_rate)*100) with open(grade_file, 'w+') as grade_file: grade_file.write("Coverage grade: {}".format(grade)) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( '--xml_file', default='./autograder_coverage.xml', type=str, help='Path to coverage XML file.' ) parser.add_argument( '--json_file', default='./autograder_coverage.json', type=str, help='Path to target JSON file.' ) args = parser.parse_args() json_coverage = generate_json_file(args.xml_file, args.json_file) coverage_grade_file_location = extract_folderpath(args.json_file) analyze_tests_coverage(coverage_grade_file_location, json_coverage)
29.439394
77
0.661863
c474dbb5f76c2f0fa6fc82e7ead58ed2c61d5cab
4,332
py
Python
metalibm_functions/unit_tests/function_formats.py
nibrunie/metalibm
776b044f5f323ef907a8724d9ce9a27a482f6cc5
[ "MIT" ]
2
2019-02-18T13:42:04.000Z
2021-03-12T18:54:53.000Z
metalibm_functions/unit_tests/function_formats.py
nibrunie/metalibm
776b044f5f323ef907a8724d9ce9a27a482f6cc5
[ "MIT" ]
null
null
null
metalibm_functions/unit_tests/function_formats.py
nibrunie/metalibm
776b044f5f323ef907a8724d9ce9a27a482f6cc5
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- ############################################################################### # This file is part of metalibm (https://github.com/kalray/metalibm) ############################################################################### # MIT License # # Copyright (c) 2018 Kalray # # 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. ############################################################################### # last-modified: Mar 7th, 2018 # Author(s): Nicolas Brunie <nbrunie@kalray.eu> ############################################################################### import sys from metalibm_core.core.ml_function import ML_Function, ML_FunctionBasis from metalibm_core.core.attributes import ML_Debug from metalibm_core.core.ml_operations import * from metalibm_core.core.ml_formats import * from metalibm_core.core.ml_complex_formats import ML_Mpfr_t from metalibm_core.code_generation.c_code_generator import CCodeGenerator from metalibm_core.code_generation.generic_processor import GenericProcessor from metalibm_core.code_generation.mpfr_backend import MPFRProcessor from metalibm_core.code_generation.code_object import CodeObject from metalibm_core.code_generation.code_function import CodeFunction from metalibm_core.code_generation.code_constant import C_Code from metalibm_core.core.ml_optimization_engine import OptimizationEngine from metalibm_core.core.polynomials import * from metalibm_core.core.ml_table import ML_Table from metalibm_core.code_generation.gappa_code_generator import GappaCodeGenerator from metalibm_core.utility.gappa_utils import execute_gappa_script_extract from metalibm_core.utility.ml_template import * from metalibm_core.utility.arg_utils import test_flag_option, extract_option_value from metalibm_core.utility.debug_utils import * class ML_UT_FunctionFormat(ML_Function("ml_ut_function_format")): def __init__(self, args=DefaultArgTemplate): # initializing base class ML_FunctionBasis.__init__(self, args) @staticmethod def get_default_args(**kw): """ Return a structure containing the arguments for current class, builtin from a default argument mapping overloaded with @p kw """ default_args = { "output_file": "ut_function_format.c", "function_name": "ut_function_format", "precision": ML_Binary32, "target": MPFRProcessor(), "fast_path_extract": True, "fuse_fma": True, "libm_compliant": True } default_args.update(kw) return DefaultArgTemplate(**default_args) def generate_scheme(self): #func_implementation = CodeFunction(self.function_name, output_format = self.precision) vx = self.implementation.add_input_variable("x", self.get_input_precision()) mpfr_x = Conversion(vx, precision = ML_Mpfr_t) result = mpfr_x + mpfr_x result.set_precision(ML_Mpfr_t) scheme = Statement(Return(Conversion(result, precision = self.precision))) return scheme def run_test(args): ml_ut_function_format = ML_UT_FunctionFormat(args) ml_ut_function_format.gen_implementation() return True if __name__ == "__main__": # auto-test arg_template = ML_NewArgTemplate(default_arg=ML_UT_FunctionFormat.get_default_args()) args = arg_template.arg_extraction() if run_test(args): exit(0) else: exit(1)
39.381818
91
0.724608
aa6a7f67ae524865af85cc0252b61c21372e92c1
12,276
py
Python
official/resnet/imagenet_main.py
kichiro09/object-detection
b7087955bb5f2689b0ef42ab5400931cd8f416b6
[ "Apache-2.0" ]
48
2018-12-19T13:09:14.000Z
2021-11-12T12:04:36.000Z
official/resnet/imagenet_main.py
bhushan23/models
e498d28503fd4a12d1fa9ade41891f2f9601c674
[ "Apache-2.0" ]
12
2018-12-13T18:04:36.000Z
2019-06-14T20:49:33.000Z
official/resnet/imagenet_main.py
bhushan23/models
e498d28503fd4a12d1fa9ade41891f2f9601c674
[ "Apache-2.0" ]
44
2018-11-09T21:04:52.000Z
2019-06-24T07:40:28.000Z
# Copyright 2017 The TensorFlow 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. # ============================================================================== """Runs a ResNet model on the ImageNet dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import app as absl_app from absl import flags import tensorflow as tf # pylint: disable=g-bad-import-order from official.utils.flags import core as flags_core from official.utils.logs import logger from official.resnet import imagenet_preprocessing from official.resnet import resnet_model from official.resnet import resnet_run_loop _DEFAULT_IMAGE_SIZE = 224 _NUM_CHANNELS = 3 _NUM_CLASSES = 1001 _NUM_IMAGES = { 'train': 1281167, 'validation': 50000, } _NUM_TRAIN_FILES = 1024 _SHUFFLE_BUFFER = 10000 DATASET_NAME = 'ImageNet' ############################################################################### # Data processing ############################################################################### def get_filenames(is_training, data_dir): """Return filenames for dataset.""" if is_training: return [ os.path.join(data_dir, 'train-%05d-of-01024' % i) for i in range(_NUM_TRAIN_FILES)] else: return [ os.path.join(data_dir, 'validation-%05d-of-00128' % i) for i in range(128)] def _parse_example_proto(example_serialized): """Parses an Example proto containing a training example of an image. The output of the build_image_data.py image preprocessing script is a dataset containing serialized Example protocol buffers. Each Example proto contains the following fields (values are included as examples): image/height: 462 image/width: 581 image/colorspace: 'RGB' image/channels: 3 image/class/label: 615 image/class/synset: 'n03623198' image/class/text: 'knee pad' image/object/bbox/xmin: 0.1 image/object/bbox/xmax: 0.9 image/object/bbox/ymin: 0.2 image/object/bbox/ymax: 0.6 image/object/bbox/label: 615 image/format: 'JPEG' image/filename: 'ILSVRC2012_val_00041207.JPEG' image/encoded: <JPEG encoded string> Args: example_serialized: scalar Tensor tf.string containing a serialized Example protocol buffer. Returns: image_buffer: Tensor tf.string containing the contents of a JPEG file. label: Tensor tf.int32 containing the label. bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. """ # Dense features in Example proto. feature_map = { 'image/encoded': tf.FixedLenFeature([], dtype=tf.string, default_value=''), 'image/class/label': tf.FixedLenFeature([], dtype=tf.int64, default_value=-1), 'image/class/text': tf.FixedLenFeature([], dtype=tf.string, default_value=''), } sparse_float32 = tf.VarLenFeature(dtype=tf.float32) # Sparse features in Example proto. feature_map.update( {k: sparse_float32 for k in ['image/object/bbox/xmin', 'image/object/bbox/ymin', 'image/object/bbox/xmax', 'image/object/bbox/ymax']}) features = tf.parse_single_example(example_serialized, feature_map) label = tf.cast(features['image/class/label'], dtype=tf.int32) xmin = tf.expand_dims(features['image/object/bbox/xmin'].values, 0) ymin = tf.expand_dims(features['image/object/bbox/ymin'].values, 0) xmax = tf.expand_dims(features['image/object/bbox/xmax'].values, 0) ymax = tf.expand_dims(features['image/object/bbox/ymax'].values, 0) # Note that we impose an ordering of (y, x) just to make life difficult. bbox = tf.concat([ymin, xmin, ymax, xmax], 0) # Force the variable number of bounding boxes into the shape # [1, num_boxes, coords]. bbox = tf.expand_dims(bbox, 0) bbox = tf.transpose(bbox, [0, 2, 1]) return features['image/encoded'], label, bbox def parse_record(raw_record, is_training, dtype): """Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a serialized Example protocol buffer. is_training: A boolean denoting whether the input is for training. dtype: data type to use for images/features. Returns: Tuple with processed image tensor and one-hot-encoded label tensor. """ image_buffer, label, bbox = _parse_example_proto(raw_record) image = imagenet_preprocessing.preprocess_image( image_buffer=image_buffer, bbox=bbox, output_height=_DEFAULT_IMAGE_SIZE, output_width=_DEFAULT_IMAGE_SIZE, num_channels=_NUM_CHANNELS, is_training=is_training) image = tf.cast(image, dtype) return image, label def input_fn(is_training, data_dir, batch_size, num_epochs=1, dtype=tf.float32, datasets_num_private_threads=None, num_parallel_batches=1): """Input function which provides batches for train or eval. Args: is_training: A boolean denoting whether the input is for training. data_dir: The directory containing the input data. batch_size: The number of samples per batch. num_epochs: The number of epochs to repeat the dataset. dtype: Data type to use for images/features datasets_num_private_threads: Number of private threads for tf.data. num_parallel_batches: Number of parallel batches for tf.data. Returns: A dataset that can be used for iteration. """ filenames = get_filenames(is_training, data_dir) dataset = tf.data.Dataset.from_tensor_slices(filenames) if is_training: # Shuffle the input files dataset = dataset.shuffle(buffer_size=_NUM_TRAIN_FILES) # Convert to individual records. # cycle_length = 10 means 10 files will be read and deserialized in parallel. # This number is low enough to not cause too much contention on small systems # but high enough to provide the benefits of parallelization. You may want # to increase this number if you have a large number of CPU cores. dataset = dataset.apply(tf.contrib.data.parallel_interleave( tf.data.TFRecordDataset, cycle_length=10)) return resnet_run_loop.process_record_dataset( dataset=dataset, is_training=is_training, batch_size=batch_size, shuffle_buffer=_SHUFFLE_BUFFER, parse_record_fn=parse_record, num_epochs=num_epochs, dtype=dtype, datasets_num_private_threads=datasets_num_private_threads, num_parallel_batches=num_parallel_batches ) def get_synth_input_fn(dtype): return resnet_run_loop.get_synth_input_fn( _DEFAULT_IMAGE_SIZE, _DEFAULT_IMAGE_SIZE, _NUM_CHANNELS, _NUM_CLASSES, dtype=dtype) ############################################################################### # Running the model ############################################################################### class ImagenetModel(resnet_model.Model): """Model class with appropriate defaults for Imagenet data.""" def __init__(self, resnet_size, data_format=None, num_classes=_NUM_CLASSES, resnet_version=resnet_model.DEFAULT_VERSION, dtype=resnet_model.DEFAULT_DTYPE): """These are the parameters that work for Imagenet data. Args: resnet_size: The number of convolutional layers needed in the model. data_format: Either 'channels_first' or 'channels_last', specifying which data format to use when setting up the model. num_classes: The number of output classes needed from the model. This enables users to extend the same model to their own datasets. resnet_version: Integer representing which version of the ResNet network to use. See README for details. Valid values: [1, 2] dtype: The TensorFlow dtype to use for calculations. """ # For bigger models, we want to use "bottleneck" layers if resnet_size < 50: bottleneck = False else: bottleneck = True super(ImagenetModel, self).__init__( resnet_size=resnet_size, bottleneck=bottleneck, num_classes=num_classes, num_filters=64, kernel_size=7, conv_stride=2, first_pool_size=3, first_pool_stride=2, block_sizes=_get_block_sizes(resnet_size), block_strides=[1, 2, 2, 2], resnet_version=resnet_version, data_format=data_format, dtype=dtype ) def _get_block_sizes(resnet_size): """Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Args: resnet_size: The number of convolutional layers needed in the model. Returns: A list of block sizes to use in building the model. Raises: KeyError: if invalid resnet_size is received. """ choices = { 18: [2, 2, 2, 2], 34: [3, 4, 6, 3], 50: [3, 4, 6, 3], 101: [3, 4, 23, 3], 152: [3, 8, 36, 3], 200: [3, 24, 36, 3] } try: return choices[resnet_size] except KeyError: err = ('Could not find layers for selected Resnet size.\n' 'Size received: {}; sizes allowed: {}.'.format( resnet_size, choices.keys())) raise ValueError(err) def imagenet_model_fn(features, labels, mode, params): """Our model_fn for ResNet to be used with our Estimator.""" # Warmup and higher lr may not be valid for fine tuning with small batches # and smaller numbers of training images. if params['fine_tune']: warmup = False base_lr = .1 else: warmup = True base_lr = .128 learning_rate_fn = resnet_run_loop.learning_rate_with_decay( batch_size=params['batch_size'], batch_denom=256, num_images=_NUM_IMAGES['train'], boundary_epochs=[30, 60, 80, 90], decay_rates=[1, 0.1, 0.01, 0.001, 1e-4], warmup=warmup, base_lr=base_lr) return resnet_run_loop.resnet_model_fn( features=features, labels=labels, mode=mode, model_class=ImagenetModel, resnet_size=params['resnet_size'], weight_decay=1e-4, learning_rate_fn=learning_rate_fn, momentum=0.9, data_format=params['data_format'], resnet_version=params['resnet_version'], loss_scale=params['loss_scale'], loss_filter_fn=None, dtype=params['dtype'], fine_tune=params['fine_tune'] ) def define_imagenet_flags(): resnet_run_loop.define_resnet_flags( resnet_size_choices=['18', '34', '50', '101', '152', '200']) flags.adopt_module_key_flags(resnet_run_loop) flags_core.set_defaults(train_epochs=90) def run_imagenet(flags_obj): """Run ResNet ImageNet training and eval loop. Args: flags_obj: An object containing parsed flag values. """ input_function = (flags_obj.use_synthetic_data and get_synth_input_fn(flags_core.get_tf_dtype(flags_obj)) or input_fn) resnet_run_loop.resnet_main( flags_obj, imagenet_model_fn, input_function, DATASET_NAME, shape=[_DEFAULT_IMAGE_SIZE, _DEFAULT_IMAGE_SIZE, _NUM_CHANNELS]) def main(_): with logger.benchmark_context(flags.FLAGS): run_imagenet(flags.FLAGS) if __name__ == '__main__': tf.logging.set_verbosity(tf.logging.INFO) define_imagenet_flags() absl_app.run(main)
34.386555
80
0.678804
78de34db1136d45b305fa61e25c62b02195ed359
168
py
Python
Pcolors/shortcuts/__init__.py
rafalou38/Pcolors
a4dc57c57d6a142a23a8ce8bc422581028fc8abd
[ "MIT" ]
1
2020-08-31T09:45:28.000Z
2020-08-31T09:45:28.000Z
Pcolors/shortcuts/__init__.py
rafalou38/Pcolors
a4dc57c57d6a142a23a8ce8bc422581028fc8abd
[ "MIT" ]
null
null
null
Pcolors/shortcuts/__init__.py
rafalou38/Pcolors
a4dc57c57d6a142a23a8ce8bc422581028fc8abd
[ "MIT" ]
null
null
null
from . import dark, light, format def to_bg(id): """ :param id: id of a color (light or dark) :return: id of the color for background """ return str(int(id) + 10)
21
41
0.654762
80bc55b42901ad1ac86043ba360ea5d3fe5ba8b1
9,865
py
Python
src/retroasm/asm_parser.py
mthuurne/retroasm
90b6617f7b24da05f55efceb1447314b251192e8
[ "MIT" ]
2
2019-11-29T22:57:42.000Z
2022-03-29T21:31:47.000Z
src/retroasm/asm_parser.py
mthuurne/retroasm
90b6617f7b24da05f55efceb1447314b251192e8
[ "MIT" ]
null
null
null
src/retroasm/asm_parser.py
mthuurne/retroasm
90b6617f7b24da05f55efceb1447314b251192e8
[ "MIT" ]
null
null
null
from __future__ import annotations from logging import getLogger from pathlib import Path from typing import Iterable, Iterator from .asm_directives import DataDirective, OriginDirective, StringDirective from .expression import Expression, IntLiteral, truncate from .expression_nodes import IdentifierNode, NumberNode, ParseError, parseDigits from .instrset import InstructionSet from .linereader import DelayedError, InputLocation, LineReader from .reference import FixedValueReference from .symbol import SymbolValue from .tokens import TokenEnum, Tokenizer from .types import IntType, unlimited from .utils import bad_type logger = getLogger("parse-asm") class AsmToken(TokenEnum): number = r"\$\w+|%\w+|\d\w*|0[xXbB]\w+" word = r"[\w.]+" string = r'"[^"]*"|\'[^\']*\'' comment = r";.*$" symbol = r"." Token = tuple[AsmToken, InputLocation] def parse_number(location: InputLocation) -> NumberNode: """ Parse a numeric literal in one of several formats. Raise `ValueError` if the location does not contain a valid number. """ value = location.text if value[0] == "$": digits = value[1:] digit_width = 4 elif value[0] == "%": digits = value[1:] digit_width = 1 elif value[0] == "0" and len(value) >= 2 and value[1] in "xXbB": digits = value[2:] digit_width = 4 if value[1] in "xX" else 1 elif value[-1].isdigit(): # Decimal numbers have no integer per-digit width. return NumberNode(parseDigits(value, 10), unlimited, location) else: digits = value[:-1] try: digit_width = {"b": 1, "h": 4}[value[-1].casefold()] except KeyError: raise ValueError(f'bad number suffix "{value[-1]}"') from None return NumberNode( parseDigits(digits, 1 << digit_width), len(digits) * digit_width, location ) def create_match_sequence( nodes: Iterable[IdentifierNode | NumberNode], ) -> Iterator[type[int] | str]: """Convert tokens to a match sequence.""" for node in nodes: if isinstance(node, IdentifierNode): yield node.name elif isinstance(node, NumberNode): yield int else: bad_type(node) def parse_instruction( tokens: Tokenizer[AsmToken], reader: LineReader ) -> Iterator[IdentifierNode | NumberNode]: for kind, location in tokens: if kind is AsmToken.word: yield IdentifierNode(location.text, location) elif kind is AsmToken.symbol: # TODO: Treating symbols as identifiers is weird, but it works for now. yield IdentifierNode(location.text, location) elif kind is AsmToken.number: try: yield parse_number(location) except ValueError as ex: reader.error("%s", ex, location=location) elif kind is AsmToken.string: # Arbitrary strings are not allowed as instruction # operands, but single characters should be replaced # by their character numbers. value = location.text assert len(value) >= 2, value assert value[0] == value[-1], value if len(value) == 2: reader.error("empty string in instruction operand", location=location) elif len(value) == 3: yield NumberNode(ord(value[1]), 8, location) else: reader.error( "multi-character string in instruction operand", location=location, ) elif kind is AsmToken.comment: pass else: assert False, kind def build_instruction(tokens: Tokenizer[AsmToken], reader: LineReader) -> None: name = tokens.location try: with reader.checkErrors(): match_seq = tuple(create_match_sequence(parse_instruction(tokens, reader))) except DelayedError: return reader.info( "instruction %s", " ".join(str(elem) for elem in match_seq), location=name ) def parse_value(tokens: Tokenizer[AsmToken]) -> Expression: if (location := tokens.eat(AsmToken.number)) is not None: number = parse_number(location) return IntLiteral(number.value) elif (location := tokens.eat(AsmToken.word)) is not None: # We don't know at this stage whether a symbol is a label or a constant, # so assume the width is unlimited. return SymbolValue(location.text, unlimited) elif tokens.end: raise ParseError("missing value", tokens.location) else: # TODO: Implement. raise ParseError.withText( "unexpected token; expression parsing not implemented yet", tokens.location ) _data_widths = { "db": 8, "defb": 8, "dw": 16, "defw": 16, "dd": 32, "defd": 32, "dq": 64, "defq": 64, } def parse_directive( tokens: Tokenizer[AsmToken], instr_set: InstructionSet ) -> DataDirective | OriginDirective | StringDirective: # TODO: It would be good to store the expression locations, so we can print # a proper error report if we later discover the value is bad. name = tokens.eat(AsmToken.word) assert name is not None keyword = name.text.casefold() if (width := _data_widths.get(keyword)) is not None: data_type = IntType.u(width) data_class: type[DataDirective | StringDirective] = DataDirective data: list[FixedValueReference | bytes] = [] while True: if (location := tokens.eat(AsmToken.string)) is not None: if width != 8: raise ParseError( f'the "{keyword}" directive does not support string literals', location, ) data_class = StringDirective text = location.text assert text[0] == text[-1], text # TODO: Support other encodings? try: data.append(text[1:-1].encode("ascii")) except UnicodeError as ex: raise ParseError( f"string literal is not pure ASCII: {ex}", location ) from None else: value = parse_value(tokens) # TODO: I don't like the use of truncation here, since it might silence # errors. # One alternative would be to add an expression node that performs # a range check. Perhaps this could also store the location (see # TODO at the top of this function). # Another alternative would be to not use FixedValueReference for # storing the values. Instead, we could store expressions (ignore # width, since it's implied by the directive) or we could store # ASTs (preserves more of the original code when reformatting). data.append(FixedValueReference(truncate(value, width), data_type)) if tokens.end: break if tokens.eat(AsmToken.symbol, ",") is None: raise ParseError.withText( "unexpected token after value", tokens.location ) return data_class(*data) # type: ignore[arg-type] elif keyword == "org": addr = parse_value(tokens) if tokens.end: return OriginDirective(FixedValueReference(addr, instr_set.addrType)) else: raise ParseError.withText("unexpected token after value", tokens.location) else: raise ParseError.withText( "statement is not a known instruction or directive", name ) def parse_label(tokens: Tokenizer[AsmToken]) -> InputLocation | None: """Consume and return a label if one is defined at the start of this line.""" lookahead = tokens.copy() label = lookahead.eat(AsmToken.word) if label is None: return None elif lookahead.peek(AsmToken.symbol, ":"): # Explicit label declaration. tokens.eat(AsmToken.word) tokens.eat(AsmToken.symbol) return label elif lookahead.peek(AsmToken.word) and tokens.value.lower() == "equ": # EQU directive. tokens.eat(AsmToken.word) return label else: return None def parse_asm(reader: LineReader, instr_set: InstructionSet) -> None: instruction_names = instr_set.instructionNames for line in reader: tokens = AsmToken.scan(line) # Look for a label. label = parse_label(tokens) if label is not None: reader.info("label: %s", label.text, location=label) # Look for a directive or instruction. if tokens.peek(AsmToken.word): if tokens.value.casefold() in instruction_names: build_instruction(tokens, reader) else: location = tokens.location try: directive = parse_directive(tokens, instr_set) except ParseError as ex: reader.error("%s", ex, location=ex.locations) else: reader.info("directive: %s", directive, location=location) elif tokens.eat(AsmToken.comment) is not None: assert tokens.end, tokens.kind elif not tokens.end: reader.error( "expected directive or instruction, got %s", tokens.kind.name, location=tokens.location, ) def read_source(path: Path, instr_set: InstructionSet) -> None: with LineReader.open(path, logger) as reader: with reader.checkErrors(): parse_asm(reader, instr_set) reader.summarize()
36.402214
88
0.597567
bd3a0d0c2b71afda19f90c92c54c25c94c187e0e
744
py
Python
kubernetes_engine/django_tutorial/mysite/wsgi.py
yshalabi/python-docs-samples
591787c01d94102ba9205f998d95a05b39ccad2f
[ "Apache-2.0" ]
5,938
2015-05-18T05:04:37.000Z
2022-03-31T20:16:39.000Z
kubernetes_engine/django_tutorial/mysite/wsgi.py
yshalabi/python-docs-samples
591787c01d94102ba9205f998d95a05b39ccad2f
[ "Apache-2.0" ]
4,730
2015-05-07T19:00:38.000Z
2022-03-31T21:59:41.000Z
kubernetes_engine/django_tutorial/mysite/wsgi.py
yshalabi/python-docs-samples
591787c01d94102ba9205f998d95a05b39ccad2f
[ "Apache-2.0" ]
6,734
2015-05-05T17:06:20.000Z
2022-03-31T12:02:51.000Z
# Copyright 2015 Google 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 os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application()
32.347826
74
0.774194
df82a27c999d633f6a723a63f73f2a48e8f853e1
9,121
py
Python
libs/sdc_etl_libs/api_helpers/apis/Ultipro/UltiproServices.py
darknegma/docker-airflow
44e3d02d7ac43c8876145ae47acfbbbde67230df
[ "Apache-2.0" ]
null
null
null
libs/sdc_etl_libs/api_helpers/apis/Ultipro/UltiproServices.py
darknegma/docker-airflow
44e3d02d7ac43c8876145ae47acfbbbde67230df
[ "Apache-2.0" ]
3
2021-03-31T19:26:57.000Z
2021-12-13T20:33:01.000Z
libs/sdc_etl_libs/api_helpers/apis/Ultipro/UltiproServices.py
darknegma/docker-airflow
44e3d02d7ac43c8876145ae47acfbbbde67230df
[ "Apache-2.0" ]
null
null
null
import datetime import decimal import json import logging import zeep from sdc_etl_libs.api_helpers.apis.Ultipro.Ultipro import Ultipro from sdc_etl_libs.sdc_dataframe.Dataframe import Dataframe, SDCDFTypes from sdc_etl_libs.sdc_file_helpers.SDCFileHelpers import SDCFileHelpers logging.basicConfig(level=logging.INFO) class UltiproServices(Ultipro): def __init__(self): super().__init__() def convert_to_literals(self, dict_): """ Recursively travels a data set dictionary - at both the dictionary and list level - and converts Decimal() objects to literal floats and datetime.datetimes objects to literal datetime strings. :param dict_: Dictionary to evaluate. :return: None """ for key, value in dict_.items(): if isinstance(value, dict): self.convert_to_literals(value) elif isinstance(value, list): for num, item in enumerate(value): if isinstance(item, dict): self.convert_to_literals(item) else: if isinstance(value, decimal.Decimal): dict_[key] = float(value) elif isinstance(value, datetime.datetime): dict_[key] = value.strftime('%Y-%m-%d %H:%M:%S') def get_service(self, service_name_): """ Given an endpoint, creaetes the Zeep client, authenticates and returns the service function for use. :param service_name_: Ultipro SOAP service name. :return: Zeep client service for Ultipro endpoint. """ if service_name_ == 'FindCompensations': endpoint = 'EmployeeCompensation' zeep_client = zeep.Client(f"{self.base_url}{endpoint}") service = zeep_client.service.FindCompensations elif service_name_ == 'EmployeeEmploymentInformation': endpoint = "EmployeeEmploymentInformation" zeep_client = zeep.Client(f"{self.base_url}{endpoint}") service = zeep_client.service.FindEmploymentInformations elif service_name_ == 'FindLastPayStatement': endpoint = "EmployeePayStatement" zeep_client = zeep.Client(f"{self.base_url}{endpoint}") service = zeep_client.service.FindLastPayStatement else: raise Exception(f"{service_name_} is no currently supported.") self.soap_authenticate() return service, endpoint, zeep_client def process_endpoint(self, service_name_, query_=None, limit_=None): """ Processes an Ultipro SOAP endpoint. :param service_name_: Ultipro SOAP service name. :param query_: SOAP query as a dictionary. :param limit_: Page results limit. :return: Results as Zeep array object """ results = [] if query_ == None: query_ = {} elif query_ and not isinstance(query_, dict): raise Exception("Query for Ultipro SOAP must be in dictionary format.") # Paginate by updating the query in with a new PageNumber. The current_page # and total_pages are evaluated to determine if we got every page. To start, # set current_page to 1 and total_pages to 2 (to ensure the first call is made). # The first call will update to the correct total_pages. query_["PageNumber"] = "1" query_["PageSize"] = limit_ current_page = 1 total_pages = 2 service, endpoint, zeep_client = self.get_service(service_name_) while current_page < total_pages: response = service(_soapheaders=[self.session_header], query=query_) if response["OperationResult"]["Success"] == True: total_pages = int( response["OperationResult"]["PagingInfo"]["PageTotal"]) current_page = int( response["OperationResult"]["PagingInfo"]["CurrentPage"]) records = response["Results"][endpoint] if current_page == 1: logging.info(f"Total pages: {total_pages}.") results.extend(records) logging.info(f'Grabbed {query_["PageSize"]} record(s) from Page #{current_page}.') query_["PageNumber"] = \ str(int(response["OperationResult"]["PagingInfo"][ "CurrentPage"]) + 1) else: msg = response["OperationResult"]["Messages"] raise Exception(f"Grabbing from {endpoint} failed. {msg}") return results def convert_zeep_result_to_dict(self, data_): """ Converts a Ultipro Services Zeep array object to a list of flattened dictionaries. :param data_: Ultipro Services Zeep array to process. :return: List of flattened dictionaries. """ data = [] for result in data_: empId = dict(zeep.helpers.serialize_object(result, target_cls=dict)) empInfo = dict(empId.popitem()[1]).popitem()[1] for item in empInfo: item.update(empId) data.append(item) return data def get_employee_employement_information(self, query_=None, limit_=500): """ Processes Ultipro SOAP Employee Employment Information endpoint results. https://connect.ultipro.com/documentation#/api/1168 :param query_: SOAP query as a dictionary. :param limit_: Page results limit. :return: SDCDataFrame object with data in dataframe. """ file_name = SDCFileHelpers.get_file_path( "schema", "Ultipro/services/employee-employment-information.json") json_data = json.loads(open(file_name).read()) if "data_source" in json_data and json_data["data_source"][ "type"] == "api": self.base_url = json_data["data_source"]["base_url"] else: raise Exception("Missing data_source metadata in schema definition.") df = Dataframe(SDCDFTypes.PANDAS, json_data) results = self.process_endpoint('EmployeeEmploymentInformation', query_=query_, limit_=limit_) data = self.convert_zeep_result_to_dict(results) if len(data) >= 1: df.load_data(data) return df else: logging.warning("Received no data") return None def get_employee_compensation(self, query_=None, limit_=500): """ Processes Ultipro SOAP Employee Compensation endpoint results. https://connect.ultipro.com/documentation#/api/1144 :param query_: SOAP query as a dictionary. :param limit_: Page results limit. :return: SDCDataFrame object with data in dataframe. """ file_name = SDCFileHelpers.get_file_path( "schema", "Ultipro/services/employee-compensation.json") json_data = json.loads(open(file_name).read()) if "data_source" in json_data and json_data["data_source"][ "type"] == "api": self.base_url = json_data["data_source"]["base_url"] else: raise Exception("Missing data_source metadata in schema definition.") df = Dataframe(SDCDFTypes.PANDAS, json_data) results = self.process_endpoint('FindCompensations', query_=query_, limit_=limit_) data = self.convert_zeep_result_to_dict(results) if len(data) >= 1: df.load_data(data) return df else: logging.warning("Received no data") return None def get_employee_latest_pay_statement(self, query_=None, limit_=1000): """ Processes Ultipro SOAP Employee Pay Statement endpoint results. Pulls the most recent pay statement for each Employee in system. https://connect.ultipro.com/documentation#/api/1150 :param query_: SOAP query as a dictionary. :param limit_: Page results limit. :return: SDCDataFrame object with data in dataframe. """ file_name = SDCFileHelpers.get_file_path( "schema", "Ultipro/services/employee-pay-statement.json") json_data = json.loads(open(file_name).read()) if "data_source" in json_data and json_data["data_source"]["type"] == "api": self.base_url = json_data["data_source"]["base_url"] else: raise Exception("Missing data_source metadata in schema definition.") df = Dataframe(SDCDFTypes.PANDAS, json_data) results = self.process_endpoint('FindLastPayStatement', query_=query_, limit_=limit_) data = self.convert_zeep_result_to_dict(results) for i in data: self.convert_to_literals(i) if len(data) >= 1: df.load_data(data) df.drop_columns(["SSN"]) return df else: logging.warning("Received no data") return None
36.484
98
0.612871
1e2d427612b4edf234eaddeb1d90644a8def46ea
9,653
py
Python
vcx/wrappers/python3/demo/vcxdemo.py
dastardlychimp/indy-sdk
febdc881ccfba7a0b1b19e1c2c985142ff147548
[ "Apache-2.0" ]
null
null
null
vcx/wrappers/python3/demo/vcxdemo.py
dastardlychimp/indy-sdk
febdc881ccfba7a0b1b19e1c2c985142ff147548
[ "Apache-2.0" ]
2
2018-09-13T20:07:09.000Z
2021-12-29T20:52:05.000Z
vcx/wrappers/python3/demo/vcxdemo.py
dastardlychimp/indy-sdk
febdc881ccfba7a0b1b19e1c2c985142ff147548
[ "Apache-2.0" ]
1
2021-08-16T23:07:17.000Z
2021-08-16T23:07:17.000Z
from vcx.api.connection import Connection from demo.wait import wait_for_state from demo.vcxbase import VCXBase import json import asyncio from vcx.state import State from vcx.api.issuer_credential import IssuerCredential from vcx.api.schema import Schema from vcx.api.credential_def import CredentialDef from vcx.api.proof import Proof import qrcode ENTERPRISE_DID = '2hoqvcwupRTUNkXn6ArYzs' class Vcxdemo(VCXBase): proof_requests = {} schemas = [] credential_defs = {} did = ENTERPRISE_DID def __init__(self, source_id, details=None, phone_number='8888675309'): self.source_id = source_id self.details = details self.state = {} self.state['connection'] = State.Undefined self.state['credential'] = State.Undefined self.loop = Vcxdemo.get_loop() self.connection = None self.credential = None self.phone_number = phone_number self.invite_details = None @classmethod def set_did(cls, did): cls.did = did @classmethod def get_did(cls): return cls.did def create_qr_code(self, dest): img = qrcode.make(str(json.dumps(self.invite_details))) img.save(dest) async def _wait_for_credential_state(self, target_state): self.state['credential'] = await self.credential.update_state() while self.state['credential'] != target_state: print('waiting for credential to be [%s]...\ncurrent %s' % (target_state, self.state['credential'])) await asyncio.sleep(5) self.state['credential'] = await self.credential.update_state() print('Successful state change for credential to be [%s]...\ncurrent %s' % (target_state, self.state['credential'])) async def create_and_connect(self): self.connection = await Connection.create(self.source_id) self.state['connection'] = await self.connection.get_state() await self.connection.connect(self.phone_number) self.invite_details = await self.connection.invite_details(True) print('\n %s \n' % str(json.dumps(self.invite_details))) self.create_qr_code('./qrcode1.png') self.state['connection'] = await self.wait_for_connection_state(State.Accepted) def connect(self): self.loop.run_until_complete(asyncio.gather(self.create_and_connect())) def create_credential(self, schema_seq_number, attr, credential_name): self.loop.run_until_complete(asyncio.gather(self._create_credential(schema_seq_number, attr, credential_name))) async def _create_credential(self, schema_seq_number, attr, credential_name): self.credential = await IssuerCredential.create(self.source_id, attr, schema_seq_number, credential_name) def request_proof(self, proof_id): proof = self.get_proof_request(proof_id) res = Vcxdemo.get_loop().run_until_complete(proof.request_proof(self.connection)) async def _serialize_connection(self): return await self.connection.serialize() def serialize_connection(self): res = self.loop.run_until_complete(asyncio.gather(self._serialize_connection())) if len(res) > 0: return res[0] async def _serialize_credential(self): return await self.credential.serialize() def serialize_credential(self): res = self.loop.run_until_complete(asyncio.gather(self._serialize_credential())) if len(res) > 0: return res[0] async def _deserialize_connection(self, data): self.connection = await Connection.deserialize(data) async def _deserialize_credential(self, data): self.credential = await IssuerCredential.deserialize(data) def deserialize_connection(self, filename): try: with open(filename) as in_file: res = self.loop.run_until_complete(asyncio.gather(self._deserialize_connection(json.load(in_file)))) except IOError as e: print("Error opening file %s: %s" % (filename, e)) def deserialize_credential(self,filename): try: with open(filename) as in_file: res = self.loop.run_until_complete(asyncio.gather(self._deserialize_credential(json.load(in_file)))) except IOError as e: print("Error opening file %s: %s" % (filename, e)) async def _update_credential_state(self): self.state['credential'] = await self.credential.update_state() async def _update_proof_state(self, proof_id): await self.get_proof_request(proof_id).update_state() async def _get_proof_state(self, proof_id): return await self.get_proof_request(proof_id).get_state() def update_proof_state(self, proof_id): Vcxdemo.get_loop().run_until_complete(asyncio.gather(self._update_proof_state(proof_id))) def get_proof_state(self, proof_id): res = Vcxdemo.get_loop().run_until_complete(asyncio.gather(self._get_proof_state(proof_id))) return res[0] def update_credential_state(self): res = self.loop.run_until_complete(asyncio.gather(self._update_credential_state())) if len(res) > 0: return res[0] async def _send_offer(self): await self.credential.send_offer(self.connection) await self.credential.update_state() self.state['credential'] = await self.credential.get_state() def issue_credential_offer(self): res = self.loop.run_until_complete(asyncio.gather(self._send_offer())) if len(res) > 0: return res[0] async def _send_issuer_credential(self): await self.credential.send_credential(self.connection) await self.credential.update_state() def send_issuer_credential(self): res = self.loop.run_until_complete(asyncio.gather(self._send_issuer_credential())) if len(res) > 0: return res[0] @classmethod def create_schema(cls, source_id: str, name: str, attr: dict): res = Vcxdemo.get_loop().run_until_complete(asyncio.gather(Vcxdemo._create_schema(source_id, name, attr))) print(res[0]) cls.schemas.append(res[0]) @classmethod def get_schema(cls, index): return cls.schemas[index] @classmethod def serialize_schema(cls, schema_number): res = Vcxdemo.get_loop().run_until_complete(asyncio.gather( cls._serialize_schema(cls.schemas[schema_number]))) if len(res) > 0: return res[0] @classmethod def get_schema_sequence_number(cls, index): res = Vcxdemo.get_loop().run_until_complete(asyncio.gather(cls.schemas[index].get_sequence_number())) return res[0] @classmethod def deserialize_schema(cls, filename): try: with open(filename, 'r') as in_file: data = json.load(in_file) res = Vcxdemo.get_loop().run_until_complete(asyncio.gather(Schema.deserialize(data))) cls.schemas.append(res[0]) except IOError as e: print('Error opening %s: %s', (filename, e)) @classmethod def create_credential_def(cls, source_id, name, schema_number, revocation=False): cls.credential_defs[name] = Vcxdemo.get_loop().run_until_complete(CredentialDef.create(source_id, name, schema_number, revocation)) def create_proof_request(self, source_id, name, proof_attr): res = Vcxdemo.get_loop().run_until_complete(asyncio.gather(Proof.create(source_id, name, proof_attr))) if len(res) > 0: self.proof_requests[source_id] = res[0] def get_proof_request(self, source_id): return self.proof_requests[source_id] @classmethod def get_schema_attr_list(cls, index): return cls.schemas[index].attrs async def _wait_for_proof_state(self, proof_id, target_state): proof = self.get_proof_request(proof_id) state = await proof.get_state() while state != target_state: print('waiting for Proof Request %s to be [%s]...\ncurrent %s' % (proof_id, target_state, state)) await asyncio.sleep(5) await proof.update_state() state = await proof.get_state() print('Successful state change for Proof Request %s to [%s]...\ncurrent %s' % (proof_id, target_state, state)) async def wait_for_connection_state(self, target_state): await self.connection.update_state() state = await self.connection.get_state() while state != target_state: print('waiting for connection to be accepted...\ncurrent %s' % state) await asyncio.sleep(5) await self.connection.update_state() state = await self.connection.get_state() return state def wait_for_credential_state(self, target_state): self.loop.run_until_complete(asyncio.gather(self._wait_for_credential_state(target_state))) def wait_for_proof_state(self, proof_id, target_state): proof = self.get_proof_request(proof_id) Vcxdemo.get_loop().run_until_complete(asyncio.gather(self._wait_for_proof_state(proof_id, target_state))) # Vcxdemo.get_loop().run_until_complete(asyncio.gather(wait_for_state(proof, target_state))) def retrieve_proof(self, proof_id): proof = self.get_proof_request(proof_id) res = Vcxdemo.get_loop().run_until_complete(asyncio.gather(proof.get_proof(self.connection))) print(res[0]) if len(res) > 0: return res[0] else: return None
39.88843
139
0.673469
7f56bbf8631758a7a2a0a36430ae46dd483f58fc
61,876
py
Python
src/sage/symbolic/units.py
bopopescu/classic_diff_geom
2b1d88becbc8cb30962e0995cc78e429e0f5589f
[ "BSL-1.0" ]
null
null
null
src/sage/symbolic/units.py
bopopescu/classic_diff_geom
2b1d88becbc8cb30962e0995cc78e429e0f5589f
[ "BSL-1.0" ]
null
null
null
src/sage/symbolic/units.py
bopopescu/classic_diff_geom
2b1d88becbc8cb30962e0995cc78e429e0f5589f
[ "BSL-1.0" ]
1
2020-07-24T12:08:30.000Z
2020-07-24T12:08:30.000Z
""" Units of measurement This is the units package. It contains information about many units and conversions between them. TUTORIAL: To return a unit:: sage: units.length.meter meter This unit acts exactly like a symbolic variable:: sage: s = units.length.meter sage: s^2 meter^2 sage: s + var('x') meter + x Units have additional information in their docstring:: sage: # You would type: units.force.dyne? sage: print units.force.dyne._sage_doc_() CGS unit for force defined to be gram*centimeter/second^2. Equal to 10^-5 newtons. You may call the convert function with units:: sage: t = units.mass.gram*units.length.centimeter/units.time.second^2 sage: t.convert(units.mass.pound*units.length.foot/units.time.hour^2) 5400000000000/5760623099*(foot*pound/hour^2) sage: t.convert(units.force.newton) 1/100000*newton Calling the convert function with no target returns base SI units:: sage: t.convert() 1/100000*kilogram*meter/second^2 Giving improper units to convert to raises a ValueError:: sage: t.convert(units.charge.coulomb) Traceback (most recent call last): ... ValueError: Incompatible units Converting temperatures works as well:: sage: s = 68*units.temperature.fahrenheit sage: s.convert(units.temperature.celsius) 20*celsius sage: s.convert() 293.150000000000*kelvin Trying to multiply temperatures by another unit then converting raises a ValueError:: sage: wrong = 50*units.temperature.celsius*units.length.foot sage: wrong.convert() Traceback (most recent call last): ... ValueError: Cannot convert TESTS: Check that Trac 12373 if fixed:: sage: b = units.amount_of_substance.mole sage: b.convert(units.amount_of_substance.elementary_entity) 6.02214129000000e23*elementary_entity AUTHORS: - David Ackerman - William Stein """ ############################################################################### # Sage: Open Source Mathematical Software # Copyright (C) 2009 David Ackerman <davidnackerman@gmail.com> # William Stein <wstein@gmail.com> # Distributed under the terms of the GNU General Public License (GPL), # version 2 or any later version. The full text of the GPL is available at: # http://www.gnu.org/licenses/ ############################################################################### # standard Python libraries import re # Sage library from ring import SR from expression import Expression ############################################################################### # Unit conversions dictionary. ############################################################################### unitdict = { 'acceleration': {'gal':'1/100', 'galileo':'1/100', 'gravity':'9.80665000000000'}, 'amount_of_substance': {'elementary_entity':'1/6.02214129000000e23', 'mole':'1'}, 'angles': {'arc_minute':'1/10800*pi', 'arc_second':'1/648000*pi', 'degree':'1/180*pi', 'grade':'1/200*pi', 'quadrant':'1/2*pi', 'radian':'1', 'right_angle':'1/2*pi'}, 'area': {'acre':'316160658/78125', 'are':'100', 'barn':'1/10000000000000000000000000000', 'hectare':'10000', 'rood':'158080329/156250', 'section':'40468564224/15625', 'square_chain':'158080329/390625', 'square_meter':'1', 'township':'1456868312064/15625'}, 'capacitance': {'abfarad':'1000000000', 'farad':'1', 'statfarad':'25000/22468879468420441'}, 'charge': {'abcoulomb':'10', 'coulomb':'1', 'elementary_charge':'1.60217646200000e-19', 'faraday':'96485.3399000000', 'franklin':'1/2997924580', 'statcoulomb':'1/2997924580'}, 'conductance': {'abmho':'1000000000', 'mho':'1', 'siemens':'1'}, 'current': {'abampere':'10', 'amp':'1', 'ampere':'1', 'biot':'10', 'statampere':'1/2997924580'}, 'electric_potential': {'abvolt':'1/100000000', 'statvolt':'149896229/500000', 'volt':'1'}, 'energy': {'british_thermal_unit':'52752792631/50000000', 'btu':'52752792631/50000000', 'calorie':'10467/2500', 'electron_volt':'1.60217733000000e-19', 'erg':'1/10000000', 'ev':'1.60217733000000e-19', 'joule':'1', 'rydberg':'2.17987200000000e-18', 'therm':'52752792631/500'}, 'fiber_linear_mass_density': {'denier':'1/9000000', 'tex':'1/1000000'}, 'force': {'dyne':'1/100000', 'gram_weight':'196133/20000000', 'kilogram_force':'196133/20000', 'kilogram_weight':'196133/20000', 'newton':'1', 'pound_force':'8896443230521/2000000000000', 'pound_weight':'8896443230521/2000000000000', 'poundal':'17281869297/125000000000', 'ton_force':'8896443230521/1000000000'}, 'frequency': {'1/second':'1', 'hertz':'1'}, 'illuminance': {'foot_candle':'1562500/145161', 'lux':'1', 'phot':'10000'}, 'inductance': {'abhenry':'1/1000000000', 'henry':'1', 'stathenry':'22468879468420441/25000'}, 'information': {'bit':'1', 'byte':'8', 'nibble':'4'}, 'information_rate': {'baud':'1'}, 'inverse_length': {'diopter':'1', 'kayser':'100'}, 'length': {'angstrom':'1/10000000000', 'astronomical_unit':'149597870691', 'bolt':'4572/125', 'cable_international':'926/5', 'cable_us':'27432/125', 'caliber':'127/500000', 'centimeter':'1/100', 'chain':'12573/625', 'cicero':'125/27706', 'cubit':'1143/2500', 'didot':'125/332472', 'dtp_point':'127/360000', 'ell':'1143/1000', 'fathom':'1143/625', 'feet':'381/1250', 'fermi':'1/1000000000000000', 'foot':'381/1250', 'furlong':'25146/125', 'hand':'127/1250', 'inch':'127/5000', 'kilometer':'1000', 'league':'603504/125', 'light_year':'9460730472580800', 'link':'12573/62500', 'meter':'1', 'micron':'1/1000000', 'mil':'127/5000000', 'millimeter':'1/1000', 'mile':'201168/125', 'nautical_mile':'1852', 'parsec':'3.08570000000000e16', 'perch':'12573/2500', 'pica':'127/30000', 'pole':'12573/2500', 'rod':'12573/2500', 'rope':'762/125', 'skein':'13716/125', 'stadion':'118491/625', 'stadium':'115443/625', 'statute_mile':'201168/125', 'survey_foot':'1200/3937', 'survey_mile':'6336000/3937', 'x_unit':'1.00210000000000e-13', 'yard':'1143/1250'}, 'luminance': {'apostilb':'1/pi', 'lambert':'10000/pi', 'nit':'1', 'stilb':'10000'}, 'luminous_energy': {'lumerg':'1', 'talbot':'1'}, 'luminous_flux': {'lumen':'1'}, 'luminous_intensity': {'candela':'1', 'candle':'1', 'hefnerkerze':'1019/1128'}, 'magnetic_field': {'gauss':'1/10000', 'tesla':'1'}, 'magnetic_flux': {'maxwell':'1/100000000', 'weber':'1'}, 'magnetic_intensity': {'oersted':'250/pi'}, 'magnetic_moment': {'bohr_magneton':'9.27400915000000e-24', 'nuclear_magneton':'5.05078324000000e-27'}, 'magnetomotive_force': {'ampere_turn':'1', 'gilbert':'5/2/pi'}, 'mass': {'amu':'1.66053878200000e-27', 'assay_ton':'7/240', 'atomic_mass_unit':'1.66053878200000e-27', 'avoirdupois_ounce':'45359237/1600000000', 'avoirdupois_pound':'45359237/100000000', 'bale':'45359237/200000', 'carat':'1/5000', 'cental':'45359237/1000000', 'dalton':'1.66053878200000e-27', 'drachma':"(0.00429234000000000, {'greek':1})", 'geepound':'14593903/1000000', 'grain':'6479891/100000000000', 'gram':'1/1000', 'gross_hundredweight':'317514659/6250000', 'hundredweight':'317514659/6250000', 'kilogram':'1', 'libra':'0.325971000000000', 'long_ton':'317514659/312500', 'metric_ton':'1000', 'mina':"(0.429234000000000, {'greek':100})", 'net_hundredweight':'45359237/1000000', 'obol':"(0.000715380000000000,{'greek':1/6})", 'ounce':'45359237/1600000000', 'ounce_troy':'19439673/625000000', 'pennyweight':'19439673/12500000000', 'pondus':'0.325969000000000', 'pound':'45359237/100000000', 'pound_troy':'58319019/156250000', 'quintal':'100', 'shekel':'0.0141000000000000', 'short_hundredweight':'45359237/1000000', 'short_ton':'45359237/50000', 'slug':'14593903/1000000', 'solar_mass':'1.98892000000000e30', 'stone':'317514659/50000000', 'talent':"(25.7540400000000, {'greek':6000})", 'ton':'45359237/50000', 'tonne':'1000', 'wey':'2857631931/25000000'}, 'power': {'cheval_vapeur':'588399/800', 'horsepower':'37284993579113511/50000000000000', 'watt':'1'}, 'pressure': {'atmosphere':'101325', 'bar':'100000', 'barye':'1/10', 'inch_mercury':'3386.38900000000', 'millimeter_mercury':'133.322400000000', 'mmhg':'133.322400000000', 'pa':'1', 'pascal':'1', 'pounds_per_square_inch':'8896443230521/1290320000', 'psi':'8896443230521/1290320000', 'torr':'20265/152'}, 'radiation': {'becquerel':'1', 'curie':'37000000000', 'rutherford':'1000000'}, 'radiation_absorbed': {'gray':'1', 'rad':'1/100'}, 'radiation_ionizing': {'roentgen':'0.000258000000000000', 'rontgen':'0.000258000000000000'}, 'resistance': {'abohm':'1/1000000000', 'ohm':'1', 'statohm':'22468879468420441/25000'}, 'si_prefixes': {'atto':'1/1000000000000000000', 'centi':'1/100', 'deca':'10', 'deci':'1/10', 'exa':'1000000000000000000', 'femto':'1/1000000000000000', 'giga':'1000000000', 'hecto':'100', 'kilo':'1000', 'mega':'1000000', 'micro':'1/1000000', 'milli':'1/1000', 'nano':'1/1000000000', 'peta':'1000000000000000', 'pico':'1/1000000000000', 'tera':'1000000000000', 'yocto':'1/1000000000000000000000000', 'yotta':'1000000000000000000000000', 'zepto':'1/1000000000000000000000', 'zetta':'1000000000000000000000'}, 'solid_angle': {'steradian':'1'}, 'temperature': {'celsius':'(x + 273.15), (x), (x*9/5 + 32), ((x+273.15)*9/5)', 'centigrade':'(x + 273.15), (x), (x*9/5 + 32), ((x+273.15)*9/5)', 'fahrenheit':'(5/9*(x + 459.67)), ((x - 32)*5/9), (x), (x+459.67)', 'kelvin':'(x), (x - 273.15), (x*9/5 - 459.67), (x*9/5)', 'rankine':'(5/9*x), ((x-491.67)*5/9), (x-459.67), (x)'}, 'time': {'century':'3153600000', 'day':'86400', 'decade':'315360000', 'fortnight':'1209600', 'hour':'3600', 'millenium':'31536000000', 'minute':'60', 'month':'2628000', 'second':'1', 'sidereal_day':"(86164.0905308330, {'sidereal':86400})", 'sidereal_second':"(0.997269566329086, {'sidereal':1})", 'sidereal_year':'3.15581497632000e7', 'tropical_year':'3.15569251779840e7', 'week':'604800', 'year':'31536000'}, 'unit_multipliers': {'bakers_dozen':'13', 'dozen':'12', 'gross':'144', 'percent':'1/100'}, 'velocity': {'knot':'463/900'}, 'viscosity_absolute': {'poise':'1/10', 'reyn':'8896443230521/1290320000'}, 'viscosity_kinematic': {'stokes':'1/10000'}, 'viscosity_other': {'rhes':'10'}, 'volume': {'bag':'660732565629/6250000000000', 'barrel':'9936705933/62500000000', 'board_foot':'18435447/7812500000', 'bucket':'473176473/31250000000', 'bushel':'220244188543/6250000000000', 'butt':'29810117799/62500000000', 'cord':'884901456/244140625', 'cubic_meter':'1', 'cup':'473176473/2000000000000', 'ephah':'1982197696887/50000000000000', 'fifth':'473176473/625000000000', 'firkin':'4091481/100000000', 'fluid_dram':'473176473/128000000000000', 'fluid_ounce':'473176473/16000000000000', 'gallon':'473176473/125000000000', 'gill':'473176473/4000000000000', 'hogshead':'29810117799/125000000000', 'imperial_gallon':'454609/100000000', 'imperial_pint':'454609/800000000', 'jeroboam':'473176473/156250000000', 'jigger':'1419529419/32000000000000', 'liter':'1/1000', 'magnum':'473176473/250000000000', 'minim':'157725491/2560000000000000', 'noggin':'473176473/4000000000000', 'omer':'1982197696887/500000000000000', 'peck':'220244188543/25000000000000', 'pint':'473176473/1000000000000', 'pony':'1419529419/64000000000000', 'puncheon':'9936705933/31250000000', 'quart':'473176473/500000000000', 'register_ton':'55306341/19531250', 'seam':'220244188543/781250000000', 'shot':'473176473/16000000000000', 'stere':'1', 'tablespoon':'473176473/32000000000000', 'teaspoon':'157725491/32000000000000', 'tun':'29810117799/31250000000', 'uk_gallon':'454609/100000000', 'uk_pint':'454609/800000000', 'wine_bottle':'3/4000'} } unit_to_type = {} value_to_unit = {} def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if isinstance(unitdict[w][j], tuple): unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys())) ############################################################################### # Documentation for individual units. # Appears in unit's docstring. ############################################################################### unit_docs = { 'acceleration_docs': {'gal':'Abbreviation for galileo.\nDefined to be 1/100 meter/second^2.', 'galileo':'Defined to be 1/100 meter/second^2.', 'gravity':'Also called standard gravity.\nPhysical constant defined to be 9.80665 meter/second^2.'}, 'amount_of_substance_docs': {'elementary_entity':'Defined to be one elementary unit of choice, usually atoms or other elementary particles.\nApproximately equal to 1.6605e-24 moles.', 'mole':'SI base unit of quantity.\nDefined to be the amount of substance that has an equal number of elementary entities as there are atoms in 12 grams of carbon-12.\nEquivalent to Avogadros constant elementary entities or approximately equal to 6.022*10^23 elementary entities.'}, 'angles_docs': {'arc_minute':'Defined to be 1/60 of a degree or pi/10800 radians.', 'arc_second':'Defined to be 1/3600 of a degree or pi/648000 radians.', 'degree':'Defined to be pi/180 radians.', 'grade':'Defined to be pi/200 radians.', 'quadrant':'Equivalent to a right angle.\nDefined to be pi/2 radians.', 'radian':'SI derived unit of angle.\nDefined to be the angle subtended at the center of a circle by an arc that is equal in length to the radius of the circle.', 'right_angle':'Equivalent to a quadrant.\nDefined to be pi/2 radians.'}, 'area_docs': {'acre':'Defined to be 10 square chains or 4840 square yards.\nApproximately equal to 4046.856 square meters.', 'are':'Defined to be 100 square meters.', 'barn':'Defined to be 100 square femtometers or 10^-28 square meters.', 'hectare':'Defined to be 10000 square meters.', 'rood':'Defined to be 1/4 of an acre.\nApproximately equal to 1011.714 square meters.', 'section':'Equivalent to a square mile.\nApproximately equal to 2.59*10^6 square meters.', 'square_chain':'Defined to be 4356 square feet.\nApproximately equal to 404.9856 square meters.', 'square_meter':'SI derived unit of area.\nDefined to be meter^2.', 'township':'Defined to be 36 square miles.\nApproximately equal to 9.324*10^7 square meters.'}, 'capacitance_docs': {'abfarad':'Defined to be 10^9 farads.', 'farad':'SI derived unit of capacitance.\nDefined to be the charge in coulombs a capacitor will accept for the potential across it to change one volt.\nEquivalent to coulomb/volt.', 'statfarad':'CGS unit defined to be statcoulomb/statvolt.\nApproximately equal to 1.11265*10^-12 farads.'}, 'charge_docs': {'abcoulomb':'CGS unit defined to be 10 coulombs.', 'coulomb':'SI derived unit of charge.\nDefined to be the amount of electric charge transported by 1 ampere in 1 second.', 'elementary_charge':'Defined to be the amount of electric charge carried by a single proton or negative charge carried by a single electron.\nApproximately equal to 1.602176462*10^-19 coulombs.', 'faraday':'Defined to be the magnitude of electric charge in one mole of electrons.\nApproximately equal to 96485.3399 coulombs.', 'franklin':'CGS unit defined to be the amount of electric charge necessary such that if two stationary objects placed one centimeter apart had one franklin of charge each they would repel each other with a force of one dyne.\nApproximately equal to 3.3356*10^-10 coulombs.', 'statcoulomb':'Equivalent to franklin.\nApproximately equal to 3.3356*10^-10 coulombs.'}, 'conductance_docs': {'abmho':'Defined to be 10^9 siemens.', 'mho':'Equivalent to siemens.', 'siemens':'SI derived unit of conductance.\nDefined to be an ampere per volt or 1/ohm.'}, 'current_docs': {'abampere':'CGS unit defined to be 10 amperes.', 'amp':'Abbreviation for ampere.', 'ampere':'SI base unit of current.\nDefined to be the constant current which will produce an attractive force of 2*10^-7 newtons per meter between two straight, parallel conductors of infinite length and negligible circular cross section placed one meter apart in free space.', 'biot':'Equivalent to abampere.\nEqual to 10 amperes.', 'statampere':'CGS unit defined to be statcoulomb/second.\nApproximately equal to 3.335641*10^-10 amperes.'}, 'electric_potential_docs': {'abvolt':'Defined to be 10^-8 volts.', 'statvolt':'CGS unit defined to be the speed of light in a vacuum/10^6 volts or approximately 299.792 volts.', 'volt':'SI derived unit of electric potential.\nDefined to be the value of voltage across a conductor when a current of one ampere dissipates one watt of power.'}, 'energy_docs': {'british_thermal_unit':'Defined to be the amount of energy required to raise the temperature of one pound of liquid water from 60 degrees Fahrenheit to 61 degrees Fahrenheit at a constant pressure of one atmosphere.\nApproximately equal to 1055.05585 joules.', 'btu':'Abbreviation for British thermal unit.\nApproximately equal to 1055.05585 joules.', 'calorie':'Defined to be the amount of energy required to raise the temperature of one gram of liquid water one degree Celsius.\nEqual to 4.1868 joules.', 'electron_volt':'Defined to be the amount of kinetic energy gained by a single unbound electron when it accelerates through an electrostatic potential difference of 1 volt.\nApproximately equal to 1.602*10^-19 joules.', 'erg':'CGS unit for energy defined to be gram*centimeter^2/second^2.\nEqual to 10^-7 joules.', 'ev':'Abbreviation for electron volt.\nApproximately equal to 1.602*10^-19 joules.', 'joule':'SI derived unit of energy.\nDefined to be kilogram*meter^2/second^2.', 'rydberg':'Defined to be the absolute value of the binding energy of the electron in the ground state hydrogen atom.\nApproximately equal to 2.17987*10^-18 joules.', 'therm':'Defined to be 100,000 British thermal units.\nApproximately equal to 1.05505585*10^8 joules.'}, 'fiber_linear_mass_density_docs': {'denier':'Defined to be 1 gram per 9000 meters.\nEqual to 1/9000000 of a kilogram/meter.', 'tex':'Defined to be 1 gram per 1000 meters.\nEqual to 1/1000000 of a kilogram/meter.'}, 'force_docs': {'dyne':'CGS unit for force defined to be gram*centimeter/second^2.\nEqual to 10^-5 newtons.', 'gram_weight':'Defined to be the magnitude of the force exerted on one gram of mass by a 9.80665 meter/second^2 gravitational field.\nEqual to 1/1000 of a kilogram weight.\nEqual to 0.00980665 newtons.', 'kilogram_force':'Equivalent to a kilogram weight.\nEqual to 9.80665 newtons.', 'kilogram_weight':'Defined to be the magnitude of the force exerted on one kilogram of mass by a 9.80665 meter/second^2 gravitational field.\nEqual to 9.80665 newtons.', 'newton':'SI derived unit of force.\nDefined to be kilogram*meter/second^2.', 'pound_force':'Equivalent to a pound weight.\nApproximately equal to 4.44822 newtons.', 'pound_weight':'Defined to be the magnitude of the force exerted on one pound of mass by a 9.80665 meter/second^2 gravitational field.\nApproximately equal to 4.44822 newtons.', 'poundal':'Defined to be pound*foot/second^2.\nApproximately equal to 0.13825 newtons.', 'ton_force':'Defined to be 2000 pounds of force.\nApproximately equal to 8896.4432 newtons.'}, 'frequency_docs': {'hertz':'SI derived unit of frequency.\nDefined to be one complete cycle per second.'}, 'illuminance_docs': {'foot_candle':'Defined to be lumen/foot^2.\nApproximately equal to 10.764 lux.', 'lux':'SI derived unit of illuminance.\nDefined to be lumen/meter^2.', 'phot':'CGS unit defined to be 10000 lux.'}, 'inductance_docs': {'abhenry':'Defined to be 10^-9 henries.', 'henry':'SI derived unit of inductance./nDefined to be a volt per ampere per second.', 'stathenry':'CGS unit defined to be one statvolt*second/statampere.\nApproximately equal to 8.98758*10^11 henries.'}, 'information_docs': {'bit':'Base unit of information.\nDefined to be the maximum amount of information that can be stored by a device of other physical system that can normally exist in only two distinct states.', 'byte':'Defined to be 8 bits.', 'nibble':'Defined to be 4 bits.'}, 'information_rate_docs': {'baud':'Defined to be 1 bit/second.'}, 'inverse_length_docs': {'diopter':'Defined to be 1/meter.', 'kayser':'Defined to be 100/meter.'}, 'length_docs': {'angstrom':'Defined to be 10^-10 meters.', 'astronomical_unit':'Originally defined as the length of the semi-major axis of the elliptical orbit of the Earth around the Sun.\nRedefined for accuracy to be the radius of an unperturbed circular Newtonian orbit about the Sun of a particle having infinitesimal mass, moving with a mean motion of 0.01720209895 radians per day.\nApproximately equal to 1.496*10^11 meters.', 'bolt':'Defined to be 40 yards.\nEqual to 36.576 meters.', 'cable_international':'Nautical unit defined to be 1/10 of a nautical mile.\nEqual to 185.2 meters.', 'cable_us':'Nautical unit defined to be equal to 720 feet or 120 fathoms.\nEqual to 219.456 meters.', 'caliber':'Equal to 1/100 of an inch.\nEqual to 0.000254 meters.', 'centimeter':'Equal to 1/100 of a meter.', 'chain':'Surveying unit defined to be 66 feet.\nApproximately equal to 20.12 meters.', 'cicero':'Printing unit defined to be 12 didot points.\nApproximately equal to 0.004512 meters.', 'cubit':'Ancient unit of length defined to be 18 inches.\nEqual to 0.4572 meters.', 'didot':'Printing unit equal to 1/12 of a cicero.\nApproximately equal to 0.00037597 meters.', 'dtp_point':'The desktop publishing point is defined to be 1/72 of an inch.\nApproximately equal to 0.0003528 meters.', 'ell':'Ancient unit of length defined to be 45 inches.\nEqual to 1.143 meters.', 'fathom':'Nautical unit defined to be 6 feet.\nEqual to 1.8288 meters.', 'feet':'Equal to 12 inches.\nDefined to be 0.3048 meters.', 'fermi':'Equivalent to a femtometer.\nEqual to 10^-15 meters.', 'foot':'Equal to 12 inches.\nDefined to be 0.3048 meters.', 'furlong':'Defined to be 660 feet, or 1/8 of a mile.\nEqual to 201.168 meters.', 'hand':'Defined to be 4 inches.\nEqual to 0.1016 meters.', 'inch':'Equal to 1/12 of a foot.\nEqual to 0.0254 meters.', 'kilometer':'Equal to 1000 meters.\nEqual to 3280.8399 feet.', 'league':'Defined to be 3 miles.\nConventionally equal to the distance a person or horse can walk in one hour.\nEqual to 4828.032 meters.', 'light_year':'Defined to be the distance light travels in vacuum in 365.25 days.\nApproximately equal to 9.4607*10^15 meters.', 'link':'Surveying unit defined to be 1/100 of a chain.\nEqual to 0.201168 meters.', 'meter':'SI base unit of length.\nDefined to be the distance light travels in vacuum in 1/299792458 of a second.', 'micron':'Defined to be 10^-6 meters.', 'mil':'Defined to be 1/1000 of an inch.\nEqual to 0.0000254 meters.', 'millimeter':'Defined to be 1/1000 of a meter.\nEqual to 0.001 meters.', 'mile':'Defined to be 5280 feet.\nEqual to 1609.344 meters.', 'nautical_mile':'Nautical unit defined to be 1852 meters.', 'parsec':'Defined to be the length of the adjacent side of a right triangle whose angle is 1 arcsecond and opposite side equal to 1 astronomical unit, or 1 AU/arctan(1 arcsecond).\nApproximately equal to 30.857*10^15 meters.', 'perch':'Equivalent to rod.\nDefined to be 16.5 feet.\nEqual to 5.0292 meters.', 'pica':'Printing unit defined to be 12 dtp points.\nEqual to 1/72 of a foot.\nApproximately equal to 0.004233 meters.', 'pole':'Equivalent to rod.\nDefined to be 16.5 feet.\nEqual to 5.0292 meters.', 'rod':'Defined to be 16.5 feet.\nEqual to 5.0292 meters.', 'rope':'Defined to be 20 feet.\nEqual to 6.096 meters.', 'skein':'Defined to be 360 feet.\nEqual to 109.728 meters.', 'stadion':'Ancient unit of length defined to be 622 feet.\nEqual to 189.5856 meters.', 'stadium':'Defined to be 202 yards or 606 feet.\nEqual to 184.7088 meters.', 'statute_mile':'Equivalent to mile.\nDefined to be 5280 feet.\nEqual to 1609.344 meters.', 'survey_foot':'Defined to be 1200/3937 or approximately 0.3048006 meters.', 'survey_mile':'Defined to be 5280 survey feet.\nApproximately equal to 1609.347 meters.', 'x_unit':'Unit of length used to quote wavelengths of X-rays and gamma rays.\nApproximately equal to 1.0021*10^-13 meters.', 'yard':'Defined to be 3 feet.\nEqual to 0.9144 meters.'}, 'luminance_docs': {'apostilb':'Defined to be 10^-4 lamberts.\nEqual to 1/pi*candela/meter^2.', 'lambert':'Defined to be 10^4/pi candela/meter^2.', 'nit':'Equivalent to candela/meter^2.', 'stilb':'CGS unit equal to 10000 candela/meter^2.'}, 'luminous_energy_docs': {'lumerg':'Equivalent to lumen*second', 'talbot':'Equivalent to lumen*second.'}, 'luminous_flux_docs': {'lumen':'SI derived unit of luminous flux.\nDefined to be candela*steradian.'}, 'luminous_intensity_docs': {'candela':'SI base unit of luminous intensity.\nDefined to be the luminous intensity, in a given direction, of a source that emits monochromatic radiation of frequency 540*10^12 hertz and that has a radiant intensity in that direction of 1/683 watt per steradian.', 'candle':'Equivalent to candela.', 'hefnerkerze':'Old German unit defined to be a 8 millimeter wick burning amyl acetate with a flame height of 40 millimeters.\nApproximately equal to 0.9034 candelas.'}, 'magnetic_field_docs': {'gauss':'CGS unit defined to be a maxwell/centimeter^2.\nEqual to 1/10000 of a tesla.', 'tesla':'SI derived unit of magnetic field.\nDefined to be the magnitude of a magnetic field such that a particle with a charge of 1 coulomb passing through that field at 1 meter/second will experience a force of 1 newton.'}, 'magnetic_flux_docs': {'maxwell':'CGS unit defined to be a gauss*centimeter^2 or 10^-8 webers.', 'weber':'SI derived unit of magnetic flux.\nDefined to be a change in magnetic flux of 1 weber per second will induce an electromotive force of 1 volt.'}, 'magnetic_intensity_docs': {'oersted':'CGS unit defined to be 1000/(4*pi) amperes per meter of flux path.'}, 'magnetic_moment_docs': {'bohr_magneton':'Physical constant defined to be the magnetic moment of an electron, or elementary_charge*h_bar/2*electron_rest_mass.\nApproximately equal to 9.274*10^-24 joules/tesla.', 'nuclear_magneton':'Physical constant defined to be the magnetic moment of a proton, or elementary_charge*h_bar/2*proton_rest_mass.\nApproximately equal to 5.05078324*10^-27 joules/tesla.'}, 'magnetomotive_force_docs': {'ampere_turn':'SI derived unit of magnetomotive force.\nDefined to be a direct current of 1 ampere flowing through a single turn loop in a vacuum.', 'gilbert':'CGS unit defined to be 10/(4*pi) ampere turns.'}, 'mass_docs': {'amu':'Abbreviation for atomic mass unit.\nApproximately equal to 1.660538782*10^-27 kilograms.', 'assay_ton':'Defined to be milligram*short_ton/ounce_troy.\nEqual to 7/240 of a kilogram.', 'atomic_mass_unit':'Defined to be one twelfth of the mass of an isolated atom of carbon-12 at rest and in its ground state.\nApproximately equal to 1.660538782*10^-27 kilograms.', 'avoirdupois_ounce':'Equivalent to ounce.\nEqual to 1/16 of an avoirdupois pound.\nApproximately equal to 0.02835 kilograms.', 'avoirdupois_pound':'Equivalent to pound.\nEqual to 16 avoirdupois ounces.\nApproximately equal to 0.45359 kilograms.', 'bale':'Equal to 500 pounds.\nApproximately equal to 226.796 kilograms.', 'carat':'Defined to be equal to 200 milligrams.\nCommonly denoted ct.', 'cental':'Equal to 100 pounds.\nApproximately equal to 45.36 kilograms.', 'dalton':'Equivalent to atomic_mass_unit.\nApproximately equal to 1.660538782*10^-27 kilograms.', 'drachma':'Ancient Greek unit of mass.\nEqual to 6 obols.\nApproximately equal to 0.00429234 kilograms.', 'geepound':'Equivalent to slug.\nApproximately equal to 14.5939 kilograms.', 'grain':'Historically based on the average mass of a single seed of a typical cereal.\nDefined in 1958 to be 64.79891 milligrams.', 'gram':'Equal to 0.0001 kilograms.', 'gross_hundredweight':'Equivalent to hundredweight.\nEqual to 112 pounds.\nApproximately equal to 50.802 kilograms.', 'hundredweight':'Defined to be 112 pounds.\nApproximately equal to 50.802 kilograms.', 'kilogram':'SI base unit of mass.\nDefined to be equal to the mass of the International Prototype Kilogram.\nAlmost exactly equal to the amount of mass in one liter of water.', 'libra':'Ancient Roman unit of mass.\nApproximately equal to 0.325971 kilogram.', 'long_ton':'Defined to be 2240 pounds.\nApproximately equal to 1016.05 kilograms.', 'metric_ton':'Defined to be 1000 kilograms.', 'mina':'Ancient Greek unit of mass.\nEqual to 100 drachma.\nApproximately equal to 0.429234 kilograms.', 'net_hundredweight':'Equivalent to cental.\nEqual to 100 pounds.\nApproximately equal to 45.36 kilograms.', 'obol':'Ancient Greek unit of mass.\nEqual to 1/6 of drachma.\nApproximately equal to 0.00071538 kilograms.', 'ounce':'Equal to 1/16 of pound.\nCommonly abbreviated oz.\nApproximately equal to 0.02835 kilograms.', 'ounce_troy':'Equal to 1/12 of pound_troy.\nApproximately equal to 0.031103 kilograms.', 'pennyweight':'Equal to 1/20 of ounce_troy.\nCommonly abbreviated dwt.\nApproximately equal to 0.001555 kilograms.', 'pondus':'Ancient Roman unit of mass.\nApproximately equal to 0.325969 kilograms.', 'pound':'Equal to 16 ounces.\nDefined to be exactly 0.45359237 kilograms.', 'pound_troy':'Equal to 12 ounce_troy.\nApproximately equal to 0.37324 kilograms.', 'quintal':'Equal to 100 kilograms.', 'shekel':'Ancient Hebrew unit of mass.\nApproximately equal to 0.0141 kilograms.', 'short_hundredweight':'Equivalent to cental.\nEqual to 100 pounds.\nApproximately equal to 45.36 kilograms.', 'short_ton':'Equivalent to ton.\nEqual to 2000 pounds.\nApproximately equal to 907.18 kilograms.', 'slug':'Defined to be a mass that is accelerated 1 ft/s^2 when 1 pound_force is exerted on it.\nApproximately equal to 14.5939 kilograms.', 'solar_mass':'Defined to be the mass of the Sun.\nAbout 332,950 times the mass of the Earth or 1,048 times the mass of Jupiter.\nApproximately equal to 1.98892*10^30 kilograms.', 'stone':'Defined to be 14 pounds.\nApproximately equal to 6.35 kilograms.', 'talent':'Ancient Greek unit of mass.\nEqual to 6000 drachmae.\nApproximately equal to 25.754 kilograms.', 'ton':'Equal to 2000 pounds.\nApproximately equal to 907.18 kilograms.', 'tonne':'Equivalent to metric_ton.\nDefined to be 1000 kilograms.', 'wey':'Defined to be 252 pounds.\nApproximately equal to 114.305 kilograms.'}, 'power_docs': {'cheval_vapeur':'Defined to be 75 kilogram force*meter/second.\nAlso known as metric horsepower.\nEqual to 735.49875 watts.', 'horsepower':'Defined to be 550 feet*pound force/second.\nApproximately equal to 745.7 watts.', 'watt':'SI derived unit of power.\nDefined to be joule/second or, in base units, kilogram*meter^2/second^3.'}, 'pressure_docs': {'atmosphere':'Defined to be 101325 pascals.', 'bar':'Defined to be 100000 pascals.', 'barye':'CGS unit defined to be dyne/centimeter^2.\nEqual to 1/10 of a pascal.', 'inch_mercury':'Defined to be 13595.1 kilogram/meter^3*inch*gravity.\nApproximately equal to 3386.389 pascals.', 'millimeter_mercury':'Defined to be 13595.1 kilogram/meter^3*millimeter*gravity.\nApproximately equal to 133.3224 pascals.', 'mmhg':'Abbreviation for millimeter mercury.\nApproximately equal to 133.3224 pascals.', 'pa':'Abbreviation for pascal.', 'pascal':'SI derived unit of pressure.\nDefined to be newton/meter^2 or, in base units, kilogram/(meter*second^2).', 'pounds_per_square_inch':'Defined to be pound force/inch^2.\nApproximately equal to 6894.76 pascals.', 'psi':'Abbreviation for pounds per square inch.\nApproximately equal to 6894.76 pascals.', 'torr':'Defined to be 1/760 of an atmosphere.\nApproximately equal to 133.322 pascals.'}, 'radiation_absorbed_docs': {'gray':'SI derived unit of absorbed radiation.\nDefined to be the absorption of one joule of ionizing radiation by one kilogram of matter.', 'rad':'Defined to be 1/100 of a gray.'}, 'radiation_docs': {'becquerel':'SI derived unit of radiation.\nDefined to be the activity of a quantity of radioactive material in which one nucleus decays per second.', 'curie':'Defined to be 37*10^9 becquerels.', 'rutherford':'Defined to be 10^6 becquerels.'}, 'radiation_ionizing_docs': {'roentgen':'Defined to be .000258 coulombs/kilogram.', 'rontgen':'Equivalent to roentgen.\nDefined to be .000258 coulombs/kilogram.'}, 'resistance_docs': {'abohm':'Defined to be 10^-9 ohms.', 'ohm':'SI derived unit of resistance.\nDefined to be a volt per ampere.', 'statohm':'CGS unit defined to be statvolt/statampere.\nApproximately equal to 8.98758*10^11 ohms.'}, 'solid_angle_docs': {'steradian':'SI derived unit of solid angle.\nDefined to be the solid angle subtended at the center of a sphere of radius r by a portion of the surface of the sphere having an area of r^2.'}, 'temperature_docs': {'celsius':'Defined to be -273.15 at absolute zero and 0.01 at the triple point of Vienna Standard Mean Ocean Water.\nCelsius is related to kelvin by the equation K = 273.15 + degrees Celsius.\nA change of 1 degree Celsius is equivalent to a change of 1 degree kelvin.', 'centigrade':'Equivalent to celsius.', 'fahrenheit':'Defined to be 32 degrees at the freezing point of water and 212 degrees at the boiling point of water, both at standard pressure (1 atmosphere).\nFahrenheit is related to kelvin by the equation K = 5/9*(degrees Fahrenheit + 459.67).\nA change of 1 degree fahrenheit is equal to a change of 5/9 kelvin.', 'kelvin':'SI base unit of temperature.\nDefined to be exactly 0 at absolute zero and 273.16 at the triple point of Vienna Standard Mean Ocean Water.', 'rankine':'Defined to be 0 at absolute zero and to have the same degree increment as Fahrenheit.\nRankine is related to kelvin by the equation K = 5/9*R.'}, 'time_docs': {'century':'Defined to be 100 years.\nEqual to 3153600000 seconds.', 'day':'Defined to be 24 hours.\nEqual to 86400 seconds.', 'decade':'Defined to be 10 years.\nEqual to 315360000 seconds.', 'fortnight':'Defined to be 2 weeks or 14 days.\nEqual to 1209600 seconds.', 'hour':'Defined to be 60 minutes.\nEqual to 3600 seconds.', 'millenium':'Defined to be 1000 years.\nEqual to 31536000000 seconds.', 'minute':'Defined to be 60 seconds.', 'month':'Defined to be 30 days.\nEqual to 2628000 seconds.', 'second':'SI base unit of time.\nDefined to be the duration of 9,192,631,770 periods of the radiation corresponding to the transition between the two hyperfine levels of the ground state of the caesium 133 atom.', 'sidereal_day':'Defined to be the time it takes for the Earth to make one complete rotation relative to the stars.\nApproximately equal to 86164.09 seconds.', 'sidereal_second':'Defined to be 1/86400 of a sidereal day.\nApproximately equal to 0.997269566329086 seconds.', 'sidereal_year':'Defined to be the time taken by the Earth to orbit the Sun once with respect to the fixed stars.\nApproximately equal to 31558149.7632 seconds.', 'tropical_year':'Defined to be the length of time that the Sun takes to return to the same position in the cycle of seasons, as seen from the Earth.\nApproximately equal to 31556925.1779840 seconds.', 'week':'Defined to be 7 days.\nEqual to 604800 seconds.', 'year':'Defined to be 365 days.\nEqual to 31536000 seconds.'}, 'unit_multipliers_docs': {'bakers_dozen':'Defined to be 13 items.', 'dozen':'Defined to be 12 items.', 'gross':'Defined to be 144 items.', 'percent':'Defined to be 1/100 of a quantity.'}, 'velocity_docs': {'knot':'Nautical unit of velocity defined to be a nautical mile per hour.\nApproximately equal to 0.5144 meter/second.'}, 'viscosity_absolute_docs': {'poise':'CGS unit defined to be 1/10 of pascal*second.', 'reyn':'Defined to be a pound_force*second/inch^2.\nApproximately equal to 6894.76 pascal*second.'}, 'viscosity_kinematic_docs': {'stokes':'CGS unit defined to be 1/10000 of meter^2/second.'}, 'viscosity_other_docs': {'rhes':'Defined to be 1/poise or 10/(pascal*second).'}, 'volume_docs': {'bag':'Defined to be 3 bushels.\nApproximately equal to 0.10572 cubic meters.', 'barrel':'Defined to be 42 gallons.\nApproximately equal to 0.15899 cubic meters.', 'board_foot':'Defined to be 144 cubic inches.\nApproximately equal to 0.0023597 cubic meters.', 'bucket':'Defined to be 4 gallons.\nApproximately equal to 0.0151416 cubic meters.', 'bushel':'Defined to be 2150.42 cubic inches.\nEquivalent to 4 pecks.\nApproximately equal to 0.035239 cubic meters.', 'butt':'Old English unit of wine casks defined to be 2 hogsheads or 126 gallons.\nApproximately equal to 0.476962 cubic meters.', 'cord':'Defined to be 8 feet x 8 feet x 4 feet.\nApproximately equal to 3.624556 cubic meters.', 'cubic_meter':'SI derived unit of volume.\nDefined to be meter^3.', 'cup':'Defined to be 8 fluid ounces.\nApproximately equal to 0.000236588 cubic meters.', 'ephah':'Ancient Hebrew unit of volume equal to 10 omers.\nApproximately equal to 0.03964 cubic meters.', 'fifth':'Defined to be 1/5 of a gallon.\nApproximately equal to 0.00075708 cubic meters.', 'firkin':'Defined to be 9 imperial gallons.\nApproximately equal to 0.04091 cubic meters.', 'fluid_dram':'Defined to be 1/8 of a fluid ounce.\nApproximately equal to 3.69669*10^-6 cubic meters.', 'fluid_ounce':'Defined to be 1/128 of a gallon.\nApproximately equal to 0.000029574 cubic meters.', 'gallon':'Defined to be 231 cubic inches.\nApproximately equal to 0.0037854 cubic meters.', 'gill':'Defined to be 4 fluid ounces.\nApproximately equal to 0.00011829 cubic meters.', 'hogshead':'Old English unit of wine casks defined to be 63 gallons.\nApproximately equal to 0.23848 cubic meters.', 'imperial_gallon':'Defined to be 4.54609 liters.\nEqual to 0.00454609 cubic meters.', 'imperial_pint':'Defined to be 1/8 of an imperial gallon.\nApproximately equal to 0.00056826 cubic meters.', 'jeroboam':'Defined to be 4/5 of a gallon.\nApproximately equal to 0.0030283 cubic meters.', 'jigger':'Defined to be 1 1/2 fluid ounces.\nApproximately equal to 0.00004436 cubic meters.', 'liter':'Defined to be 1 decimeter^3.\nEqual to 1/1000 of a cubic meter.', 'magnum':'Defined to be 1/2 a gallon.\nApproximately equal to 0.0018927 cubic meters.', 'minim':'Defined to be 1/480 of a fluid ounce.\nApproximately equal to 6.16115*10^-8 cubic meters.', 'noggin':'Equivalent to gill.\nDefined to be 4 fluid ounces.\nApproximately equal to 0.00011829 cubic meters.', 'omer':'Ancient Hebrew unit of volume equal to 9/20 of a peck.\nApproximately equal to 0.0039644 cubic meters.', 'peck':'Defined to be 1/4 of a bushel.\nApproximately equal to 0.0088098 cubic meters.', 'pint':'Defined to be 1/8 of a gallon.\nApproximately equal to 0.00047318 cubic meters.', 'pony':'Defined to be 3/4 of a fluid ounce.\nApproximately equal to 0.00002218 cubic meters.', 'puncheon':'Old English unit of wine casks defined to be 84 gallons.\nApproximately equal to 0.31797 cubic meters.', 'quart':'Defined to be 1/4 of a gallon.\nApproximately equal to 0.00094635 cubic meters.', 'register_ton':'Defined to be 100 cubic feet.\nApproximately equal to 2.83168 cubic meters.', 'seam':'Defined to be 8 bushels.\nApproximately equal to 0.281913 cubic meters.', 'shot':'Defined to be 1 fluid ounce.\nApproximately equal to 0.000029574 cubic meters.', 'stere':'Equivalent to cubic meter.', 'tablespoon':'Defined to be 1/2 of a fluid ounce.\nApproximately equal to 0.000014787 cubic meters.', 'teaspoon':'Defined to be 1/6 of a fluid ounce.\nEqual to 1/3 of a tablespoon.\nApproximately equal to 4.9289*10^-6 cubic meters.', 'tun':'Old English unit of wine casks defined to be 252 gallons.\nApproximately equal to 0.95392 cubic meters.', 'uk_gallon':'Equivalent to an imperial gallon.\nEqual to 0.00454609 cubic meters.', 'uk_pint':'Equivalent to and imperial pint.\nApproximately equal to 0.00056826 cubic meters.', 'wine_bottle':'Defined to be 750 milliliters.\nEqual to 0.00075 cubic meters.'} } ############################################################################### # Dictionary for converting from derived units to base SI units. ############################################################################### unit_derivations = {'acceleration':'length/time^2', 'area':'length^2', 'capacitance':'time^4*current^2/(length^2*mass)', 'charge':'current*time', 'conductance':'current^2*time^3/(mass*length^2)', 'electric_potential':'mass*length^2/(current*time^3)', 'energy':'mass*length^2/time^2', 'fiber_linear_mass_density':'mass/length', 'force':'mass*length/time^2', 'frequency':'1/time', 'illuminance':'luminous_intensity*solid_angle/length^2', 'inductance':'length^2*mass/(time^2*current^2)', 'information_rate':'information/time', 'inverse_length':'1/length', 'luminance':'luminous_intensity/length^2', 'luminous_energy':'luminous_intensity*solid_angle*time', 'luminous_flux':'luminous_intensity*solid_angle', 'magnetic_field':'mass/(current*time^2)', 'magnetic_flux':'mass*length^2/(current*time^2)', 'magnetic_intensity':'current/length', 'magnetic_moment':'current*length^2', 'power':'mass*length^2/time^3', 'pressure':'mass/(length*time^2)', 'radiation':'1/time', 'radiation_absorbed':'length^2/time^2', 'radiation_ionizing':'current*time/mass', 'resistance':'mass*length^2/(current^2*time^3)', 'velocity':'length/time', 'viscosity_absolute':'mass/(length*time)', 'viscosity_kinematic':'length^2/time', 'viscosity_other':'length*time/mass', 'volume':'length^3' } def vars_in_str(s): """ Given a string like 'mass/(length*time)', return the list ['mass', 'length', 'time']. INPUT: - `s` -- string OUTPUT: - list of strings (unit names) EXAMPLES:: sage: sage.symbolic.units.vars_in_str('mass/(length*time)') ['mass', 'length', 'time'] """ return re.findall('[a-z|_]+', s) def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z class UnitExpression(Expression): """ A symbolic unit. EXAMPLES:: sage: acre = units.area.acre sage: type(acre) <class 'sage.symbolic.units.UnitExpression'> TESTS:: sage: bool(loads(dumps(acre)) == acre) True sage: type(loads(dumps(acre))) <class 'sage.symbolic.units.UnitExpression'> """ def _sage_doc_(self): """ Return docstring for this unit. EXAMPLES:: sage: print units.area.acre._sage_doc_() Defined to be 10 square chains or 4840 square yards. Approximately equal to 4046.856 square meters. """ return unitdocs(self) def str_to_unit(name): """ Create the symbolic unit with given name. A symbolic unit is a class that derives from symbolic expression, and has a specialized docstring. INPUT: - ``name`` -- string OUTPUT: - UnitExpression EXAMPLES:: sage: sage.symbolic.units.str_to_unit('acre') acre sage: type(sage.symbolic.units.str_to_unit('acre')) <class 'sage.symbolic.units.UnitExpression'> """ return UnitExpression(SR, SR.var(name)) class Units: """ A collection of units of a some type. EXAMPLES:: sage: units.power Collection of units of power: cheval_vapeur horsepower watt """ def __init__(self, data, name=''): """ EXAMPLES:: sage: sage.symbolic.units.Units(sage.symbolic.units.unitdict, 'all units') Collection of units of all units: acceleration ... volume """ self.__name = name self.__data = data self.__units = {} def __getstate__(self): """ Used for pickling. We throw away all cached information. EXAMPLES:: sage: type(units.__getstate__()[0]) <type 'str'> sage: type(units.__getstate__()[1]) <type 'dict'> sage: loads(dumps(units)) == units True sage: loads(dumps(units.area)) == units.area True sage: bool(loads(dumps(units.area.acre)) == units.area.acre) True """ return (self.__name, self.__data) def __setstate__(self, state): """ Used for unpickling. See __getstate__. EXAMPLES:: sage: state = units.__getstate__() sage: units.__setstate__(state) """ self.__name = state[0] self.__data = state[1] self.__units = {} def __cmp__(self, other): """ Compare two collections of units, or a collection of units with some other object. EXAMPLES:: sage: units.length == 10 False sage: units.length == units.length True sage: units.length == units.mass False """ if not isinstance(other, Units): return cmp(type(self), type(other)) return cmp((self.__name, self.__data), (other.__name, other.__data)) def trait_names(self): """ Return completions of this unit objects. This is used by the Sage command line and notebook to create the list of method names. EXAMPLES:: sage: units.area.trait_names() ['acre', 'are', 'barn', 'hectare', 'rood', 'section', 'square_chain', 'square_meter', 'township'] """ return sorted([x for x in self.__data.keys() if '/' not in x]) def __getattr__(self, name): """ Return the unit with the given name. EXAMPLES:: sage: units.area Collection of units of area: acre are barn hectare rood section square_chain square_meter township sage: units.area.barn barn Units are cached:: sage: units.area.acre is units.area.acre True """ if name in self.__units: return self.__units[name] if len(unit_to_type) == 0: evalunitdict() try: v = self.__data[name] except KeyError: raise AttributeError if isinstance(v, dict): U = Units(self.__data[name], name) else: U = str_to_unit(name) self.__units[name] = U return U def __repr__(self): """ Return string representation of this collection of units. EXAMPLES:: sage: units.__repr__() 'Collection of units: acceleration ... volume' sage: units.area.__repr__() 'Collection of units of area: acre are barn hectare rood section square_chain square_meter township' """ name = ' of ' + self.__name if self.__name else '' return "Collection of units{0}: {1}".format(name, ' '.join(sorted([str(x) for x in self.__data]))) units = Units(unitdict, '') def unitdocs(unit): r""" Returns docstring for the given unit. INPUT: - ``unit`` OUTPUT: - ``string`` EXAMPLES:: sage: sage.symbolic.units.unitdocs('meter') 'SI base unit of length.\nDefined to be the distance light travels in vacuum in 1/299792458 of a second.' sage: sage.symbolic.units.unitdocs('amu') 'Abbreviation for atomic mass unit.\nApproximately equal to 1.660538782*10^-27 kilograms.' Units not in the list unit_docs will raise a ValueError:: sage: sage.symbolic.units.unitdocs('earth') Traceback (most recent call last): ... ValueError: No documentation exists for the unit earth. """ if is_unit(unit): return unit_docs[unit_to_type[str(unit)]+"_docs"][str(unit)] else: raise ValueError("No documentation exists for the unit %s."%unit) def is_unit(s): """ Returns a boolean when asked whether the input is in the list of units. INPUT: - `s` -- an object OUTPUT: - ``bool`` EXAMPLES:: sage: sage.symbolic.units.is_unit(1) False sage: sage.symbolic.units.is_unit(units.length.meter) True The square of a unit is not a unit:: sage: sage.symbolic.units.is_unit(units.length.meter^2) False You can also directly create units using var, though they won't have a nice docstring describing the unit:: sage: sage.symbolic.units.is_unit(var('meter')) True """ return str(s) in unit_to_type def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*(acre*inch) sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) (ampere*second) sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch You can also convert quantities of units:: sage: sage.symbolic.units.convert(cos(50) * units.angles.radian, units.angles.degree) degree*(180*cos(50)/pi) sage: sage.symbolic.units.convert(cos(30) * units.angles.radian, units.angles.degree).polynomial(RR) 8.83795706233228*degree sage: sage.symbolic.units.convert(50 * units.length.light_year / units.time.year, units.length.foot / units.time.second) 6249954068750/127*(foot/second) Quantities may contain variables (not for temperature conversion, though):: sage: sage.symbolic.units.convert(50 * x * units.area.square_meter, units.area.acre) acre*(1953125/158080329*x) """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() for variable in coeff.variables(): if is_unit(str(variable)): raise ValueError("Incompatible units") return coeff.mul(target, hold=True) def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if str(unit) not in unit_to_type: return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if str(v) in unit_derivations: base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base def convert_temperature(expr, target): """ Function for converting between temperatures. INPUT: - `expr` -- a unit of temperature - `target` -- a units of temperature OUTPUT: - `symbolic expression` EXAMPLES:: sage: t = 32*units.temperature.fahrenheit sage: t.convert(units.temperature.celsius) 0 sage: t.convert(units.temperature.kelvin) 273.150000000000*kelvin If target is None then it defaults to kelvin:: sage: t.convert() 273.150000000000*kelvin Raises ValueError when either input is not a unit of temperature:: sage: t.convert(units.length.foot) Traceback (most recent call last): ... ValueError: Cannot convert sage: wrong = units.length.meter*units.temperature.fahrenheit sage: wrong.convert() Traceback (most recent call last): ... ValueError: Cannot convert We directly call the convert_temperature function:: sage: sage.symbolic.units.convert_temperature(37*units.temperature.celsius, units.temperature.fahrenheit) 493/5*fahrenheit sage: 493/5.0 98.6000000000000 """ if len(expr.variables()) != 1: raise ValueError("Cannot convert") elif target == None or unit_to_type[str(target)] == 'temperature': from sage.misc.all import sage_eval expr_temp = expr.variables()[0] coeff = expr/expr_temp if target != None: target_temp = target.variables()[0] a = sage_eval(unitdict['temperature'][str(expr_temp)], locals = {'x':coeff}) if target == None or target_temp == units.temperature.kelvin: return a[0]*units.temperature.kelvin elif target_temp == units.temperature.celsius or target_temp == units.temperature.centigrade: return a[1]*target_temp elif target_temp == units.temperature.fahrenheit: return a[2]*units.temperature.fahrenheit elif target_temp == units.temperature.rankine: return a[3]*target_temp else: raise ValueError("Cannot convert")
43.149233
382
0.63658
b78c1e5aa1c6406208f62c223bc7eb41761a4311
1,127
py
Python
Examples/Basic/chatting.py
NekoGamiYuki/SpicyTwitch
b74b64026ba64c2303d7cc32da094f5c80cab325
[ "MIT" ]
null
null
null
Examples/Basic/chatting.py
NekoGamiYuki/SpicyTwitch
b74b64026ba64c2303d7cc32da094f5c80cab325
[ "MIT" ]
null
null
null
Examples/Basic/chatting.py
NekoGamiYuki/SpicyTwitch
b74b64026ba64c2303d7cc32da094f5c80cab325
[ "MIT" ]
null
null
null
""" This example file shows how to send a message to a twitch channel. It waits 30 seconds before sending the same message again, so as to not spam the channel. WARNING: Please do not remove the time.sleep(), or lower it, as you may get banned from twitch for a certain amount of time. Do so only if you know what you are doing. Replace the necessary parameters (such as "username") with your own. """ import sys import time from spicytwitch import irc # Connect to twitch, make sure we've logged in. if not irc.connect("username", "oauth:..."): print("Unable to login!") sys.exit(1) # Close the program if we can't login # Go ahead and set it to your own channel. my_channel = "my_channel" irc.join_channel(my_channel) while True: if irc.get_info(): # Wait 30 seconds before sending another message as we don't want to # spam the channel... time.sleep(30) # chat() requires two parameters; First is the message you'd like to # send. Second is the channel you would like to send that message to. irc.chat("Hey! I'm chatting! Kappa Kappa MingLee", my_channel)
34.151515
80
0.704525
5a9d30f852d1adc98dcd88d5ec1624df21b1d59c
1,575
py
Python
app/models/calendar.py
Joeper214/barm
77cd8ddcf73ceacf86b13ca819d8e56471e43574
[ "MIT" ]
2
2015-03-04T07:05:57.000Z
2015-03-04T07:06:00.000Z
app/models/calendar.py
Joeper214/barm
77cd8ddcf73ceacf86b13ca819d8e56471e43574
[ "MIT" ]
null
null
null
app/models/calendar.py
Joeper214/barm
77cd8ddcf73ceacf86b13ca819d8e56471e43574
[ "MIT" ]
null
null
null
from ferris import BasicModel, ndb from datetime import datetime, timedelta from google.appengine.ext import deferred class Calendar(BasicModel): event_id = ndb.KeyProperty(required=True) calendar_id = ndb.StringProperty(required=True) alloc_date = ndb.DateProperty(required=True) alloc_end = ndb.DateProperty(required=True) alloc_hours = ndb.FloatProperty(required=True) project_name = ndb.StringProperty(required=True) resource_name = ndb.StringProperty(required=True) email = ndb.StringProperty(required=True) color = ndb.StringProperty(required=True) # class Meta: # behaviors = (EventBehavior, ) @classmethod def list_all(cls): return cls.query().order(cls.alloc_date).fetch() @classmethod def get(cls, key): return cls(parent=key) @classmethod def create(cls, params): item = cls() item.populate(**params) item.put() return item def update(self, params): self.populate(**params) self.put() @classmethod def find_by_event_id(cls, id): return cls.query().filter(cls.allocation_id == id).order(cls.end_date).fetch() def delete(self): ndb.delete_multi(ndb.Query(ancestor=self.key).iter(keys_only=True)) @classmethod def delete_by_event_id(cls,id): allocs = cls.find_by_event_id(id) for a in allocs: deferred.defer(cls.del_calendar, a.key.urlsafe()) @classmethod def del_calendar(cls, key): key = ndb.Key(urlsafe=key) key.delete()
28.125
86
0.664127
aab0b4d85864d5dfba3206393c38dde21b19d0cc
1,608
py
Python
firewall/app/main/controllers/ipController.py
vivitek/box
82b8f9fec3b92b38b8587e18bdfeb08d50708d03
[ "CC-BY-4.0" ]
2
2020-05-28T14:39:46.000Z
2020-06-19T18:38:46.000Z
firewall/app/main/controllers/ipController.py
vivitek/deep-thought
9f0e3ec1e1c1dbc14466ec8ebd24ae83e6fcee94
[ "CC-BY-4.0" ]
35
2020-06-19T18:43:47.000Z
2021-04-02T13:23:30.000Z
firewall/app/main/controllers/ipController.py
vivitek/box
82b8f9fec3b92b38b8587e18bdfeb08d50708d03
[ "CC-BY-4.0" ]
1
2020-09-01T16:08:49.000Z
2020-09-01T16:08:49.000Z
from flask import Blueprint, request, abort from flask_api import status from app.main import redis_client from app.main.firewall_manager import FWManager from app.main.utils.custom_exception import CustomException import app.main.utils.validate_form as validateForm bp = Blueprint('ip', __name__, url_prefix='/ip') PyNFT = FWManager() IP_FORMAT = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$" @bp.route('/ban', methods=['POST']) def banIP(): try: body = request.get_json() address = body.get('address') # bandwith # setBandwith() validateForm.validateForm(address, IP_FORMAT) response = PyNFT.ban_ipv4(address) if (response['error']): raise Exception(response['error']) redis_client.zadd('ipBan', {address: 0}) return response, status.HTTP_200_OK except CustomException as e: return(e.reason, e.code) except Exception as e: return (str(e), status.HTTP_500_INTERNAL_SERVER_ERROR) @bp.route('/unban', methods=['POST']) def unbanIp(): try: body = request.get_json() address = body.get('address') validateForm.validateForm(address, IP_FORMAT) response = PyNFT.unban_ipv4(address) if (response['error']): raise Exception(response['error']) redis_client.zrem('ipBan', address) return response, status.HTTP_200_OK except CustomException as e: return(e.reason, e.code) except Exception as e: return (str(e), status.HTTP_500_INTERNAL_SERVER_ERROR)
34.956522
113
0.648632
3319ef9f8f12dbab4d86177de680b7204b490299
651
py
Python
Lib/site-packages/registration/__init__.py
pablotose/Curso-Django
812ffc0b45cf8c26b3b052ad2e5a5ce22fa7ad7f
[ "bzip2-1.0.6" ]
16
2016-09-01T20:34:48.000Z
2020-03-20T06:16:25.000Z
Lib/site-packages/registration/__init__.py
pablotose/Curso-Django
812ffc0b45cf8c26b3b052ad2e5a5ce22fa7ad7f
[ "bzip2-1.0.6" ]
1
2017-01-26T19:50:36.000Z
2017-01-26T20:01:41.000Z
Lib/site-packages/registration/__init__.py
pablotose/Curso-Django
812ffc0b45cf8c26b3b052ad2e5a5ce22fa7ad7f
[ "bzip2-1.0.6" ]
5
2016-09-28T20:24:26.000Z
2019-10-07T08:33:13.000Z
VERSION = (1, 4, 0, 'final', 0) def get_version(): "Returns a PEP 386-compliant version number from VERSION." assert len(VERSION) == 5 assert VERSION[3] in ('alpha', 'beta', 'rc', 'final') # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha, beta and rc releases parts = 2 if VERSION[2] == 0 else 3 main = '.'.join(str(x) for x in VERSION[:parts]) sub = '' if VERSION[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[VERSION[3]] + str(VERSION[4]) return str(main + sub)
28.304348
62
0.554531
10f52a70b0562e02b5160d6512b8fdef69d24e54
14,613
py
Python
Python_Tello(DJI_UAV)/tello_image_ros/2022_2_12/TelloGO_IMAG/src/tello_control/tello_control/tello_base.py
Chentao2000/practice_code
aa4fb6bbc26ac1ea0fb40e6e0889050b7e9f096c
[ "Apache-2.0" ]
4
2022-01-07T13:07:48.000Z
2022-02-08T04:46:02.000Z
Python_Tello(DJI_UAV)/tello_image_ros/2022_2_12/TelloGO_IMAG/src/tello_control/tello_control/tello_base.py
Chentao2000/practice_code
aa4fb6bbc26ac1ea0fb40e6e0889050b7e9f096c
[ "Apache-2.0" ]
null
null
null
Python_Tello(DJI_UAV)/tello_image_ros/2022_2_12/TelloGO_IMAG/src/tello_control/tello_control/tello_base.py
Chentao2000/practice_code
aa4fb6bbc26ac1ea0fb40e6e0889050b7e9f096c
[ "Apache-2.0" ]
null
null
null
import socket import threading import time import numpy as np import libh264decoder from stats import Stats class Tello: """Wrapper class to interact with the Tello drone.""" def __init__(self, local_ip, local_port, imperial=False, command_timeout=.3, tello_ip='192.168.10.1', tello_port=8889): """ Binds to the local IP/port and puts the Tello into command mode. :param local_ip (str): Local IP address to bind. :param local_port (int): Local port to bind. :param imperial (bool): If True, speed is MPH and distance is feet. If False, speed is KPH and distance is meters. :param command_timeout (int|float): Number of seconds to wait for a response to a command. :param tello_ip (str): Tello IP. :param tello_port (int): Tello port. """ self.last = False self.command = "" #for debug self.abort_flag = False self.decoder = libh264decoder.H264Decoder() self.command_timeout = command_timeout self.imperial = imperial self.response = None self.frame = None # numpy array BGR -- current camera output frame self.is_freeze = False # freeze current camera output self.last_frame = None self.log = [] self.MAX_TIME_OUT = 10.0 self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # socket for sending cmd self.socket_video = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # socket for receiving video stream self.socket_state=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)#state socket self.tello_ip=tello_ip self.tello_address = (tello_ip, tello_port) self.local_video_port = 11111 # port for receiving video stream self.last_height = 0 self.socket.bind((local_ip, local_port)) # thread for receiving cmd ack self.receive_thread = threading.Thread(target=self._receive_thread) self.receive_thread.daemon = True self.receive_thread.start() # to receive video -- send cmd: command, streamon self.socket.sendto(b'command', self.tello_address) print ('sent: command') self.socket.sendto(b'streamon', self.tello_address) print ('sent: streamon') self.socket_video.bind((local_ip, self.local_video_port)) # thread for receiving video self.receive_video_thread = threading.Thread(target=self._receive_video_thread) self.receive_video_thread.daemon = True self.receive_video_thread.start() #state receive self.results=None self.socket_state.bind((local_ip,8890)) self.receive_state_thread=threading.Thread(target=self._recevie_state_thread) self.receive_state_thread.daemon=True self.receive_state_thread.start() def __del__(self): """Closes the local socket.""" self.socket.close() self.socket_video.close() self.socket_state.close() def read_frame(self): """Return the last frame from camera.""" if self.is_freeze: return self.last_frame else: return self.frame def read_state(self): if self.results=='ok' or self.results==None: return self.results else: return self.results[0:8] def video_freeze(self, is_freeze=True): """Pause video output -- set is_freeze to True""" self.is_freeze = is_freeze if is_freeze: self.last_frame = self.frame def _receive_thread(self): """Listen to responses from the Tello. Runs as a thread, sets self.response to whatever the Tello last returned. """ while True: try: self.response, ip = self.socket.recvfrom(3000) if len(self.log)!=0: self.log[-1].add_response(self.response) #print(self.response) except socket.error as exc: print ("Caught exception socket.error : %s" % exc) def _receive_video_thread(self): """ Listens for video streaming (raw h264) from the Tello. Runs as a thread, sets self.frame to the most recent frame Tello captured. """ packet_data = "" while True: try: res_string, ip = self.socket_video.recvfrom(2048) packet_data += res_string # end of frame if len(res_string) != 1460: for frame in self._h264_decode(packet_data): self.frame = frame packet_data = "" except socket.error as exc: print ("Caught exception socket.error : %s" % exc) def _recevie_state_thread(self): while True: try: state, ip = self.socket_state.recvfrom(1024) out = state.replace(';', ';\n') self.results = out.split() #print("received result: " + str(self.results) ) except socket.error as exc: print ("Caught exception socket.error : %s" % exc) def _h264_decode(self, packet_data): """ decode raw h264 format data from Tello :param packet_data: raw h264 data array :return: a list of decoded frame """ res_frame_list = [] frames = self.decoder.decode(packet_data) for framedata in frames: (frame, w, h, ls) = framedata if frame is not None: # print 'frame size %i bytes, w %i, h %i, linesize %i' % (len(frame), w, h, ls) frame = np.fromstring(frame, dtype=np.ubyte, count=len(frame), sep='') frame = (frame.reshape((h, ls / 3, 3))) frame = frame[:, :w, :] res_frame_list.append(frame) return res_frame_list def send_command(self, command): """ Send a command to the Tello and wait for a response. :param command: Command to send. :return (str): Response from Tello. """ self.log.append(Stats(command, len(self.log))) print(">> send cmd: {}".format(command)) print(len(self.log),self.log[-1].got_response()) self.socket.sendto(command.encode('utf-8'), self.tello_address) print(len(self.log),self.log[-1].got_response()) self.last = self.log[-1].got_response() start = time.time() #print(self.log[-1].got_response()) timelen = 0. while True: if not self.log[-1].got_response(): continue elif (not self.last) and('ok' in str(self.log[-1].got_response())): break elif ('ok' in str(self.last)) and('ok' in str(self.log[-1].got_response())): self.last = self.log[-1].got_response() continue elif 'ok' not in str(self.log[-1].got_response()): now = time.time() diff = now - start if diff > timelen: print(self.log[-1].got_response()) timelen += 1. self.socket.sendto(command.encode('utf-8'), self.tello_address) #print(len(self.log)) if diff > self.MAX_TIME_OUT: print ('Max timeout exceeded... command %s' % command) raise Exception('command timeout') print ('Done!!! sent command: %s to %s' % (command, self.tello_ip)) print (self.log[-1].got_response()) return self.log[-1].got_response() def set_abort_flag(self): """ Sets self.abort_flag to True. Used by the timer in Tello.send_command() to indicate to that a response timeout has occurred. """ self.abort_flag = True def takeoff(self): """ Initiates take-off. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ return self.send_command('takeoff') def set_speed(self, speed): """ Sets speed. This method expects KPH or MPH. The Tello API expects speeds from 1 to 100 centimeters/second. Metric: .1 to 3.6 KPH Imperial: .1 to 2.2 MPH Args: speed (int|float): Speed. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ speed = float(speed) if self.imperial is True: speed = int(round(speed * 44.704)) else: speed = int(round(speed * 27.7778)) return self.send_command('speed %s' % speed) def rotate_cw(self, degrees): """ Rotates clockwise. Args: degrees (int): Degrees to rotate, 1 to 360. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ return self.send_command('cw %s' % degrees) def rotate_ccw(self, degrees): """ Rotates counter-clockwise. Args: degrees (int): Degrees to rotate, 1 to 360. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ return self.send_command('ccw %s' % degrees) def flip(self, direction): """ Flips. Args: direction (str): Direction to flip, 'l', 'r', 'f', 'b'. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ return self.send_command('flip %s' % direction) def get_response(self): """ Returns response of tello. Returns: int: response of tello. """ response = self.response return response def get_height(self): """Returns height(dm) of tello. Returns: int: Height(dm) of tello. """ height = self.send_command('height?') height = str(height) height = filter(str.isdigit, height) try: height = int(height) self.last_height = height except: height = self.last_height pass return height def get_battery(self): """Returns percent battery life remaining. Returns: int: Percent battery life remaining. """ battery = self.send_command('battery?') try: battery = int(battery) except: pass return battery def get_flight_time(self): """Returns the number of seconds elapsed during flight. Returns: int: Seconds elapsed during flight. """ flight_time = self.send_command('time?') try: flight_time = int(flight_time) except: pass return flight_time def get_speed(self): """Returns the current speed. Returns: int: Current speed in KPH or MPH. """ speed = self.send_command('speed?') try: speed = float(speed) if self.imperial is True: speed = round((speed / 44.704), 1) else: speed = round((speed / 27.7778), 1) except: pass return speed def land(self): """Initiates landing. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ return self.send_command('land') def move(self, direction, distance): """Moves in a direction for a distance. This method expects meters or feet. The Tello API expects distances from 20 to 500 centimeters. Metric: .02 to 5 meters Imperial: .7 to 16.4 feet Args: direction (str): Direction to move, 'forward', 'back', 'right' or 'left'. distance (int|float): Distance to move. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ distance = float(distance) if self.imperial is True: distance = int(round(distance * 30.48)) else: distance = int(round(distance * 100)) return self.send_command('%s %s' % (direction, distance)) def move_backward(self, distance): """Moves backward for a distance. See comments for Tello.move(). Args: distance (int): Distance to move. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ return self.move('back', distance) def move_down(self, distance): """Moves down for a distance. See comments for Tello.move(). Args: distance (int): Distance to move. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ return self.move('down', distance) def move_forward(self, distance): """Moves forward for a distance. See comments for Tello.move(). Args: distance (int): Distance to move. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ return self.move('forward', distance) def move_left(self, distance): """Moves left for a distance. See comments for Tello.move(). Args: distance (int): Distance to move. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ return self.move('left', distance) def move_right(self, distance): """Moves right for a distance. See comments for Tello.move(). Args: distance (int): Distance to move. """ return self.move('right', distance) def move_up(self, distance): """Moves up for a distance. See comments for Tello.move(). Args: distance (int): Distance to move. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ return self.move('up', distance)
28.822485
114
0.529665
37478165cbb1270124f8fd9d85f2a48e92615606
910
py
Python
docs/source/examples/FB2.0/post_quotas_users.py
Flav-STOR-WL/py-pure-client
03b889c997d90380ac5d6380ca5d5432792d3e89
[ "BSD-2-Clause" ]
14
2018-12-07T18:30:27.000Z
2022-02-22T09:12:33.000Z
docs/source/examples/FB2.0/post_quotas_users.py
Flav-STOR-WL/py-pure-client
03b889c997d90380ac5d6380ca5d5432792d3e89
[ "BSD-2-Clause" ]
28
2019-09-17T21:03:52.000Z
2022-03-29T22:07:35.000Z
docs/source/examples/FB2.0/post_quotas_users.py
Flav-STOR-WL/py-pure-client
03b889c997d90380ac5d6380ca5d5432792d3e89
[ "BSD-2-Clause" ]
15
2020-06-11T15:50:08.000Z
2022-03-21T09:27:25.000Z
from pypureclient.flashblade import UserQuota file_system_name = "quotaFs" # Add a quota of 1024 for the file system to apply to the users with ids 123 and 124 res = client.post_quotas_users(file_system_names=[file_system_name], uids=[123, 124], quota=UserQuota(quota=1024)) # print the created quotas print(res) if type(res) == pypureclient.responses.ValidResponse: print(list(res.items)) # Add a quota of 2048 for the file system to apply to the users with names user1 and user2 res = client.post_quotas_users(file_system_names=[file_system_name], user_names=["user1", "user2"], quota=UserQuota(quota=2048)) # print the created quotas print(res) if type(res) == pypureclient.responses.ValidResponse: print(list(res.items)) # Other valid fields: file_system_ids # See section "Common Fields" for examples
39.565217
90
0.696703
3a30879e0d09658c2b82e6bd126f4eec74259c1e
1,068
py
Python
dingo/migrations/0001_initial.py
MartorSkull/Tomu
8bcc2676b030fca1720efce185c398a52eed005a
[ "MIT" ]
null
null
null
dingo/migrations/0001_initial.py
MartorSkull/Tomu
8bcc2676b030fca1720efce185c398a52eed005a
[ "MIT" ]
null
null
null
dingo/migrations/0001_initial.py
MartorSkull/Tomu
8bcc2676b030fca1720efce185c398a52eed005a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-07-19 18:58 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Chatter', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('discord_id', models.IntegerField()), ('discord_username', models.CharField(max_length=32)), ('banned', models.BooleanField(default=False)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'Chatter', 'verbose_name_plural': 'Chatters', }, ), ]
31.411765
121
0.608614
42cc51a10a19fd868be3bffb77ded5505a8ee90b
4,113
py
Python
misc/model-builder/quant/tflite.py
jackwish/shrub
acd14c72269c88e3143997288efcc6f0130c4c8e
[ "Apache-2.0" ]
2
2020-09-23T01:16:39.000Z
2022-01-26T23:16:21.000Z
misc/model-builder/quant/tflite.py
jackwish/shrub
acd14c72269c88e3143997288efcc6f0130c4c8e
[ "Apache-2.0" ]
1
2020-09-23T01:09:54.000Z
2020-09-23T01:09:54.000Z
misc/model-builder/quant/tflite.py
jackwish/shrub
acd14c72269c88e3143997288efcc6f0130c4c8e
[ "Apache-2.0" ]
null
null
null
import os import numpy as np import tensorflow as tf from tensorflow.python.platform import gfile from tensorflow.core.framework import graph_pb2 from tensorflow.python.framework import graph_util class OpChecker: def __init__(self, op, ishape, range_min, range_max, mode="MIN_COMBINED"): # args in TensorFlow style self.op = op self.name = 'gen' self.ishape = ishape self.oshape = ishape self.min = range_min self.max = range_max self.mode = mode self.iname = 'input' self.oname = 'output' if op == tf.quantize: self.idtype = tf.float32 self.odtype = tf.quint8 self.tflite_model_path = "quant.tflite" self.tflite_dtype = tf.float32 elif op == tf.dequantize: self.idtype = tf.quint8 self.odtype = tf.float32 self.tflite_model_path = "dequant.tflite" self.tflite_dtype = tf.float32 else: raise ValueError("Unkown op") def genModels(self): print("Generating Models...") with tf.Session(graph=tf.Graph()) as sess: data = tf.placeholder( self.idtype, shape=self.ishape, name=self.iname) output = self.op( data, self.min, self.max, tf.quint8, mode=self.mode, name=self.oname) sess.run(tf.global_variables_initializer()) constant_graph = graph_util.convert_variables_to_constants( sess, sess.graph_def, [self.oname]) with tf.gfile.FastGFile(self.name + ".pb", mode='wb') as f: f.write(constant_graph.SerializeToString()) def genTFLiteModel(self): print("Generating TensorFlow Lite model...") converter = tf.lite.TFLiteConverter.from_frozen_graph( self.name + ".pb", input_arrays=[self.iname], output_arrays=[self.oname, ]) # converter.inference_type = self.tflite_dtype # converter.inference_inpute_type = self.tflite_dtype converter.default_ranges_stats = (0, 6) converter.quantized_input_stats = {self.iname: (100, 100.0)} # converter.post_training_quantize = True # converter.target_ops = set([OpsSet.TFLITE_BUILTINS]) tflite_model = converter.convert() open(self.name + ".tflite", "wb").write(tflite_model) def preRun(self): self.input_nhwc = np.random.uniform( size=self.ishape).astype( self.dtype) self.input_nchw = self.input_nhwc.transpose(0, 3, 1, 2) def runTensorFlow(self): print("run TensorFlow...") tf.reset_default_graph() graph_def = graph_pb2.GraphDef() with open(self.name + ".pb", 'rb') as f: graph_def.ParseFromString(f.read()) g = tf.import_graph_def(graph_def) with tf.Session(graph=g) as sess: image_input_tensor = sess.graph.get_tensor_by_name( 'import/' + self.iname + ":0") outputs = [ sess.graph.get_tensor_by_name( "import/" + self.oname + ":0")] self.output_tf = sess.run( outputs, feed_dict={ image_input_tensor: self.input_nhwc})[0] def test_OP(op, input_shape, range_min, range_max, mode="MIN_COMBINED"): op = OpChecker(op, input_shape, range_min, range_max, mode=mode) op.genModels() op.genTFLiteModel() def test_dequant(): print("[START] test_dequant") print("") input_shape = (1, 256, 256, 32) # NHWC range_min = 0.0 range_max = 6.0 # see # http://tensorflow.biotecan.com/python/Python_1.8/tensorflow.google.cn/api_docs/python/tf/dequantize.html mode = 'MIN_COMBINED' # mode='MIN_FIRST' # mode='SCALED' quant_op = tf.dequantize quant_op = tf.quantize test_OP(quant_op, input_shape, range_min, range_max, mode=mode) print("") print("[DONE] test_dequant") test_dequant()
32.904
110
0.592025
952eb3ab8d7cc0df19291f01e960de255a4ae1a4
2,005
py
Python
solutions/2021/day_13.py
mokytis/advent-of-code
7bddbc87411388bb0da8284c3daa5252f9d5007d
[ "MIT" ]
null
null
null
solutions/2021/day_13.py
mokytis/advent-of-code
7bddbc87411388bb0da8284c3daa5252f9d5007d
[ "MIT" ]
null
null
null
solutions/2021/day_13.py
mokytis/advent-of-code
7bddbc87411388bb0da8284c3daa5252f9d5007d
[ "MIT" ]
null
null
null
#!/usr/bin/env python """ Puzzle Title: AoC 2021 Day 13: Transparent Origami Puzzle Link: https://adventofcode.com/2021/day/13 Solution Author: Luke Spademan <info@lukespademan.com> Solution License: MIT """ import fileinput from dataclasses import dataclass import copy @dataclass class Fold: axis: str value: int def parse_input(): points = set() folds = [] for line in map(lambda x: x.rstrip(), fileinput.input()): if line: if line.startswith("fold along "): axis, value = line[11:].split("=") folds.append(Fold(axis, int(value))) else: num1, num2 = line.split(",") points.add((int(num1), int(num2))) return points, folds def fold_points(points, fold): if fold.axis == "x": i = 0 else: i = 1 for point in copy.copy(points): if point[i] == fold.value: points.remove(point) elif point[i] > fold.value: points.remove(point) distance = point[i] - fold.value if i == 0: points.add((fold.value - distance, point[1])) else: points.add((point[0], fold.value - distance)) return len(points) def output(points): ys = [point[1] for point in points] xs = [point[0] for point in points] for row in range(min(ys), max(ys) + 1): for value in range(min(xs), max(xs) + 1): if (value, row) in points: print("#", end="") else: print(" ", end="") print() def solve_part1(points, fold): return fold_points(points, fold) def solve_part2(points, folds): for fold in folds: fold_points(points, fold) output(points) def main(): points, folds = parse_input() part1_ans = solve_part1(points, folds[0]) print(f"Part 1: {part1_ans}") print("Part 2:") solve_part2(points, folds) if __name__ == "__main__": main()
22.784091
61
0.555611
36713fc18c6674c212407ad55c4487c7aec9645d
4,512
py
Python
db/Student.py
sysu-team1/BackEnd
4773545897fee3aa7a767cbe6d011372623e1e58
[ "MIT" ]
1
2019-11-19T09:08:50.000Z
2019-11-19T09:08:50.000Z
db/Student.py
sysu-team1/BackEnd
4773545897fee3aa7a767cbe6d011372623e1e58
[ "MIT" ]
null
null
null
db/Student.py
sysu-team1/BackEnd
4773545897fee3aa7a767cbe6d011372623e1e58
[ "MIT" ]
null
null
null
import copy import random from .prepare import app, db, model_repr, SEX, EDUBG, ALL_TAGS class Student(db.Model): ''' 使用的sql语句: ```sql CREATE TABLE `students` ( `openid` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户的唯一标识符', `email` varchar(40) NOT NULL COMMENT '学校邮箱', `password` varchar(20) NOT NULL COMMENT '密码', `student_id` varchar(10) NOT NULL DEFAULT '' COMMENT '学号', `name` varchar(100) DEFAULT '' COMMENT '名称', `sex` enum('unknown','male','female') DEFAULT 'unknown' COMMENT '用户性别', `collage` varchar(20) DEFAULT '' COMMENT '学院', `grade` int(11) NOT NULL DEFAULT '2016' COMMENT '入学年级', `edu_bg` enum('undergraduate','masterofscience','doctor') DEFAULT 'undergraduate' COMMENT '学历', `tag` varchar(100) DEFAULT '' COMMENT '与任务相关的标签', `signature` varchar(300) DEFAULT '' COMMENT '用户签名', `cash` int(11) DEFAULT '0' COMMENT '拥有的币', PRIMARY KEY (`openid`), FULLTEXT KEY `stu_tag` (`tag`) ) ENGINE=InnoDB AUTO_INCREMENT=1000000 DEFAULT CHARSET=utf8 ``` 属性: 基础属性 accepts: 表示接收的任务 tasks: 表示发布的任务 ''' __tablename__ = 'students' openid = db.Column('openid', db.Integer( ), autoincrement=True, nullable=False, comment='用户的唯一标识符') email = db.Column('email', db.VARCHAR( 40), nullable=False, comment='学校邮箱') password = db.Column('password', db.VARCHAR( 20), nullable=False, comment='密码') student_id = db.Column('student_id', db.VARCHAR( 10), nullable=False, server_default='', comment='学号') name = db.Column('name', db.VARCHAR( 100), server_default='', comment='名称') sex = db.Column('sex', db.Enum( *SEX), server_default=SEX[0], comment='用户性别') # default的话是在插入时才有的 collage = db.Column('collage', db.VARCHAR( 20), server_default='', comment='学院') grade = db.Column('grade', db.Integer( ), nullable=False, server_default='2016', comment='入学年级') edu_bg = db.Column('edu_bg', db.Enum( *EDUBG), server_default=EDUBG[0], comment='学历') tag = db.Column('tag', db.VARCHAR( 100), server_default='', comment='与任务相关的标签') signature = db.Column('signature', db.VARCHAR( 300), server_default='', comment='用户签名') cash = db.Column('cash', db.Integer(), server_default='0', comment='拥有的币') __table_args__ = ( db.PrimaryKeyConstraint('openid'), db.Index('stu_tag', 'tag', mysql_prefix='FULLTEXT'), ) accepts = db.relationship( 'Accept', back_populates='student', cascade='delete') tasks = None # _tasks = None # get_tasks = None # get_tasks = None # def __getattribute__(self, name): # if name == 'tasks' and self.task is None and Student.get_tasks is not None: # 无限递归 # self.tasks = Student.get_tasks(self.openid) # return super(Student, self).__getattribute__(name) def __repr__(self): # return '<Student(email={}, password={}, sex={}, collage={}, grade={}, edu_bg={}, tag={}, signature={})>'.format( # self.email, self.password, self.sex, self.collage, self.grade, self.edu_bg, self.tag, self.signature) # return model_repr(self, config.STUDENT_JSON_PATTERN, config.STUDENT_JSON_ATTR_ORDER) return model_repr(self, app.config['STUDENT_JSON_PATTERN'], app.config['STUDENT_JSON_ATTR_ORDER']) def random_stus(num): rand_collages = ['药学院', '数据科学与计算机学院', '法学院', '心理学院', '哲学院', '医学院'] tag_len = len(ALL_TAGS) stus = [] for i in range(num): sex = random.choice(SEX) edu_bg = random.choice(EDUBG) collage = random.choice(rand_collages) grade = 2019 - random.randint(0, 10) rnum = random.randint(0, tag_len) tag = [] all_tags = copy.deepcopy(ALL_TAGS) while len(tag) < rnum: index = random.randint(0, len(all_tags) - 1) tag.append(all_tags[index]) all_tags.pop(index) tag = ','.join(tag) start, length = random.randint(1, 20), random.randint(10, 15) signature = ' '.join(['word{}'.format( j) for j in range(start, start + length)]) cash = random.randint(10, 5000) stus.append(Student(email='email{}@qq.com'.format(i), password='pass{}'.format( i), student_id="16340{:0>3d}".format(i), name="16340{:0>3d}".format(i), sex=sex, collage=collage, grade=grade, edu_bg=edu_bg, tag=tag, signature=signature, cash=cash)) return stus
41.777778
179
0.61547
2b506051142c4cac247166250931716794b59bc6
647
py
Python
md5sum/md5sum/handler.py
quartz010/OpenAPI
a62383e7ec606a1106c56e7ddc840142711250a7
[ "MIT" ]
null
null
null
md5sum/md5sum/handler.py
quartz010/OpenAPI
a62383e7ec606a1106c56e7ddc840142711250a7
[ "MIT" ]
null
null
null
md5sum/md5sum/handler.py
quartz010/OpenAPI
a62383e7ec606a1106c56e7ddc840142711250a7
[ "MIT" ]
null
null
null
import json import random import hashlib def handle(req): """handle a request to the function Args: req (str): request body """ ret = { "code": 0, "msg": "" } if req == "": ret["code"] = 0 ret["msg"] = "invalid parameters" return json.dumps(ret) else: try: hash = hashlib.md5(req.encode("utf-8")).hexdigest() ret["code"] = 0 ret["msg"] = hash return json.dumps(ret) except Exception as e: ret["code"] = -1 ret["msg"] = e return json.dumps(ret) return json.dumps(ret)
23.107143
63
0.476043
936d2d5340df81b206be3de68bd604659ede6009
6,290
py
Python
utils/metric.py
zhoufangquan/sccl
4a30cca7980f1e7319d4ce727196ea74854025b8
[ "MIT-0" ]
null
null
null
utils/metric.py
zhoufangquan/sccl
4a30cca7980f1e7319d4ce727196ea74854025b8
[ "MIT-0" ]
null
null
null
utils/metric.py
zhoufangquan/sccl
4a30cca7980f1e7319d4ce727196ea74854025b8
[ "MIT-0" ]
null
null
null
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved Author: Dejiao Zhang (dejiaoz@amazon.com) Date: 02/26/2021 """ from __future__ import print_function import time import torch import numpy as np from scipy.optimize import linear_sum_assignment as hungarian from sklearn.metrics.cluster import normalized_mutual_info_score, adjusted_rand_score, adjusted_mutual_info_score cluster_nmi = normalized_mutual_info_score def cluster_acc(y_true, y_pred): y_true = y_true.astype(np.int64) assert y_pred.size == y_true.size D = max(y_pred.max(), y_true.max()) + 1 w = np.zeros((D, D), dtype=np.int64) for i in range(y_pred.size): w[y_pred[i], y_true[i]] += 1 # ind = sklearn.utils.linear_assignment_.linear_assignment(w.max() - w) # row_ind, col_ind = linear_assignment(w.max() - w) row_ind, col_ind = hungarian(w.max() - w) return sum([w[i, j] for i, j in zip(row_ind, col_ind)]) * 1.0 / y_pred.size class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = float(self.sum) / self.count class Timer(object): """ """ def __init__(self): self.reset() def reset(self): self.interval = 0 self.time = time.time() def value(self): return time.time() - self.time def tic(self): self.time = time.time() def toc(self): self.interval = time.time() - self.time self.time = time.time() return self.interval class Confusion(object): """ column of confusion matrix: predicted index row of confusion matrix: target index """ def __init__(self, k, normalized = False): super(Confusion, self).__init__() self.k = k self.conf = torch.LongTensor(k,k) self.normalized = normalized self.reset() def reset(self): self.conf.fill_(0) self.gt_n_cluster = None def cuda(self): self.conf = self.conf.cuda() def add(self, output, target): output = output.squeeze() target = target.squeeze() assert output.size(0) == target.size(0), \ 'number of targets and outputs do not match' if output.ndimension()>1: #it is the raw probabilities over classes assert output.size(1) == self.conf.size(0), \ 'number of outputs does not match size of confusion matrix' _,pred = output.max(1) #find the predicted class else: #it is already the predicted class pred = output indices = ((target-1)*self.conf.stride(0) + pred.squeeze_().type_as(target)).type_as(self.conf) ones = torch.ones(1).type_as(self.conf).expand(indices.size(0)) self._conf_flat = self.conf.view(-1) self._conf_flat.index_add_(0, indices, ones) def classIoU(self,ignore_last=False): confusion_tensor = self.conf if ignore_last: confusion_tensor = self.conf.narrow(0,0,self.k-1).narrow(1,0,self.k-1) union = confusion_tensor.sum(0).view(-1) + confusion_tensor.sum(1).view(-1) - confusion_tensor.diag().view(-1) acc = confusion_tensor.diag().float().view(-1).div(union.float()+1) return acc def recall(self,clsId): i = clsId TP = self.conf[i,i].sum().item() TPuFN = self.conf[i,:].sum().item() if TPuFN==0: return 0 return float(TP)/TPuFN def precision(self,clsId): i = clsId TP = self.conf[i,i].sum().item() TPuFP = self.conf[:,i].sum().item() if TPuFP==0: return 0 return float(TP)/TPuFP def f1score(self,clsId): r = self.recall(clsId) p = self.precision(clsId) print("classID:{}, precision:{:.4f}, recall:{:.4f}".format(clsId, p, r)) if (p+r)==0: return 0 return 2*float(p*r)/(p+r) def acc(self): TP = self.conf.diag().sum().item() total = self.conf.sum().item() if total==0: return 0 return float(TP)/total def optimal_assignment(self,gt_n_cluster=None,assign=None): if assign is None: mat = -self.conf.cpu().numpy() #hungaian finds the minimum cost r,assign = hungarian(mat) self.conf = self.conf[:,assign] self.gt_n_cluster = gt_n_cluster return assign def show(self,width=6,row_labels=None,column_labels=None): print("Confusion Matrix:") conf = self.conf rows = self.gt_n_cluster or conf.size(0) cols = conf.size(1) if column_labels is not None: print(("%" + str(width) + "s") % '', end='') for c in column_labels: print(("%" + str(width) + "s") % c, end='') print('') for i in range(0,rows): if row_labels is not None: print(("%" + str(width) + "s|") % row_labels[i], end='') for j in range(0,cols): print(("%"+str(width)+".d")%conf[i,j],end='') print('') def conf2label(self): conf=self.conf gt_classes_count=conf.sum(1).squeeze() n_sample = gt_classes_count.sum().item() gt_label = torch.zeros(n_sample) pred_label = torch.zeros(n_sample) cur_idx = 0 for c in range(conf.size(0)): if gt_classes_count[c]>0: gt_label[cur_idx:cur_idx+gt_classes_count[c]].fill_(c) for p in range(conf.size(1)): if conf[c][p]>0: pred_label[cur_idx:cur_idx+conf[c][p]].fill_(p) cur_idx = cur_idx + conf[c][p]; return gt_label,pred_label def clusterscores(self): target,pred = self.conf2label() NMI = normalized_mutual_info_score(target,pred) ARI = adjusted_rand_score(target,pred) AMI = adjusted_mutual_info_score(target,pred) return {'NMI':NMI,'ARI':ARI,'AMI':AMI}
33.280423
118
0.574245
f4728ba13f09797b37c9db6214f9680bb58f6aab
5,848
py
Python
ironic_inspector/conf/default.py
xudan16/ironic-inspector
1d8383d0ae82730c7a107dbe85712171430b237a
[ "Apache-2.0" ]
null
null
null
ironic_inspector/conf/default.py
xudan16/ironic-inspector
1d8383d0ae82730c7a107dbe85712171430b237a
[ "Apache-2.0" ]
null
null
null
ironic_inspector/conf/default.py
xudan16/ironic-inspector
1d8383d0ae82730c7a107dbe85712171430b237a
[ "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 socket from oslo_config import cfg from oslo_config import types as cfg_types from ironic_inspector.common.i18n import _ class Octal(cfg_types.Integer): def __call__(self, value): if isinstance(value, int): return value else: return int(str(value), 8) _OPTS = [ cfg.StrOpt('listen_address', default='::', help=_('IP to listen on.')), cfg.PortOpt('listen_port', default=5050, help=_('Port to listen on.')), cfg.StrOpt('listen_unix_socket', help=_('Unix socket to listen on. Disables listen_address and ' 'listen_port.')), cfg.Opt('listen_unix_socket_mode', type=Octal(), help=_('File mode (an octal number) of the unix socket to ' 'listen on. Ignored if listen_unix_socket is not set.')), cfg.StrOpt('host', default=socket.getfqdn(), sample_default='localhost', help=_('Name of this node. This can be an opaque identifier. ' 'It is not necessarily a hostname, FQDN, or IP address. ' 'However, the node name must be valid within ' 'an AMQP key, and if using ZeroMQ, a valid ' 'hostname, FQDN, or IP address.')), cfg.StrOpt('auth_strategy', default='keystone', choices=[('noauth', _('no authentication')), ('keystone', _('use the Identity service for ' 'authentication')), ('http_basic', _('HTTP basic authentication'))], help=_('Authentication method used on the ironic-inspector ' 'API. "noauth", "keystone" or "http_basic" are valid ' 'options. "noauth" will disable all authentication.')), cfg.StrOpt('http_basic_auth_user_file', default='/etc/ironic-inspector/htpasswd', help=_('Path to Apache format user authentication file used ' 'when auth_strategy=http_basic')), cfg.IntOpt('timeout', default=3600, # We're using timedelta which can overflow if somebody sets this # too high, so limit to a sane value of 10 years. max=315576000, help=_('Timeout after which introspection is considered ' 'failed, set to 0 to disable.')), cfg.IntOpt('clean_up_period', default=60, min=0, help=_('Amount of time in seconds, after which repeat clean up ' 'of timed out nodes and old nodes status information. ' 'WARNING: If set to a value of 0, then the periodic ' 'task is disabled and inspector will not sync with ' 'ironic to complete the internal clean-up process. ' 'Not advisable if the deployment uses a PXE filter, ' 'and will result in the ironic-inspector ceasing ' 'periodic cleanup activities.')), cfg.IntOpt('leader_election_interval', default=10, help=_('Interval (in seconds) between leader elections.')), cfg.BoolOpt('use_ssl', default=False, help=_('SSL Enabled/Disabled')), cfg.IntOpt('max_concurrency', default=1000, min=2, help=_('The green thread pool size.')), cfg.IntOpt('introspection_delay', default=5, help=_('Delay (in seconds) between two introspections. Only ' 'applies when boot is managed by ironic-inspector (i.e. ' 'manage_boot==True).')), cfg.ListOpt('ipmi_address_fields', default=['redfish_address', 'ilo_address', 'drac_host', 'drac_address', 'ibmc_address'], help=_('Ironic driver_info fields that are equivalent ' 'to ipmi_address.')), cfg.StrOpt('rootwrap_config', default="/etc/ironic-inspector/rootwrap.conf", help=_('Path to the rootwrap configuration file to use for ' 'running commands as root')), cfg.IntOpt('api_max_limit', default=1000, min=1, help=_('Limit the number of elements an API list-call ' 'returns')), cfg.BoolOpt('can_manage_boot', default=True, help=_('Whether the current installation of ironic-inspector ' 'can manage PXE booting of nodes. If set to False, ' 'the API will reject introspection requests with ' 'manage_boot missing or set to True.')), cfg.BoolOpt('enable_mdns', default=False, help=_('Whether to enable publishing the ironic-inspector API ' 'endpoint via multicast DNS.')), cfg.BoolOpt('standalone', default=True, help=_('Whether to run ironic-inspector as a standalone ' 'service. It\'s EXPERIMENTAL to set to False.')), ] def register_opts(conf): conf.register_opts(_OPTS) def list_opts(): return _OPTS
45.333333
79
0.569596
adec575a6cfd91740bba0af163e0cda71cc2cc6a
5,984
py
Python
fracdiff/fracdiffstat.py
vishalbelsare/fracdiff
d51d575b147dbabd9eff9833ef207716d69f9e40
[ "BSD-3-Clause" ]
44
2019-12-23T12:25:50.000Z
2022-01-08T16:04:33.000Z
fracdiff/fracdiffstat.py
simaki/fracdiff
d51d575b147dbabd9eff9833ef207716d69f9e40
[ "BSD-3-Clause" ]
71
2019-12-23T12:55:54.000Z
2021-04-30T10:14:09.000Z
fracdiff/fracdiffstat.py
vishalbelsare/fracdiff
d51d575b147dbabd9eff9833ef207716d69f9e40
[ "BSD-3-Clause" ]
19
2020-06-23T01:34:44.000Z
2022-02-19T21:01:51.000Z
import numpy from sklearn.base import BaseEstimator from sklearn.base import TransformerMixin from sklearn.utils.validation import check_array from sklearn.utils.validation import check_is_fitted from fracdiff import Fracdiff from fracdiff.stat import StatTester class FracdiffStat(TransformerMixin, BaseEstimator): """ Carry out fractional derivative with the minumum order with which the differentiation becomes stationary. Parameters ---------- window : int > 0 or None, default 10 Number of observations to compute each element in the output. mode : {"full", "valid"}, default "full" "full" (default) : Return elements where at least one coefficient is used. Shape of a transformed array is the same with the original array. At the beginning of a transformed array, boundary effects may be seen. "valid" : Return elements where all coefficients are used. Output size along axis 1 is `n_features - window_`. At the beginning of a time-series, boundary effects is not seen. window_policy : {"fixed"}, default "fixed" If "fixed" : Fixed window method. Every term in the output is evaluated using `window_` observations. In other words, a fracdiff operator, which is a polynominal of a backshift operator, is truncated up to the `window_`-th term. The beginning `window_ - 1` elements in output are filled with ``numpy.nan``. If "expanding" (not available) : Expanding window method. Every term in fracdiff time-series is evaluated using at least `window_` observations. The beginning `window_ - 1` elements in output are filled with ``numpy.nan``. stattest : {"ADF"}, default "ADF" Method of stationarity test. pvalue : float, default 0.05 Threshold of p-value to judge stationarity. precision : float, default .01 Precision for the order of differentiation. upper : float, default 1.0 Upper limit of the range to search the order. lower : float, default 0.0 Lower limit of the range to search the order. Attributes ---------- d_ : numpy.array, shape (n_features,) Minimum order of fractional differentiation that makes time-series stationary. Note ---- If `upper`th differentiation of series is still non-stationary, order_ is set to ``numpy.nan``. If `lower`th differentiation of series is already stationary, order_ is set to `lower`, but the true value may be smaller. Examples -------- >>> numpy.random.seed(42) >>> X = numpy.random.randn(100, 4).cumsum(0) >>> f = FracdiffStat().fit(X) >>> f.d_ array([0.140625 , 0.5078125, 0.3984375, 0.140625 ]) >>> X = f.transform(X) """ def __init__( self, window=10, mode="full", window_policy="fixed", stattest="ADF", pvalue=0.05, precision=0.01, upper=1.0, lower=0.0, ): self.window = window self.mode = mode self.window_policy = window_policy self.stattest = stattest self.pvalue = pvalue self.precision = precision self.upper = upper self.lower = lower def fit(self, X, y=None): """ Fit the model with `X`. Parameters ---------- X : array_like, shape (n_samples, n_features) Time-series to perform fractional differentiation. Here `n_samples` is the number of samples and `n_features` is the number of features. y : array_like, optional Ignored. Returns ------- self : object Returns the instance itself. """ check_array(X) self.d_ = numpy.array([self._find_d(X[:, i]) for i in range(X.shape[1])]) return self def transform(self, X, y=None) -> numpy.array: """ Return the fractional differentiation of `X`. Parameters ---------- X : array_like, shape (n_samples, n_series) Time-series to perform fractional differentiation. Raises ValueError if `n_samples < self.window_`. y : array_like, optional Ignored. Returns ------- fdiff : ``numpy.array``, shape (n_samples, n_series) The fractional differentiation of `X`. """ check_is_fitted(self, ["d_"]) check_array(X) prototype = Fracdiff(0.5, window=self.window, mode=self.mode).fit_transform(X) out = numpy.empty_like(prototype[:, :0]) for i in range(X.shape[1]): f = Fracdiff(self.d_[i], window=self.window, mode=self.mode) d = f.fit_transform(X[:, [i]])[-out.shape[0] :] out = numpy.concatenate((out, d), 1) return out def _is_stat(self, x) -> bool: return StatTester(method=self.stattest).is_stat(x, pvalue=self.pvalue) def _find_d(self, x) -> float: """ Carry out binary search of minimum order of fractional differentiation to make the time-series stationary. Parameters ---------- x : array, shape (n,) Returns ------- d : float """ def diff(d): fracdiff = Fracdiff(d, window=self.window, mode=self.mode) return fracdiff.fit_transform(x.reshape(-1, 1)).reshape(-1) if not self._is_stat(diff(self.upper)): return numpy.nan if self._is_stat(diff(self.lower)): return self.lower upper, lower = self.upper, self.lower while upper - lower > self.precision: m = (upper + lower) / 2 if self._is_stat(diff(m)): upper = m else: lower = m return upper
32.172043
87
0.586397
2007ecff4db118c8dacb9f8abdbef4203b900a64
14,581
py
Python
dev-docs/extlibs/rar_SSokolow.py
VenoMpie/pyrescene
f75d98d9173f1576b5d8fd42da300673e918707c
[ "MIT" ]
18
2020-08-09T02:17:46.000Z
2022-02-18T09:17:25.000Z
dev-docs/extlibs/rar_SSokolow.py
VenoMpie/pyrescene
f75d98d9173f1576b5d8fd42da300673e918707c
[ "MIT" ]
1
2021-11-23T21:13:37.000Z
2021-11-23T21:13:37.000Z
dev-docs/extlibs/rar_SSokolow.py
VenoMpie/pyrescene
f75d98d9173f1576b5d8fd42da300673e918707c
[ "MIT" ]
9
2020-10-15T11:02:49.000Z
2022-03-15T10:36:14.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A pure-Python module for identifying and examining RAR files developed without any exposure to the original unrar code. (Just format docs from wotsit.org) It was, however, influenced by the zipfile module in the Python standard library as, having already decided to match the zipfile.ZipFile API as closely as feasibly possible, I didn't see a point to doing extra work to come up with new ways of laying out my code for no good reason. @todo: Determine how rarfile (http://rarfile.berlios.de/) compares to this in various target metrics. If it is superior or close enough on all fronts, patch it as necessary and plan a migration path. Otherwise, do the following: - Complete the parsing of the RAR metadata. (eg. Get data from archive header, check CRCs, read cleartext comments, etc.) - Optimize further and write a test suite. - Double-check that ZipFile/ZipInfo API compatibility has been maintained wherever feasible. - Support extraction of files stored with no compression. - Look into supporting split and password-protected RARs. - Some password-protected RAR files use blocks with types 0x30, 0x60, and 0xAD according to this code. Figure out whether it's a bug or whether they're really completely new kinds of blocks. (Encrypted headers for filename-hiding?) - When the appropriate code is available, use the following message for failure to extract compressed files:: For reasons of patent, performance, and a general lack of motivation on the author's part, this module does not extract compressed files. """ __appname__ = "rar.py" __author__ = "Stephan Sokolow (deitarion/SSokolow)" __version__ = "0.2.99.0" __license__ = "PSF License 2.4 or higher (The Python License)" #{ Settings for findRarHeader() CHUNK_SIZE = 4096 MARKER_BLOCK = "\x52\x61\x72\x21\x1a\x07\x00" FIND_LIMIT = 1024**2 #: 1MiB # A Compromise. Override FIND_LIMIT with 0 to be sure but potentially very slow. #{ Packing method values RAR_STORED = 0x30 RAR_FASTEST = 0x31 RAR_FAST = 0x32 RAR_NORMAL = 0x33 RAR_GOOD = 0x34 RAR_BEST = 0x35 #} import math, struct, sys, time, zlib _struct_blockHeader = struct.Struct("<HBHH") _struct_addSize = struct.Struct('<L') _struct_fileHead_add1 = struct.Struct("<LBLLBBHL") # Plus FILE_NAME and everything after it class BadRarFile(Exception): """Raised when no valid RAR header is found in a given file.""" class RarInfo(object): """The metadata for a file stored in a RAR archive. @attention: API compatibility with ZipInfo could not be maintained in the following fields: - C{create_version} (Not stored in RAR files) - C{flag_bits} (Zip and RAR use different file header flags) - C{volume} (Zip files specify volume number. RAR files just have "File is continued from previous" and "File continues in next" flags and an archive-level "is volume" flag) - C{comment} (RAR files may have multiple comments per file and they may be stored using compression... which rar.py doesn't support) @todo: How do I interpret the raw file timestamp? @todo: Is the file's CRC of the compressed or uncompressed data? @todo: Does RAR perform any kind of path separator normalization? """ os_map = ['MS DOS', 'OS/2', 'Win32', 'Unix'] #: Interpretations for possible L{create_system} values. compress_size = None #: File's compressed size compress_type = None #: Packing method (C{0x30} indicates no compression) create_system = None #: Type of system on which the file originated (See L{os_map}) date_time = None #: File's timestamp external_attr = None #: File's attributes extract_version = None #: Minimum RAR version needed to extract (major * 10 + minor) filename = None #: Filename relative to the archive root file_size = None #: File's uncompressed size flag_bits = 0 #: Raw flag bits from the RAR header header_offset = None #: Offset of the compressed data within the file is_directory = False #: The entry describes a folder/directory is_encrypted = False #: The file has been encrypted with a password is_solid = False #: Information from previous files has been used not_first_piece = False #: File is continued from previous volume not_last_piece = False #: File continues in next volume CRC = None #: File's CRC _raw_time = None #: Raw integer time value extracted from the header #TODO: comment, extra, reserved, internal_attr def __init__(self, filename, ftime=0): """ @param filename: The file's name and path relative to the archive root. @note: Since I know of no filesystem which allows null bytes in paths, this borrows a trick from C{ZipInfo} and truncates L{filename} at the first null byte to protect against certain kinds of virus tricks. @todo: Implement support for taking ints OR tuples for L{ftime}. """ null_byte = filename.find(chr(0)) if null_byte >= 0: filename = filename[0:null_byte] self.filename = filename self.orig_filename = filename # Match ZipInfo for better compatibility self._raw_time = ftime self.date_time = time.gmtime(self._raw_time) #TODO: Verify this is correct. class RarFile(object): """A simple parser for RAR archives capable of retrieving content metadata and, possibly in the future, of extracting entries stored without compression. @note: Whenever feasible, this class replicates the API of C{zipfile.ZipFile}. As a side-effect, design decisions the author has no strong feelings about (eg. naming of private methods) will generally closely follow those made C{in zipfile.ZipFile}. """ _block_types = { 0x72: 'Marker Block ( MARK_HEAD )', 0x73: 'Archive Heaver ( MAIN_HEAD )', 0x74: 'File Header', 0x75: 'Comment Header', 0x76: 'Extra Info', 0x77: 'Subblock', 0x78: 'Recovery Record', 0x7b: 'Terminator?' } #: Raw HEAD_TYPE values used in block headers. # According to the comment in zipfile.ZipFile, __del__ needs fp here. fp = None #: The file handle used to read the metadata. _filePassed = None #: Whether an already-open file handle was passed in. # I just put all public members here as a matter of course. filelist = None #: A C{list} of L{RarInfo} objects corresponding to the contents. debug = 0 #: Debugging verbosity. Effective range is currently 0 to 1. def __init__(self, handle): # If we've been given a path, get our desired file-like object. if isinstance(handle, basestring): self_filePassed = False self.filename = handle self.fp = open(handle, 'rb') else: self._filePassed = True self.fp = handle self.filename = getattr(handle, 'name', None) # Find the header, skipping the SFX module if present. start_offset = findRarHeader(self.fp) if start_offset: self.fp.seek(start_offset) else: if not self._filePassed: self.fp.close() self.fp = None raise BadRarFile("Not a valid RAR file") self.filelist = [] # Actually read the file metadata. self._getContents() def __del__(self): """Close the file handle if we opened it... just in case the underlying Python implementation doesn't do refcount closing.""" if self.fp and not self._filePassed: self.fp.close() def _getContents(self): """Content-reading code is here separated from L{__init__} so that, if the author so chooses, writing of uncompressed RAR files may be implemented in a later version more easily. """ while True: offset = self.fp.tell() # Read the fields present in every type of block header try: head_crc, head_type, head_flags, head_size = self._read_struct(_struct_blockHeader) except struct.error: # If it fails here, we've reached the end of the file. return # Read the optional field ADD_SIZE if present. if head_flags & 0x8000: add_size = self._read_struct(_struct_addSize)[0] else: add_size = 0 # TODO: Rework handling of archive headers. if head_type == 0x73: #TODO: Try to factor this out to reduce time spent in syscalls. self.fp.seek(offset + 2) # Seek to just after HEAD_CRC #FIXME: Check header CRC on all blocks. assert self._check_crc(self.fp.read(11), head_crc) # TODO: Rework handling of file headers. elif head_type == 0x74: unp_size, host_os, file_crc, ftime, unp_ver, method, name_size, attr = self._read_struct(_struct_fileHead_add1) # FIXME: What encoding does WinRAR use for filenames? # TODO: Verify that ftime is seconds since the epoch as it seems fileinfo = RarInfo(self.fp.read(name_size), ftime) fileinfo.compress_size = add_size fileinfo.header_offset = offset fileinfo.file_size = unp_size #TODO: What about >2GiB files? (Zip64 equivalent?) fileinfo.CRC = file_crc #TODO: Verify the format matches that ZipInfo uses. fileinfo.compress_type = method # Note: RAR seems to have copied the encoding methods used by # Zip for these values. fileinfo.create_system = host_os fileinfo.extract_version = unp_ver fileinfo.external_attr = attr #TODO: Verify that this is correct. # Handle flags fileinfo.flag_bits = head_flags fileinfo.not_first_piece = head_flags & 0x01 fileinfo.not_last_piece = head_flags & 0x02 fileinfo.is_encrypted = head_flags & 0x04 #TODO: Handle comments fileinfo.is_solid = head_flags & 0x10 # TODO: Verify this is correct handling of bits 7,6,5 == 111 fileinfo.is_directory = head_flags & 0xe0 self.filelist.append(fileinfo) elif self.debug > 0: sys.stderr.write("Unhandled block: %s\n" % self._block_types.get(head_type, 'Unknown (0x%x)' % head_type)) # Line up for the next block #TODO: Try to factor this out to reduce time spent in syscalls. self.fp.seek(offset + head_size + add_size) def _read_struct(self, fmt): """Simplifies the process of extracting a struct from the open file.""" return fmt.unpack(self.fp.read(fmt.size)) def _check_crc(self, data, crc): """Check some data against a stored CRC. Note: For header CRCs, RAR calculates a CRC32 and then throws out the high-order bytes. @bug: This method of parsing is deprecated. @todo: I've only tested this out on 2-byte CRCs, not 4-byte file data CRCs. @todo: Isn't there some better way to do the check for CRC bitwidth? @bug: Figure out why I can't get a match on valid File Header CRCs. """ if isinstance(crc, int): if crc < 65536: crc = struct.pack('>H', crc) else: crc = struct.pack('>L', crc) return struct.pack('>L',zlib.crc32(data)).endswith(crc) def infolist(self): """Return a list of L{RarInfo} instances for the files in the archive.""" return self.filelist def namelist(self): """Return a list of filenames for the files in the archive.""" return [x.filename for x in self.filelist] def findRarHeader(handle, limit=FIND_LIMIT): """Searches a file-like object for a RAR header. @returns: The in-file offset of the first byte after the header block or C{None} if no RAR header was found. @warning: The given file-like object must support C{seek()} up to the size of C{limit}. @note: C{limit} is rounded up to the nearest multiple of L{CHUNK_SIZE}. @todo: Audit this to ensure it can't raise an exception L{is_rarfile()} won't catch. """ startPos, chunk = handle.tell(), "" limit = math.ceil(limit / float(CHUNK_SIZE)) * CHUNK_SIZE # Find the RAR header and line up for further reads. (Support SFX bundles) while True: temp = handle.read(CHUNK_SIZE) curr_pos = handle.tell() # If we hit the end of the file without finding a RAR marker block... if not temp or (limit > 0 and curr_pos > limit): handle.seek(startPos) return None chunk += temp marker_offset = chunk.find(MARKER_BLOCK) if marker_offset > -1: handle.seek(startPos) return curr_pos - len(chunk) + marker_offset + len(MARKER_BLOCK) # Obviously we haven't found the marker yet... chunk = chunk[len(temp):] # Use a rolling window to minimize memory consumption. def is_rarfile(filename, limit=FIND_LIMIT): """Convenience wrapper for L{findRarHeader} equivalent to C{is_zipfile}. Returns C{True} if C{filename} is a valid RAR file based on its magic number, otherwise returns C{False}. Optionally takes a limiting value for the maximum amount of data to sift through. Defaults to L{FIND_LIMIT} to set a sane bound on performance. Set it to 0 to perform an exhaustive search for a RAR header. @note: findRarHeader rounds this limit up to the nearest multiple of L{CHUNK_SIZE}. """ try: handle = file(filename, 'rb') return findRarHeader(handle, limit) is not None except IOError: pass return False if __name__ == '__main__': from optparse import OptionParser parser = OptionParser(description=__doc__.split('\n\n')[0], version="%%prog v%s" % __version__, usage="%prog <path> ...") opts, args = parser.parse_args() if args: RarFile.debug = 1 for fpath in args: print "File: %s" % fpath if is_rarfile(fpath): for line in RarFile(fpath).namelist(): print "\t%s" % line else: print "Not a RAR file"
41.77937
127
0.646183
1588a4c8fc8dec91174e5dd32a884294dd46addb
23,832
py
Python
tests/conftest.py
iMajna/nipyapi
5480af8fe8c6b470249837835cb1a067abb6678e
[ "Apache-2.0" ]
null
null
null
tests/conftest.py
iMajna/nipyapi
5480af8fe8c6b470249837835cb1a067abb6678e
[ "Apache-2.0" ]
1
2020-03-16T10:02:46.000Z
2020-03-16T13:37:42.000Z
tests/conftest.py
iMajna/nipyapi
5480af8fe8c6b470249837835cb1a067abb6678e
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """Configuration fixtures for pytest for `nipyapi` package.""" from __future__ import absolute_import import logging import pytest from os import environ, path from collections import namedtuple from time import sleep import nipyapi log = logging.getLogger(__name__) # Test Suite Controls test_default = True # Default to True for release test_security = False # Default to False for release test_regression = False # Default to False for release # Test Configuration parameters test_host = nipyapi.config.default_host test_basename = "nipyapi_test" test_pg_name = test_basename + "_ProcessGroup" test_another_pg_name = test_basename + "_AnotherProcessGroup" test_registry_client_name = test_basename + "_reg_client" test_processor_name = test_basename + "_proc" test_bucket_name = test_basename + "_bucket" test_versioned_flow_name = test_basename + "_ver_flow" test_cloned_ver_flow_name = test_basename + '_cloned_ver_flow' test_variable_registry_entry = [ (test_basename + '_name', test_basename + '_name' + '_value') ] test_write_file_path = test_basename + '_fs_write_dir' test_read_file_path = test_basename + '_fs_read_dir' test_write_file_name = test_basename + '_fs_write_file' test_ver_export_tmpdir = test_basename + '_ver_flow_dir' test_ver_export_filename = test_basename + "_ver_flow_export" test_parameter_context_name = test_basename + "_parameter_context" test_user_name = test_basename + '_user' test_user_group_name = test_basename + '_user_group' test_resource_dir = 'resources' # Test template filenames should match the template PG name test_templates = { 'basic': test_basename + 'Template_00', 'greedy': test_basename + 'Template_00_greedy', 'complex': test_basename + 'Template_01' } # Determining test environment # Can't use skiptest with parametrize for Travis # Mostly because loading up all the environments takes too long default_nifi_endpoints = ['http://' + test_host + ':8080/nifi-api'] regress_nifi_endpoints = [ 'http://' + test_host + ':10112/nifi-api', 'http://' + test_host + ':10120/nifi-api', 'http://' + test_host + ':10180/nifi-api', 'http://' + test_host + ':10192/nifi-api', ] secure_nifi_endpoints = ['https://' + test_host + ':8443/nifi-api'] default_registry_endpoints = [ ('http://' + test_host + ':18080/nifi-registry-api', 'http://registry:18080', 'http://' + test_host + ':8080/nifi-api' ) ] regress_registry_endpoints = [ ('http://' + test_host + ':18010/nifi-registry-api', 'http://registry-010:18010', 'http://' + test_host + ':8080/nifi-api' ), ('http://' + test_host + ':18030/nifi-registry-api', 'http://registry-030:18030', 'http://' + test_host + ':10192/nifi-api' ) ] secure_registry_endpoints = [ ('https://' + test_host + ':18443/nifi-registry-api', 'https://secure-registry:18443', 'https://' + test_host + ':8443/nifi-api' )] if "TRAVIS" in environ and environ["TRAVIS"] == "true": log.info("Running tests on TRAVIS, skipping regression suite") nifi_test_endpoints = default_nifi_endpoints registry_test_endpoints = default_registry_endpoints else: log.info("Running tests on NOT TRAVIS, enabling regression suite") # Note that these endpoints are assumed to be available # look in Nipyapi/test_env_config/docker_compose_full_test for # convenient Docker configs and port mappings. # NOTE: it is important that the latest version is the last in the list # So that after a parametrized test we leave the single tests against # The latest release without bulking the test suite ensuring they change # back each time. nifi_test_endpoints = [] registry_test_endpoints = [] if test_default: nifi_test_endpoints += default_nifi_endpoints registry_test_endpoints += default_registry_endpoints if test_regression: nifi_test_endpoints += regress_nifi_endpoints registry_test_endpoints += regress_registry_endpoints if test_security: nifi_test_endpoints += secure_nifi_endpoints registry_test_endpoints += secure_registry_endpoints # 'regress' generates tests against previous versions of NiFi or sub-projects. # If you are using regression, note that you have to create NiFi objects within # the Test itself. This is because the fixture is generated before the # PyTest parametrize call, making the order # new test_func > fixtures > parametrize > run_test_func > teardown > next def pytest_generate_tests(metafunc): log.info("Metafunc Fixturenames are %s", metafunc.fixturenames) if 'regress_nifi' in metafunc.fixturenames: log.info("NiFi Regression testing requested for ({0})." .format(metafunc.function.__name__)) metafunc.parametrize( argnames='regress_nifi', argvalues=nifi_test_endpoints, indirect=True ) elif 'regress_flow_reg' in metafunc.fixturenames: log.info("NiFi Flow Registry Regression testing requested for ({0})." .format(metafunc.function.__name__)) metafunc.parametrize( argnames='regress_flow_reg', argvalues=registry_test_endpoints, indirect=True ) # Note that it's important that the regress function is the first called if # you are stacking fixtures @pytest.fixture(scope="function") def regress_nifi(request): log.info("NiFi Regression test setup called against endpoint %s", request.param) nipyapi.utils.set_endpoint(request.param, True, True) def remove_test_registry_client(): _ = [nipyapi.versioning.delete_registry_client(li) for li in nipyapi.versioning.list_registry_clients().registries if test_registry_client_name in li.component.name ] def ensure_registry_client(uri): try: client = nipyapi.versioning.create_registry_client( name=test_registry_client_name + uri, uri=uri, description=uri ) except ValueError as e: if 'already exists with the name' in str(e): client = nipyapi.versioning.get_registry_client( identifier=test_registry_client_name + uri ) else: raise e if isinstance(client, nipyapi.nifi.RegistryClientEntity): return client else: raise ValueError("Could not create Registry Client") @pytest.fixture(scope="function") def regress_flow_reg(request): log.info("NiFi-Registry regression test called against endpoints %s", request.param) # Set Registry connection nipyapi.utils.set_endpoint(request.param[0], True, True) # Set paired NiFi connection nipyapi.utils.set_endpoint(request.param[2], True, True) # because pytest won't let you easily cascade parameters through fixtures # we set the docker URI in the config for retrieval later on nipyapi.config.registry_local_name = request.param[1] # Tests that the Docker test environment is available before running test suite @pytest.fixture(scope="session", autouse=True) def session_setup(request): log.info("Commencing test session setup") for url in nifi_test_endpoints + [x[0] for x in registry_test_endpoints]: log.debug("Now Checking URL [{0}]".format(url)) nipyapi.utils.set_endpoint(url, ssl=True, login=True) # ssl and login will only work if https is in the url, else will silently skip gui_url = url.replace('-api', '') if not nipyapi.utils.wait_to_complete( nipyapi.utils.is_endpoint_up, gui_url, nipyapi_delay=nipyapi.config.long_retry_delay, nipyapi_max_wait=nipyapi.config.long_max_wait): pytest.exit( "Expected Service endpoint ({0}) is not responding" .format(gui_url) ) # Test API client connection if 'nifi-api' in url: if not nipyapi.canvas.get_root_pg_id(): raise ValueError("No Response from NiFi test call") # that should've created a new API client connection api_host = nipyapi.config.nifi_config.api_client.host if api_host != url: raise ValueError("Client expected [{0}], but got [{1}] " "instead".format(url, api_host)) log.info("Tested NiFi client connection, got response from %s", url) if 'https://' in url: nipyapi.security.bootstrap_security_policies(service='nifi') cleanup_nifi() elif 'nifi-registry-api' in url: if nipyapi.registry.FlowsApi().get_available_flow_fields(): log.info("Tested NiFi-Registry client connection, got " "response from %s", url) if 'https://' in url: nipyapi.security.bootstrap_security_policies(service='registry') cleanup_reg() else: raise ValueError("No Response from NiFi-Registry test call" ) else: raise ValueError("Bad API Endpoint") request.addfinalizer(final_cleanup) log.info("Completing Test Session Setup") def remove_test_templates(): all_templates = nipyapi.templates.list_all_templates(native=False) if all_templates is not None: for this_template in all_templates: if test_basename in this_template.template.name: nipyapi.templates.delete_template(this_template.id) def remove_test_pgs(): _ = [ nipyapi.canvas.delete_process_group(x, True, True) for x in nipyapi.nifi.ProcessGroupsApi().get_process_groups('root').process_groups if test_basename in x.status.name ] def remove_test_processors(): _ = [ nipyapi.canvas.delete_processor(x, force=True) for x in nipyapi.canvas.list_all_processors() if test_basename in x.status.name ] def remove_test_funnels(): # Note that Funnels cannot be given labels so scoping is by PG only remove_test_connections() _ = [ nipyapi.canvas.delete_funnel(x) for x in nipyapi.canvas.list_all_funnels() ] def remove_test_parameter_contexts(): if nipyapi.utils.check_version('1.10.0') < 1: _ = [ nipyapi.parameters.delete_parameter_context(li) for li in nipyapi.parameters.list_all_parameter_contexts() if test_basename in li.component.name ] else: log.info("NiFi version is older than 1.10, skipping Parameter Context cleanup") def remove_test_buckets(): _ = [nipyapi.versioning.delete_registry_bucket(li) for li in nipyapi.versioning.list_registry_buckets() if test_bucket_name in li.name] def final_cleanup(): for url in nifi_test_endpoints + [x[0] for x in registry_test_endpoints]: nipyapi.utils.set_endpoint(url, True, True) if 'nifi-api' in url: cleanup_nifi() elif 'nifi-registry-api' in url: cleanup_reg() def remove_test_service_users(service='both'): nifi_test_users = [ x for x in nipyapi.security.list_service_users('nifi') if x.component.identity.startswith(test_basename) ] reg_test_users = [ x for x in nipyapi.security.list_service_users('registry') if x.identity.startswith(test_basename) ] if service != 'registry': _ = [ nipyapi.security.remove_service_user(x, 'nifi') for x in nifi_test_users ] if service != 'nifi': _ = [ nipyapi.security.remove_service_user(x, 'registry') for x in reg_test_users ] def remove_test_service_user_groups(service='both'): nifi_test_user_groups = [ x for x in nipyapi.security.list_service_user_groups('nifi') if x.component.identity.startswith(test_basename) ] reg_test_user_groups = [ x for x in nipyapi.security.list_service_user_groups('registry') if x.identity.startswith(test_basename) ] if service != 'registry': _ = [ nipyapi.security.remove_service_user_group(x, 'nifi') for x in nifi_test_user_groups ] if service != 'nifi': _ = [ nipyapi.security.remove_service_user_group(x, 'registry') for x in reg_test_user_groups ] def cleanup_nifi(): # Only bulk-cleanup universally compatible components # Ideally we would clean each test environment, but it's too slow to do it # per test, so we rely on individual fixture cleanup log.info("Bulk cleanup called on host %s", nipyapi.config.nifi_config.host) remove_test_templates() remove_test_pgs() remove_test_connections() remove_test_controllers() remove_test_processors() remove_test_ports() remove_test_funnels() remove_test_rpgs() remove_test_parameter_contexts() if test_security and 'https' in nipyapi.nifi.configuration.host: remove_test_service_user_groups('nifi') remove_test_service_users('nifi') def remove_test_rpgs(): _ = [ nipyapi.canvas.delete_remote_process_group(x) for x in nipyapi.canvas.list_all_remote_process_groups() ] def remove_test_connections(): # Funnels don't have a name, have to go by type _ = [ nipyapi.canvas.delete_connection(x, True) for x in nipyapi.canvas.list_all_connections() if x.destination_type == 'FUNNEL' or x.source_type == 'FUNNEL' or test_basename in x.component.name ] def remove_test_ports(): _ = [ nipyapi.canvas.delete_port(x) for x in nipyapi.canvas.list_all_by_kind('input_ports') if test_basename in x.component.name ] _ = [ nipyapi.canvas.delete_port(x) for x in nipyapi.canvas.list_all_by_kind('output_ports') if test_basename in x.component.name ] def remove_test_controllers(): _ = [nipyapi.canvas.delete_controller(li, True) for li in nipyapi.canvas.list_all_controllers() if test_basename in li.component.name] def cleanup_reg(): # Bulk cleanup for tests involving NiFi Registry remove_test_pgs() remove_test_buckets() remove_test_registry_client() if test_security and 'https' in nipyapi.registry.configuration.host: remove_test_service_user_groups('registry') remove_test_service_users('registry') @pytest.fixture(name='fix_templates', scope='function') def fixture_templates(request, fix_pg): log.info("Creating PyTest Fixture fix_templates on endpoint %s", nipyapi.config.nifi_config.host) FixtureTemplates = namedtuple( 'FixtureTemplates', ('pg', 'b_file', 'b_name', 'c_file', 'c_name', 'g_name', 'g_file') ) f_pg = fix_pg f_b_file = path.join( path.dirname(__file__), test_resource_dir, test_templates['basic'] + '.xml' ) f_b_name = 'nipyapi_testTemplate_00' f_c_file = path.join( path.dirname(__file__), test_resource_dir, test_templates['complex'] + '.xml' ) f_c_name = 'nipyapi_testTemplate_01' f_g_file = path.join( path.dirname(__file__), test_resource_dir, test_templates['greedy'] + '.xml' ) f_g_name = 'nipyapi_testTemplate_00_greedy' out = FixtureTemplates( pg=f_pg, b_name=f_b_name, c_name=f_c_name, g_name=f_g_name, b_file=f_b_file, g_file=f_g_file, c_file=f_c_file ) request.addfinalizer(remove_test_templates) log.info("- Returning PyTest Fixture fix_templates") return out @pytest.fixture(name='fix_pg') def fixture_pg(request): class Dummy: def __init__(self): pass def generate(self, parent_pg=None, suffix=''): if parent_pg is None: target_pg = nipyapi.canvas.get_process_group( nipyapi.canvas.get_root_pg_id(), 'id' ) else: target_pg = parent_pg return nipyapi.canvas.create_process_group( target_pg, test_pg_name + suffix, location=(400.0, 400.0) ) request.addfinalizer(remove_test_pgs) return Dummy() @pytest.fixture(name='fix_proc') def fixture_proc(request): class Dummy: def __init__(self): pass def generate(self, parent_pg=None, suffix='', kind=None, config=None): if parent_pg is None: target_pg = nipyapi.canvas.get_process_group( nipyapi.canvas.get_root_pg_id(), 'id' ) else: target_pg = parent_pg kind = kind if kind else 'GenerateFlowFile' return nipyapi.canvas.create_processor( parent_pg=target_pg, processor=nipyapi.canvas.get_processor_type( kind), location=(400.0, 400.0), name=test_processor_name + suffix, config=nipyapi.nifi.ProcessorConfigDTO( scheduling_period='1s', auto_terminated_relationships=['success'] ) ) request.addfinalizer(remove_test_processors) return Dummy() @pytest.fixture(name='fix_context') def fixture_context(request): class Dummy: def __init__(self): pass def generate(self, name=test_parameter_context_name): return nipyapi.parameters.create_parameter_context(name) request.addfinalizer(remove_test_parameter_contexts) return Dummy() @pytest.fixture(name='fix_funnel') def fixture_funnel(request): class Dummy: def __init__(self): pass def generate(self, parent_pg=None, position=(400, 400)): if parent_pg is None: target_pg = nipyapi.canvas.get_process_group( nipyapi.canvas.get_root_pg_id(), 'id' ) else: target_pg = parent_pg return nipyapi.canvas.create_funnel(target_pg.id, position) request.addfinalizer(remove_test_funnels) return Dummy() @pytest.fixture(name='fix_bucket', scope='function') def fixture_bucket(request): class Dummy: def __init__(self): pass def __call__(self, name=test_bucket_name, suffix=''): return nipyapi.versioning.create_registry_bucket( name + suffix ) request.addfinalizer(remove_test_buckets) return Dummy() @pytest.fixture(name='fix_ver_flow', scope='function') def fixture_ver_flow(request, fix_bucket, fix_pg, fix_proc): log.info("Starting setup of Fixture fix_ver_flow") FixtureVerFlow = namedtuple( 'FixtureVerFlow', ('client', 'bucket', 'pg', 'proc', 'info', 'flow', 'snapshot', 'dto') ) f_reg_client = ensure_registry_client(nipyapi.config.registry_local_name) f_pg = fix_pg.generate() f_bucket = fix_bucket() f_proc = fix_proc.generate(parent_pg=f_pg) f_info = nipyapi.versioning.save_flow_ver( process_group=f_pg, registry_client=f_reg_client, bucket=f_bucket, flow_name=test_versioned_flow_name, comment='NiPyApi Test', desc='NiPyApi Test' ) sleep(0.5) f_flow = nipyapi.versioning.get_flow_in_bucket( bucket_id=f_bucket.identifier, identifier=f_info.version_control_information.flow_id, identifier_type='id' ) f_snapshot = nipyapi.versioning.get_latest_flow_ver( f_bucket.identifier, f_flow.identifier ) f_dto = ('registry', 'VersionedFlowSnapshot') request.addfinalizer(cleanup_reg) log.info("Finished setting up Fixture fix_ver_flow") return FixtureVerFlow( client=f_reg_client, bucket=f_bucket, pg=f_pg, proc=f_proc, info=f_info, flow=f_flow, snapshot=f_snapshot, dto=f_dto ) @pytest.fixture(name='fix_flow_serde', scope='function') def fixture_flow_serde(request, tmpdir, fix_ver_flow): FixtureFlowSerde = namedtuple( 'FixtureFlowSerde', getattr(fix_ver_flow, '_fields') + ('filepath', 'json', 'yaml', 'raw') ) f_filepath = str(tmpdir.mkdir(test_ver_export_tmpdir) .join(test_ver_export_filename)) f_raw = nipyapi.versioning.get_flow_version( bucket_id=fix_ver_flow.bucket.identifier, flow_id=fix_ver_flow.flow.identifier, export=True ) f_json = nipyapi.versioning.export_flow_version( bucket_id=fix_ver_flow.bucket.identifier, flow_id=fix_ver_flow.flow.identifier, file_path=f_filepath + '.json', mode='json' ) f_yaml = nipyapi.versioning.export_flow_version( bucket_id=fix_ver_flow.bucket.identifier, flow_id=fix_ver_flow.flow.identifier, file_path=f_filepath + '.yaml', mode='yaml' ) request.addfinalizer(cleanup_reg) return FixtureFlowSerde( *fix_ver_flow, filepath=f_filepath, json=f_json, yaml=f_yaml, raw=f_raw ) @pytest.fixture(name='fix_cont', scope='function') def fixture_controller(request): class Dummy: def __init__(self): pass def __call__(self, parent_pg=None, kind=None): if parent_pg is None: target_pg = nipyapi.canvas.get_process_group( nipyapi.canvas.get_root_pg_id(), 'id' ) else: target_pg = parent_pg kind = kind if kind else 'DistributedMapCacheClientService' cont_type = [ x for x in nipyapi.canvas.list_all_controller_types() if kind in x.type ][0] c_1 = nipyapi.canvas.create_controller( parent_pg=target_pg, controller=cont_type ) c_2 = nipyapi.canvas.update_controller( c_1, nipyapi.nifi.ControllerServiceDTO( name=test_basename + c_1.component.name ) ) return c_2 request.addfinalizer(remove_test_controllers) return Dummy() @pytest.fixture(name='fix_users', scope='function') def fixture_users(request): class Dummy: def __init__(self): pass def __call__(self, name=test_user_name, suffix=''): return ( nipyapi.security.create_service_user(name + suffix), nipyapi.security.create_service_user(name + suffix, 'registry') ) request.addfinalizer(remove_test_service_users) return Dummy() @pytest.fixture(name='fix_user_groups', scope='function') def fixture_user_groups(request, fix_users): class Dummy: def __init__(self): pass def __call__(self, name=test_user_group_name, suffix=''): n_user, r_user = fix_users() return ( nipyapi.security.create_service_user_group( name + suffix, service='nifi', users=[n_user]), nipyapi.security.create_service_user_group( name + suffix, service='registry', users=[r_user]) ) request.addfinalizer(remove_test_service_user_groups) return Dummy()
34.489146
90
0.642707
a2883339c046d6caa326d2d2e642068f9d2e2994
1,081
py
Python
src/interface/main.py
NikolaTesla13/Hackerman-chat
8422a1ee45a08231c83572a8926ba571d3e29146
[ "MIT" ]
null
null
null
src/interface/main.py
NikolaTesla13/Hackerman-chat
8422a1ee45a08231c83572a8926ba571d3e29146
[ "MIT" ]
null
null
null
src/interface/main.py
NikolaTesla13/Hackerman-chat
8422a1ee45a08231c83572a8926ba571d3e29146
[ "MIT" ]
null
null
null
import sys import string import random import requests import pretty_errors args = [] other_token = "" my_token = "" status = None def generate_token(): token = "" for i in range(0, 20): token += random.choice(string.ascii_letters + string.digits) return token if __name__ == "__main__": args = sys.argv if len(args) == 2: other_token = args[1] my_token = generate_token() print("Your token is " + my_token) if other_token == "": print("Enter your friend's token: ", end="") other_token = input() if other_token != "": status = requests.get("http://127.0.0.1:5000/add/"+my_token+"/"+other_token) if status.status_code == 200: print("Connected sucsessfully!") else: status = requests.get("http://127.0.0.1:5000/check/"+my_token) if status.text != 404: other_token = status.text print("Connected sucsessfully! Your friend token is " + other_token) else: print("Error finding friend!") sys.exit(-1)
24.022222
84
0.592044
033ed341967cbdcafb87f52cee71b1b9bc88a026
497
py
Python
env/lib/python3.8/site-packages/plotly/validators/scattergl/_xaxis.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/scattergl/_xaxis.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/scattergl/_xaxis.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 XaxisValidator(_plotly_utils.basevalidators.SubplotidValidator): def __init__(self, plotly_name="xaxis", parent_name="scattergl", **kwargs): super(XaxisValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, dflt=kwargs.pop("dflt", "x"), edit_type=kwargs.pop("edit_type", "calc+clearAxisTypes"), role=kwargs.pop("role", "info"), **kwargs )
35.5
79
0.641851
d8cfee4089c96d7f7a68007b0367260a4f424572
4,016
py
Python
Assets/PrefixAllAssets.py
ChinaArvin/UnrealEditorPythonScripts
3bed2f3e1cf7f0ce93eac13726a18b3094e63145
[ "MIT" ]
414
2019-01-23T10:54:47.000Z
2022-03-31T02:58:18.000Z
Assets/PrefixAllAssets.py
ChinaArvin/UnrealEditorPythonScripts
3bed2f3e1cf7f0ce93eac13726a18b3094e63145
[ "MIT" ]
3
2019-08-29T21:42:21.000Z
2022-01-04T04:05:02.000Z
Assets/PrefixAllAssets.py
ColaTAL/UnrealEditorPythonScripts
b4478befb4764cae95ddc09bb7c6b3a23155e987
[ "MIT" ]
161
2019-01-21T08:55:44.000Z
2022-03-31T02:58:22.000Z
# _ # (_) # _ __ ___ __ _ _ __ ___ ___ _ __ _ ___ _ __ ___ # | '_ ` _ \ / _` | '_ ` _ \ / _ \| '_ \| |/ _ \ '_ ` _ \ # | | | | | | (_| | | | | | | (_) | | | | | __/ | | | | | # |_| |_| |_|\__,_|_| |_| |_|\___/|_| |_|_|\___|_| |_| |_| # www.mamoniem.com # www.ue4u.xyz #Copyright 2021 Muhammad A.Moniem (@_mamoniem). All Rights Reserved. # import unreal #You can set the prefix of your choice here prefixAnimationBlueprint = "animBP" prefixAnimationSequence = "anim" prefixAnimation = "anim" prefixBlendSpace = "animBlnd" prefixBlueprint = "bp" prefixCurveFloat = "crvF" prefixCurveLinearColor = "crvL" prefixLevel = "lvl" prefixMaterial = "mat" prefixMaterialFunction = "mat_func" prefixMaterialInstance = "mat_inst" prefixParticleSystem = "fx" prefixPhysicsAsset = "phsx" prefixSkeletalMesh = "sk" prefixSkeleton = "skln" prefixSoundCue = "cue" prefixSoundWave = "wv" prefixStaticMesh = "sm" prefixTexture2D = "tex" prefixTextureCube = "HDRI" workingPath = "/Game/" @unreal.uclass() class GetEditorAssetLibrary(unreal.EditorAssetLibrary): pass def GetProperPrefix(className): _prefix = "" if className == "AnimBlueprint": _prefix = prefixAnimationBlueprint elif className == "AnimSequence": _prefix = prefixAnimationSequence elif className == "Animation": _prefix = prefixAnimation elif className == "BlendSpace1D": _prefix = prefixBlendSpace elif className == "Blueprint": _prefix = prefixBlueprint elif className == "CurveFloat": _prefix = prefixCurveFloat elif className == "CurveLinearColor": _prefix = prefixCurveLinearColor elif className == "Material": _prefix = prefixMaterial elif className == "MaterialFunction": _prefix = prefixMaterialFunction elif className == "MaterialInstance": _prefix = prefixMaterialInstance elif className == "ParticleSystem": _prefix = prefixParticleSystem elif className == "PhysicsAsset": _prefix = prefixPhysicsAsset elif className == "SkeletalMesh": _prefix = prefixSkeletalMesh elif className == "Skeleton": _prefix = prefixSkeleton elif className == "SoundCue": _prefix = prefixSoundCue elif className == "SoundWave": _prefix = prefixSoundWave elif className == "StaticMesh": _prefix = prefixStaticMesh elif className == "Texture2D": _prefix = prefixTexture2D elif className == "TextureCube": _prefix = prefixTextureCube else: _prefix = "" return _prefix editorAssetLib = GetEditorAssetLibrary() allAssets = editorAssetLib.list_assets(workingPath, True, False) allAssetsCount = len(allAssets) selectedAssetPath = workingPath with unreal.ScopedSlowTask(allAssetsCount, selectedAssetPath) as slowTask: slowTask.make_dialog(True) for asset in allAssets: _assetData = editorAssetLib.find_asset_data(asset) _assetName = _assetData.get_asset().get_name() _assetPathName = _assetData.get_asset().get_path_name() _assetPathOnly = _assetPathName.replace((_assetName + "." + _assetName), "") _assetClassName = _assetData.get_asset().get_class().get_name() _assetPrefix = GetProperPrefix(_assetClassName) if _assetPrefix in _assetName: continue elif _assetPrefix == "": continue else: _targetPathName = _assetPathOnly + ("%s%s%s%s%s%s%s" % (_assetPrefix, "_", _assetName, ".", _assetPrefix, "_", _assetName)) editorAssetLib.rename_asset(_assetPathName, _targetPathName) print (">>> Renaming [%s] to [%s]" % (_assetPathName, _targetPathName)) if slowTask.should_cancel(): break slowTask.enter_progress_frame(1, asset)
34.033898
135
0.626992
9c6bc99833193bf2b0aa8290d9c5cda0ff3c26d3
274
py
Python
modules/mod_reload.py
crdx/face
d2980e3ab47934ab7c8097c37f18abad6a96aa06
[ "MIT" ]
null
null
null
modules/mod_reload.py
crdx/face
d2980e3ab47934ab7c8097c37f18abad6a96aa06
[ "MIT" ]
null
null
null
modules/mod_reload.py
crdx/face
d2980e3ab47934ab7c8097c37f18abad6a96aa06
[ "MIT" ]
null
null
null
name = "Module reloader" desc = "Reloads modules" def on_pubmsg(p): words = p.event.arguments[0].split() if words[0] == "!r": p.connection.privmsg(p.event.target, "Rehashing") p.face.reload() # we've handled this event return True
21.076923
57
0.59854
a6e8d7ce89f10d0b16487484edb33a34f47a26da
3,215
py
Python
auth0/v3/management/rules.py
mdornseif/auth0-python
e87afb3754a1a10fef2c9197df1e3a7681c9eb61
[ "MIT" ]
null
null
null
auth0/v3/management/rules.py
mdornseif/auth0-python
e87afb3754a1a10fef2c9197df1e3a7681c9eb61
[ "MIT" ]
null
null
null
auth0/v3/management/rules.py
mdornseif/auth0-python
e87afb3754a1a10fef2c9197df1e3a7681c9eb61
[ "MIT" ]
null
null
null
from .rest import RestClient class Rules(object): """Rules endpoint implementation. Args: domain (str): Your Auth0 domain, e.g: 'username.auth0.com' token (str): Management API v2 Token telemetry (bool, optional): Enable or disable Telemetry (defaults to True) """ def __init__(self, domain, token, telemetry=True): self.domain = domain self.client = RestClient(jwt=token, telemetry=telemetry) def _url(self, id=None): url = 'https://%s/api/v2/rules' % self.domain if id is not None: return url + '/' + id return url def all(self, stage='login_success', enabled=True, fields=[], include_fields=True): """Retrieves a list of all rules. Args: enabled (bool, optional): If provided, retrieves rules that match the value, otherwise all rules are retrieved. fields (list, optional): A list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve all fields. include_fields (bool, optional): True if the fields specified are to be included in the result, False otherwise (defaults to true). stage (str, optional): Retrieves rules that match the execution stage (defaults to login_success). """ params = {'fields': ','.join(fields) or None, 'include_fields': str(include_fields).lower(), 'stage': stage} if enabled != None: params['enabled'] = str(enabled).lower() return self.client.get(self._url(), params=params) def create(self, body): """Creates a new rule. Args: body (dict): Attributes for the newly created rule, please see: https://auth0.com/docs/api/v2#!/Rules/post_rules """ return self.client.post(self._url(), data=body) def get(self, id, fields=[], include_fields=True): """Retrieves a rule by its ID. Args: id (str): The id of the rule to retrieve. fields (list, optional): A list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve all fields. include_fields (bool, optional): True if the fields specified are to be included in the result, False otherwise (defaults to true). """ params = {'fields': ','.join(fields) or None, 'include_fields': str(include_fields).lower()} return self.client.get(self._url(id), params=params) def delete(self, id): """Delete a rule. Args: id (str): The id of the rule to delete. """ return self.client.delete(self._url(id)) def update(self, id, body): """Update an existing rule Args: id (str): The id of the rule to modify. body (dict): Please see: https://auth0.com/docs/api/v2#!/Rules/patch_rules_by_id """ return self.client.patch(self._url(id), data=body)
32.15
92
0.570762
a96d98149365a6eeece426ca15a19325bddcf684
5,035
py
Python
Packages/matplotlib-2.2.2/lib/mpl_examples/lines_bars_and_markers/psd_demo.py
NightKirie/NCKU_NLP_2108_industry3
23ac13644b140587e23cfeffb114c7c6f46f17a2
[ "MIT" ]
1
2018-06-11T07:36:04.000Z
2018-06-11T07:36:04.000Z
Packages/matplotlib-2.2.2/lib/mpl_examples/lines_bars_and_markers/psd_demo.py
NightKirie/NCKU_NLP_2108_industry3
23ac13644b140587e23cfeffb114c7c6f46f17a2
[ "MIT" ]
null
null
null
Packages/matplotlib-2.2.2/lib/mpl_examples/lines_bars_and_markers/psd_demo.py
NightKirie/NCKU_NLP_2108_industry3
23ac13644b140587e23cfeffb114c7c6f46f17a2
[ "MIT" ]
4
2018-05-19T11:31:20.000Z
2018-07-01T20:58:29.000Z
""" ======== Psd Demo ======== Plotting Power Spectral Density (PSD) in Matplotlib. The PSD is a common plot in the field of signal processing. NumPy has many useful libraries for computing a PSD. Below we demo a few examples of how this can be accomplished and visualized with Matplotlib. """ import matplotlib.pyplot as plt import numpy as np import matplotlib.mlab as mlab # Fixing random state for reproducibility np.random.seed(19680801) dt = 0.01 t = np.arange(0, 10, dt) nse = np.random.randn(len(t)) r = np.exp(-t / 0.05) cnse = np.convolve(nse, r) * dt cnse = cnse[:len(t)] s = 0.1 * np.sin(2 * np.pi * t) + cnse plt.subplot(211) plt.plot(t, s) plt.subplot(212) plt.psd(s, 512, 1 / dt) plt.show() ############################################################################### # Compare this with the equivalent Matlab code to accomplish the same thing:: # # dt = 0.01; # t = [0:dt:10]; # nse = randn(size(t)); # r = exp(-t/0.05); # cnse = conv(nse, r)*dt; # cnse = cnse(1:length(t)); # s = 0.1*sin(2*pi*t) + cnse; # # subplot(211) # plot(t,s) # subplot(212) # psd(s, 512, 1/dt) # # Below we'll show a slightly more complex example that demonstrates # how padding affects the resulting PSD. dt = np.pi / 100. fs = 1. / dt t = np.arange(0, 8, dt) y = 10. * np.sin(2 * np.pi * 4 * t) + 5. * np.sin(2 * np.pi * 4.25 * t) y = y + np.random.randn(*t.shape) # Plot the raw time series fig = plt.figure() fig.subplots_adjust(hspace=0.45, wspace=0.3) ax = fig.add_subplot(2, 1, 1) ax.plot(t, y) # Plot the PSD with different amounts of zero padding. This uses the entire # time series at once ax2 = fig.add_subplot(2, 3, 4) ax2.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs) ax2.psd(y, NFFT=len(t), pad_to=len(t) * 2, Fs=fs) ax2.psd(y, NFFT=len(t), pad_to=len(t) * 4, Fs=fs) plt.title('zero padding') # Plot the PSD with different block sizes, Zero pad to the length of the # original data sequence. ax3 = fig.add_subplot(2, 3, 5, sharex=ax2, sharey=ax2) ax3.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs) ax3.psd(y, NFFT=len(t) // 2, pad_to=len(t), Fs=fs) ax3.psd(y, NFFT=len(t) // 4, pad_to=len(t), Fs=fs) ax3.set_ylabel('') plt.title('block size') # Plot the PSD with different amounts of overlap between blocks ax4 = fig.add_subplot(2, 3, 6, sharex=ax2, sharey=ax2) ax4.psd(y, NFFT=len(t) // 2, pad_to=len(t), noverlap=0, Fs=fs) ax4.psd(y, NFFT=len(t) // 2, pad_to=len(t), noverlap=int(0.05 * len(t) / 2.), Fs=fs) ax4.psd(y, NFFT=len(t) // 2, pad_to=len(t), noverlap=int(0.2 * len(t) / 2.), Fs=fs) ax4.set_ylabel('') plt.title('overlap') plt.show() ############################################################################### # This is a ported version of a MATLAB example from the signal # processing toolbox that showed some difference at one time between # Matplotlib's and MATLAB's scaling of the PSD. fs = 1000 t = np.linspace(0, 0.3, 301) A = np.array([2, 8]).reshape(-1, 1) f = np.array([150, 140]).reshape(-1, 1) xn = (A * np.sin(2 * np.pi * f * t)).sum(axis=0) xn += 5 * np.random.randn(*t.shape) fig, (ax0, ax1) = plt.subplots(ncols=2) fig.subplots_adjust(hspace=0.45, wspace=0.3) yticks = np.arange(-50, 30, 10) yrange = (yticks[0], yticks[-1]) xticks = np.arange(0, 550, 100) ax0.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024, scale_by_freq=True) ax0.set_title('Periodogram') ax0.set_yticks(yticks) ax0.set_xticks(xticks) ax0.grid(True) ax0.set_ylim(yrange) ax1.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, pad_to=512, noverlap=75, scale_by_freq=True) ax1.set_title('Welch') ax1.set_xticks(xticks) ax1.set_yticks(yticks) ax1.set_ylabel('') # overwrite the y-label added by `psd` ax1.grid(True) ax1.set_ylim(yrange) plt.show() ############################################################################### # This is a ported version of a MATLAB example from the signal # processing toolbox that showed some difference at one time between # Matplotlib's and MATLAB's scaling of the PSD. # # It uses a complex signal so we can see that complex PSD's work properly. prng = np.random.RandomState(19680801) # to ensure reproducibility fs = 1000 t = np.linspace(0, 0.3, 301) A = np.array([2, 8]).reshape(-1, 1) f = np.array([150, 140]).reshape(-1, 1) xn = (A * np.exp(2j * np.pi * f * t)).sum(axis=0) + 5 * prng.randn(*t.shape) fig, (ax0, ax1) = plt.subplots(ncols=2) fig.subplots_adjust(hspace=0.45, wspace=0.3) yticks = np.arange(-50, 30, 10) yrange = (yticks[0], yticks[-1]) xticks = np.arange(-500, 550, 200) ax0.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024, scale_by_freq=True) ax0.set_title('Periodogram') ax0.set_yticks(yticks) ax0.set_xticks(xticks) ax0.grid(True) ax0.set_ylim(yrange) ax1.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, pad_to=512, noverlap=75, scale_by_freq=True) ax1.set_title('Welch') ax1.set_xticks(xticks) ax1.set_yticks(yticks) ax1.set_ylabel('') # overwrite the y-label added by `psd` ax1.grid(True) ax1.set_ylim(yrange) plt.show()
28.771429
79
0.636941
15c505a74a81a49bff17b4a0ef55b4fd5b09973e
17,485
py
Python
pines/gpr/__init__.py
jpn--/pine
3980a9f0b09dd36b2fed7e52750847637be5f067
[ "MIT" ]
2
2017-08-09T02:42:37.000Z
2020-06-16T14:14:16.000Z
pines/gpr/__init__.py
jpn--/pine
3980a9f0b09dd36b2fed7e52750847637be5f067
[ "MIT" ]
null
null
null
pines/gpr/__init__.py
jpn--/pine
3980a9f0b09dd36b2fed7e52750847637be5f067
[ "MIT" ]
null
null
null
from sklearn.linear_model import LinearRegression as _sklearn_LinearRegression from sklearn.gaussian_process import GaussianProcessRegressor from sklearn import preprocessing from sklearn.base import TransformerMixin from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C, RationalQuadratic as RQ from sklearn.base import RegressorMixin, BaseEstimator from sklearn.model_selection import cross_val_score, cross_val_predict from sklearn.preprocessing import StandardScaler from sklearn.metrics import r2_score from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_regression, mutual_info_regression from sklearn.exceptions import DataConversionWarning import numpy, pandas import scipy.stats import warnings import contextlib from pines.attribute_dict import dicta def feature_concat(*args): if all(isinstance(a, pandas.DataFrame) for a in args): return pandas.concat(args, axis=1) if any(isinstance(a, pandas.DataFrame) for a in args): ref = 0 while not isinstance(args[ref], pandas.DataFrame): ref += 1 ix = args[ref].index return pandas.concat([pandas.DataFrame(a, index=ix) for a in args], axis=1) return numpy.concatenate(args, axis=1) class LinearRegression(_sklearn_LinearRegression): def fit(self, X, y, sample_weight=None): # print(" LR FIT on",len(X)) super().fit(X, y, sample_weight=sample_weight) if isinstance(X, pandas.DataFrame): self.names_ = X.columns.copy() sse = numpy.sum((self.predict(X) - y) ** 2, axis=0) / float(X.shape[0] - X.shape[1]) if sse.shape == (): sse = sse.reshape(1,) inv_X_XT = numpy.linalg.inv(numpy.dot(X.T, X)) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) try: se = numpy.array([ numpy.sqrt(numpy.diagonal(sse[i] * inv_X_XT)) for i in range(sse.shape[0]) ]) except: print("sse.shape",sse.shape) print(sse) raise self.t_ = self.coef_ / se self.p_ = 2 * (1 - scipy.stats.t.cdf(numpy.abs(self.t_), y.shape[0] - X.shape[1])) # try: # print(y.values[0]) # except AttributeError: # print(y[0]) return self def predict(self, X): # print(" "*55,"LR PREDICT on", len(X)) return super().predict(X) class GaussianProcessRegressor_(GaussianProcessRegressor): def fit(self, X, y): # print(" GPR FIT on",len(X)) q = super().fit(X,y) # try: # print(y.values[0]) # except AttributeError: # print(y[0]) return q def predict(self, X, return_std=False, return_cov=False): #print(" "*55,"GPR PREDICT on", len(X)) return super().predict(X, return_std=return_std, return_cov=return_cov) def _make_as_vector(y): # if isinstance(y, (pandas.DataFrame, pandas.Series)): # y = y.values.ravel() return y @contextlib.contextmanager def ignore_warnings(category=Warning): with warnings.catch_warnings(): warnings.simplefilter("ignore", category=category) yield class LinearAndGaussianProcessRegression( BaseEstimator, RegressorMixin, ): def __init__(self, core_features=None, keep_other_features=3, use_linear=True): """ Parameters ---------- core_features feature columns to definitely keep for both LR and GPR """ self.core_features = core_features self.keep_other_features = keep_other_features self.lr = LinearRegression() self.gpr = GaussianProcessRegressor_(n_restarts_optimizer=9) self.y_residual = None self.kernel_generator = lambda dims: C() * RBF([1.0] * dims) self.use_linear = use_linear def _feature_selection(self, X, y=None): """ Parameters ---------- X : pandas.DataFrame y : ndarray If given, the SelectKBest feature selector will be re-fit to find the best features. If not given, then the previously fit SelectKBest will be used; if it has never been fit, an error is raised. Returns ------- pandas.DataFrame Contains all the core features plus the K best other features. """ if not isinstance(X, pandas.DataFrame): raise TypeError('must use pandas.DataFrame for X') if self.core_features is None: return X y = _make_as_vector(y) X_core = X.loc[:,self.core_features] X_other = X.loc[:, X.columns.difference(self.core_features)] if X_other.shape[1] <= self.keep_other_features: return X # If self.keep_other_features is zero, there is no feature selecting to do and we return only the core. if self.keep_other_features == 0: return X_core if y is not None: self.feature_selector = SelectKBest(mutual_info_regression, k=self.keep_other_features).fit(X_other, y) try: X_other = pandas.DataFrame( self.feature_selector.transform(X_other), columns=X_other.columns[self.feature_selector.get_support()], index=X_other.index, ) except: print("X_other.info") print(X_other.info(1)) print("X_other") print(X_other) raise try: return pandas.concat([X_core, X_other], axis=1) except: print("X_core") print(X_core) print("X_other") print(X_other) print(X_core.info()) print(X_other.info()) raise def fit(self, X, y): """ Fit linear and gaussian model. Parameters ---------- X : numpy array or sparse matrix of shape [n_samples, n_features] Training data y : numpy array of shape [n_samples, n_targets] Target values. Returns ------- self : returns an instance of self. """ # print("META FIT on",len(X)) # if not isinstance(X, pandas.DataFrame): # # X = pandas.DataFrame(X) # raise TypeError('must use pandas.DataFrame for X') # # if self.core_features is None: # X_core = X # X_other = X.loc[:,[]] # else: # X_core = X.loc[:,self.core_features] # X_other = X.loc[:, X.columns.difference(self.core_features)] # # self.feature_selector = SelectKBest(mutual_info_regression, k=self.keep_other_features).fit(X_other, y) # # X_other = self.feature_selector.transform(X_other) with ignore_warnings(DataConversionWarning): if isinstance(y, pandas.DataFrame): self.Y_columns = y.columns elif isinstance(y, pandas.Series): self.Y_columns = [y.name] else: self.Y_columns = None y = _make_as_vector(y) X_core_plus = self._feature_selection(X, y) if self.use_linear: try: self.lr.fit(X_core_plus, y) except: print("X_core_plus.shape",X_core_plus.shape) print("y.shape",y.shape) print(X_core_plus) print(y) raise self.y_residual = y - self.lr.predict(X_core_plus) else: self.y_residual = y dims = X_core_plus.shape[1] self.gpr.kernel = self.kernel_generator(dims) self.gpr.fit(X_core_plus, self.y_residual) # print(self.y_residual.values[0]) return self def predict(self, X, return_std=False, return_cov=False): """Predict using the model Parameters ---------- X : {array-like, sparse matrix}, shape = (n_samples, n_features) Samples. Returns ------- C : array, shape = (n_samples,) Returns predicted values. """ if not isinstance(X, pandas.DataFrame): raise TypeError('must use pandas.DataFrame for X') X_core_plus = self._feature_selection(X) if self.use_linear: y_hat_lr = self.lr.predict(X=X_core_plus) else: y_hat_lr = 0 if return_std: y_hat_gpr, y_hat_std = self.gpr.predict(X_core_plus, return_std=True) if self.Y_columns is not None: y_result = pandas.DataFrame( y_hat_lr + y_hat_gpr, columns=self.Y_columns, index=X.index, ) else: y_result = y_hat_lr + y_hat_gpr return y_result, y_hat_std else: y_hat_gpr = self.gpr.predict(X_core_plus) if self.Y_columns is not None: y_result = pandas.DataFrame( y_hat_lr + y_hat_gpr, columns=self.Y_columns, index=X.index, ) else: y_result = y_hat_lr + y_hat_gpr return y_result def cross_val_scores(self, X, Y, cv=3): p = self.cross_val_predict(X, Y, cv=cv) return pandas.Series( r2_score(Y, p, sample_weight=None, multioutput='raw_values'), index=Y.columns ) # # def cross_val_scores(self, X, y, cv=3): # with ignore_warnings(DataConversionWarning): # y = _make_as_vector(y) # X_core_plus = self._feature_selection(X, y) # total = cross_val_score(self, X_core_plus, y, cv=cv) # return total def cross_val_scores_full(self, X, y, cv=3, alt_y=None): with ignore_warnings(DataConversionWarning): y = _make_as_vector(y) X_core_plus = self._feature_selection(X, y) total = cross_val_score(self, X_core_plus, y, cv=cv) if self.use_linear: linear_cv_score = cross_val_score(self.lr, X_core_plus, y, cv=cv) linear_cv_predict = cross_val_predict(self.lr, X_core_plus, y, cv=cv) linear_cv_residual = y-linear_cv_predict gpr_cv_score = cross_val_score(self.gpr, X_core_plus, linear_cv_residual, cv=cv) self.lr.fit(X_core_plus, y) y_residual = y - self.lr.predict(X_core_plus) gpr_cv_score2 = cross_val_score(self.gpr, X_core_plus, y_residual, cv=cv) result = dicta( total=total, linear=linear_cv_score, net_gpr=total-linear_cv_score, gpr=gpr_cv_score, gpr2=gpr_cv_score2, ) else: result = dicta( total=total, ) if alt_y is not None: result['gpr_alt'] = cross_val_score(self.gpr, X, alt_y, cv=cv) # print() # print(numpy.concatenate([y_residual, alt_y, y_residual-alt_y], axis=1 )) # print() # print(result['gpr_alt']) # print(result['gpr2']) # print() return result def cross_val_predict(self, X, y, cv=3): with ignore_warnings(DataConversionWarning): X_core_plus = self._feature_selection(X, y) if isinstance(y, pandas.DataFrame): y_columns = y.columns elif isinstance(y, pandas.Series): y_columns = [y.name] else: y_columns = ['Unnamed'] total = cross_val_predict(self, X_core_plus, y, cv=cv) return pandas.DataFrame( total, index=y.index, columns=y_columns, ) def cross_val_predicts(self, X, y, cv=3): with ignore_warnings(DataConversionWarning): y = _make_as_vector(y) X_core_plus = self._feature_selection(X, y) total = cross_val_predict(self, X_core_plus, y, cv=cv) if self.use_linear: linear_cv_predict = cross_val_predict(self.lr, X_core_plus, y, cv=cv) linear_cv_residual = y-linear_cv_predict gpr_cv_predict_over_cv_linear = cross_val_predict(self.gpr, X_core_plus, linear_cv_residual, cv=cv) self.lr.fit(X_core_plus, y) linear_full_predict = self.lr.predict(X_core_plus) y_residual = y - linear_full_predict gpr_cv_predict_over_full_linear = cross_val_predict(self.gpr, X_core_plus, y_residual, cv=cv) return dicta( total=total, linear=linear_cv_predict, net_gpr=total-linear_cv_predict, gpr=gpr_cv_predict_over_cv_linear+linear_cv_predict, gpr2=gpr_cv_predict_over_full_linear+linear_full_predict, ) else: return dicta( total=total, ) def cross_val_scores(pipe, X, y, cv=3): # For pipelines y = _make_as_vector(y) self = pipe.steps[-1][1] total = cross_val_score(self, X, y, cv=cv) linear_cv_score = cross_val_score(self.lr, X, y, cv=cv) linear_cv_predict = cross_val_predict(self.lr, X, y, cv=cv) linear_cv_residual = y-linear_cv_predict gpr_cv_score = cross_val_score(self.gpr, X, linear_cv_residual, cv=cv) self.lr.fit(X, y) y_residual = y - self.lr.predict(X) gpr_cv_score2 = cross_val_score(self.gpr, X, y_residual, cv=cv) return dicta( total=total, linear=linear_cv_score, net_gpr=total-linear_cv_score, gpr=gpr_cv_score, gpr2=gpr_cv_score2, ) class PartialStandardScaler(StandardScaler): def __init__(self, copy=True, with_mean=True, with_std=True, omit=()): super().__init__(copy=copy, with_mean=with_mean, with_std=with_std) self._omit = omit self._names = None def fit(self, X, y=None): result = super().fit(X, y) omit = [i for i in self._omit] if isinstance(X, pandas.DataFrame): self._names = X.columns.copy() for n,k in enumerate(omit): if isinstance(k, str): omit[n] = X.columns.get_loc(k) for k in omit: if self.with_mean: self.mean_[k] = 0 if self.with_std: self.scale_[k] = 1 return result def transform(self, X, y='deprecated', copy=None): result = super().transform(X, y, copy) if isinstance(X, pandas.DataFrame): return pandas.DataFrame( data=result, index=X.index, columns=[(f'{i}†' if i not in self._omit else i) for i in X.columns] ) return result def inverse_transform_by_name(self, X, name): ix = self._names.get_loc(name) if self.with_std: X *= self.scale_[ix] if self.with_mean: X += self.mean_[ix] return X def transform_by_name(self, X, name): ix = self._names.get_loc(name) if self.with_mean: X -= self.mean_[ix] if self.with_std: X /= self.scale_[ix] return X class Log1pStandardScaler(StandardScaler): def __init__(self, copy=True, with_mean=True, with_std=True): super().__init__(copy=copy, with_mean=with_mean, with_std=with_std) def fit(self, X, y=None): return super().fit(numpy.log1p(X), y) def transform(self, X, y='deprecated', copy=None): result = super().transform(numpy.log1p(X), y, copy) if isinstance(X, pandas.DataFrame): return pandas.DataFrame( data=result, index=X.index, columns=[f'{i}†' for i in X.columns] ) return result def inverse_transform(self, X, copy=None): result = super().inverse_transform(X) result = numpy.expm1(result) if isinstance(X, pandas.DataFrame): return pandas.DataFrame( data=result, index=X.index, columns=[i.rstrip('†') for i in X.columns] ) return result class ExponentialFeatures(BaseEstimator, TransformerMixin): def __init__(self): pass def fit(self, X, y=None): """ Compute number of output features. Parameters ---------- X : array-like, shape (n_samples, n_features) The data. Returns ------- self : instance """ return self def transform(self, X): """Transform data to add exponential features Parameters ---------- X : array-like, shape [n_samples, n_features] The data to transform, row by row. Returns ------- XP : np.ndarray shape [n_samples, NP] The matrix of features, where NP is the number of polynomial features generated from the combination of inputs. """ from sklearn.utils import check_array from sklearn.utils.validation import check_is_fitted, check_random_state, FLOAT_DTYPES from scipy.stats.stats import pearsonr X = check_array(X, dtype=FLOAT_DTYPES) n_samples, n_features = X.shape # allocate output data XP = numpy.empty((n_samples, n_features*2), dtype=X.dtype) XP_use = numpy.ones((n_features*2,), dtype=bool) for i in range(n_features): XP[:, i] = X[:, i] exp_x = numpy.exp(X[:, i]) correlation = pearsonr(X[:, i], exp_x)[0] # print("correlation is",correlation) if numpy.fabs(correlation) < 0.99: XP[:, i+n_features] = exp_x else: XP_use[i+n_features] = 0 if isinstance(X, pandas.DataFrame): result = pandas.DataFrame( data=XP, columns=list(X.columns) + [f'exp({c})' for c in X.columns], index=X.index, ) return result.iloc[:, XP_use] return XP[:,XP_use] class InteractionFeatures(BaseEstimator, TransformerMixin): def __init__(self, interaction_point): self._interaction_name = interaction_point def fit(self, X, y=None): """ Compute number of output features. Parameters ---------- X : array-like, shape (n_samples, n_features) The data. Returns ------- self : instance """ return self def transform(self, X): """Transform data to add exponential features Parameters ---------- X : array-like, shape [n_samples, n_features] The data to transform, row by row. Returns ------- XP : np.ndarray shape [n_samples, NP] The matrix of features, where NP is the number of polynomial features generated from the combination of inputs. """ from sklearn.utils import check_array from sklearn.utils.validation import check_is_fitted, check_random_state, FLOAT_DTYPES from scipy.stats.stats import pearsonr interact_point = None if isinstance(self._interaction_name, int): interact_point = self._interaction_name else: if isinstance(X, pandas.DataFrame): interact_point = X.columns.get_loc(self._interaction_name) else: raise TypeError("X must be DataFrame when interaction_name is string") if interact_point is None: raise TypeError('interact_point is None') Xa = check_array(X, dtype=FLOAT_DTYPES) n_samples, n_features = Xa.shape # allocate output data XP = numpy.empty((n_samples, n_features*2), dtype=Xa.dtype) XP_use = numpy.ones((n_features*2,), dtype=bool) XP_fresh = numpy.zeros((n_features*2,), dtype=bool) for i in range(n_features): XP[:, i] = Xa[:, i] exp_x = Xa[:, i] * Xa[:, interact_point] #correlation = pearsonr(Xa[:, i], exp_x)[0] correlation1 = numpy.corrcoef(Xa, exp_x, rowvar=False)[-1, :-1] if XP_fresh.sum(): correlation2 = numpy.corrcoef(XP[:,XP_fresh], exp_x, rowvar=False)[-1, :-1] else: correlation2 = [0] correlation = max( numpy.fabs(correlation1).max(), numpy.fabs(correlation2).max()) if numpy.fabs(correlation) < 0.99: XP[:, i+n_features] = exp_x XP_fresh[i+n_features] = True else: XP_use[i+n_features] = 0 if isinstance(X, pandas.DataFrame): result = pandas.DataFrame( data=XP, columns=list(X.columns) + [f'{c} ~ {self._interaction_name}' for c in X.columns], index=X.index, ) return result.iloc[:, XP_use] return XP[:,XP_use]
25.903704
107
0.693795
8ee309537169151d1fc3e6f22eae7b5685388650
2,690
py
Python
src/cryptojwt/jws/utils.py
openid/JWTConnect-Python-CryptoJWT
ec79b98f62f033afc596a4be5229a0ded4ee771b
[ "Apache-2.0" ]
4
2018-10-02T14:47:43.000Z
2019-09-12T02:53:46.000Z
src/cryptojwt/jws/utils.py
IdentityPython/JWTConnect-Python-CryptoJWT
a7dd24f07e7bab2ce2580d7111340cc753a965c0
[ "Apache-2.0" ]
67
2020-01-23T17:33:56.000Z
2022-03-26T17:58:33.000Z
src/cryptojwt/jws/utils.py
openid/JWTConnect-Python-CryptoJWT
ec79b98f62f033afc596a4be5229a0ded4ee771b
[ "Apache-2.0" ]
5
2018-06-22T07:08:28.000Z
2019-12-20T09:57:03.000Z
# import struct from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from ..exception import UnsupportedAlgorithm from ..jwk.hmac import sha256_digest from ..jwk.hmac import sha384_digest from ..jwk.hmac import sha512_digest from ..utils import as_unicode from ..utils import b64e def left_hash(msg, func="HS256"): """Calculate left hash as described in https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken for at_hash and in for c_hash :param msg: The message over which the hash should be calculated :param func: Which hash function that was used for the ID token """ if func == "HS256": return as_unicode(b64e(sha256_digest(msg)[:16])) elif func == "HS384": return as_unicode(b64e(sha384_digest(msg)[:24])) elif func == "HS512": return as_unicode(b64e(sha512_digest(msg)[:32])) # def mpint(b): # b += b"\x00" # return struct.pack(">L", len(b)) + b # def alg2keytype(alg): """ Go from algorithm name to key type. :param alg: The algorithm name :return: The key type """ if not alg or alg.lower() == "none": return "none" elif alg.startswith("RS") or alg.startswith("PS"): return "RSA" elif alg.startswith("HS") or alg.startswith("A"): return "oct" elif alg.startswith("ES") or alg.startswith("ECDH-ES"): return "EC" else: return None def parse_rsa_algorithm(algorithm): """ Parses a RSA algorithm and returns tuple (hash, padding). :param algorithm: string, RSA algorithm as defined at https://tools.ietf.org/html/rfc7518#section-3.1. :raises: UnsupportedAlgorithm: if the algorithm is not supported. :returns: (hash, padding) tuple. """ if algorithm == "RS256": return hashes.SHA256(), padding.PKCS1v15() elif algorithm == "RS384": return hashes.SHA384(), padding.PKCS1v15() elif algorithm == "RS512": return hashes.SHA512(), padding.PKCS1v15() elif algorithm == "PS256": return ( hashes.SHA256(), padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), ) elif algorithm == "PS384": return ( hashes.SHA384(), padding.PSS(mgf=padding.MGF1(hashes.SHA384()), salt_length=padding.PSS.MAX_LENGTH), ) elif algorithm == "PS512": return ( hashes.SHA512(), padding.PSS(mgf=padding.MGF1(hashes.SHA512()), salt_length=padding.PSS.MAX_LENGTH), ) else: raise UnsupportedAlgorithm("Unknown algorithm: {}".format(algorithm))
30.568182
95
0.641636
c413df3e531e6990ed380923836adcfe61080053
5,140
py
Python
djangae/contrib/processing/mapreduce/tests/mapreduce_tests.py
ikedaosushi/djangae
5fd2f8d70699fbbf155740effe42a36b205a6540
[ "BSD-3-Clause" ]
null
null
null
djangae/contrib/processing/mapreduce/tests/mapreduce_tests.py
ikedaosushi/djangae
5fd2f8d70699fbbf155740effe42a36b205a6540
[ "BSD-3-Clause" ]
null
null
null
djangae/contrib/processing/mapreduce/tests/mapreduce_tests.py
ikedaosushi/djangae
5fd2f8d70699fbbf155740effe42a36b205a6540
[ "BSD-3-Clause" ]
null
null
null
from __future__ import absolute_import from mapreduce.mapreduce_pipeline import MapreducePipeline from django.db import models from djangae.test import TestCase from djangae.test import process_task_queues from djangae.contrib.processing.mapreduce.helpers import DjangoInputReader from djangae.contrib.processing.mapreduce.utils import qualname # from djangae.contrib.processing.mapreduce.pipelines import MapPipeline class MRTestNode(models.Model): data = models.CharField(max_length=32) counter = models.IntegerField() class Meta: app_label = "mapreduce" # class MapPipelineTestCase(TestCase): # # def setUp(self): # for x in range(100): # self.testnode = TestNode() # self.testnode.data = 'Lol' # self.testnode.counter = 1 # self.testnode.save() # super(MapPipelineTestCase, self).setUp() # # def test_map_works(self): # pipe = MapPipeline( # "increment", # "djangae.contrib.processing.mapreduce.tests.mapreduce.model_counter_increment", # "djangae.contrib.processing.mapreduce.input_readers.DjangoInputReader", # mapper_params={'input_reader': {'model': 'mapreduce.TestNode'}}, # shards=10 # ) # pipe.start() # process_task_queues() # nodes = TestNode.objects.all() # for node in nodes: # self.assertEqual(node.counter, 2) # class DjangoInputReaderTestCase(TestCase): ENTITY_COUNT = 300 def setUp(self): for x in range(self.ENTITY_COUNT): self.testnode = MRTestNode() self.testnode.data = 'Lol' self.testnode.counter = 1 if x < self.ENTITY_COUNT / 4: self.testnode.id = x + 1 self.testnode.save() super(DjangoInputReaderTestCase, self).setUp() def _test_split_input_on_n_shards(self, shards): from mapreduce.model import MapperSpec mapper_spec = MapperSpec( '', '', { 'input_reader': { 'model': 'mapreduce.MRTestNode' } }, shards, ) readers = DjangoInputReader.split_input(mapper_spec) self.assertEqual(len(readers), shards) models = [] for reader in readers: for model in reader: models.append(model.pk) self.assertEqual(len(models), self.ENTITY_COUNT) self.assertEqual(len(models), len(set(models))) def test_split_input_on_one_shard(self): self._test_split_input_on_n_shards(1) def test_split_input_on_two_shards(self): self._test_split_input_on_n_shards(2) def test_split_input_one_batch_per_shard(self): self._test_split_input_on_n_shards(6) class MapreduceTestCase(TestCase): def setUp(self): for x in range(20): self.testnode = MRTestNode() self.testnode.data = 'Lol' self.testnode.counter = 1 self.testnode.save() super(MapreduceTestCase, self).setUp() def test_mapreduce_basic(self): """ Tests basic mapreduce with random input """ pipe = MapreducePipeline( "word_count", qualname(letter_count_map), qualname(word_count_reduce), "mapreduce.input_readers.RandomStringInputReader", "mapreduce.output_writers.GoogleCloudStorageOutputWriter", mapper_params={'count': 10}, reducer_params={"mime_type": "text/plain", 'output_writer': {'bucket_name': 'test'}}, shards=1 ) pipe.start() process_task_queues() def test_mapreduce_django_input(self): """ Test basic django operations inside a map task, this shows that our handlers are working """ nodes = MRTestNode.objects.all() for node in nodes: self.assertEqual(node.counter, 1) pipe = MapreducePipeline( "word_count", qualname(model_counter_increment), qualname(word_count_reduce), "djangae.contrib.processing.mapreduce.input_readers.DjangoInputReader", "mapreduce.output_writers.GoogleCloudStorageOutputWriter", mapper_params={'count': 10, 'input_reader': {'model': 'mapreduce.MRTestNode'}}, reducer_params={"mime_type": "text/plain", 'output_writer': {'bucket_name': 'test'}}, shards=5 ) pipe.start() process_task_queues() nodes = MRTestNode.objects.all() for node in nodes: self.assertEqual(node.counter, 2) def letter_count_map(data): """Word Count map function.""" letters = [x for x in data] for l in letters: yield (l, "") def model_counter_increment(instance): """Word Count map function.""" instance.counter += 1 instance.save() yield (instance.pk, "{0}".format(instance.counter)) def word_count_reduce(key, values): """Word Count reduce function.""" yield "%s: %d\n" % (key, len(values))
32.948718
97
0.615175
3918496e46d3aa23a4f2631ef5731b89994d5935
3,434
py
Python
metachains/synchronizer.py
Storj/metachains
ed68e29eaf49da77a6fb924cdb9790de4e5e8965
[ "MIT" ]
2
2015-01-03T00:08:36.000Z
2015-10-10T03:32:23.000Z
metachains/synchronizer.py
StorjOld/metachains
ed68e29eaf49da77a6fb924cdb9790de4e5e8965
[ "MIT" ]
null
null
null
metachains/synchronizer.py
StorjOld/metachains
ed68e29eaf49da77a6fb924cdb9790de4e5e8965
[ "MIT" ]
4
2015-06-15T19:49:01.000Z
2015-10-16T03:29:02.000Z
from decimal import Decimal from collections import defaultdict import operator import logging class Synchronizer(object): """Synchronizer accesses data from and to a blockchain. Synchronizer must be instantiated with three objects: coin -- An object that responds to blocks() and transactions(block) cloud -- An object that responds to data_dump(bytes) and data_load(data, txid) """ ConfirmationThreshold = 10 TransactionAmount = Decimal('0.05') TransactionAddress = "F94Vd1E6Hx2uhntGRo8mn3aJvQLS4KXmSA" def __init__(self, coin, cloud): self.coin = coin self.cloud = cloud self._log = logging.getLogger('storj.metachains') def scan_database(self): """Scan database for non published data.""" while True: payload = self.cloud.data_dump(self.coin.MaxPayloadSize) if payload is None: return self._log.info('scan_database: processing payload') self.process_database(payload) def scan_blockchain(self): """Scan blockchain for non registered data, reassembling the data regions. """ outstanding_txns = {} for block in self.coin.blocks(self.cloud.last_known_block()): self._log.info('scan_blockchain: indexing block #{}'.format(block['height'])) # Todo make this debug for txid, entry in self.coin.transactions(block): if not txid: continue outstanding_txns[txid] = (entry, block) linked_entries = defaultdict(list) heads = {} for txid, (entry, block) in outstanding_txns.items(): if entry['prev_txid'] == None: heads[txid] = (entry, block) elif entry['prev_txid'] in outstanding_txns: linked_entries[entry['first_txid']].append(entry) def is_complete(txid): return heads[txid][0]['total_length'] == sum([len(entry['region']) for entry in linked_entries[txid]], len(heads[txid][0]['region'])) lowest_incomplete_block = list(self.coin.blocks(self.coin.block_count() - 1))[-1] for txid, (head_entry, head_block) in heads.items(): if not is_complete(txid): # The blockchain does not yet contain all constituent # fragments for this entry if head_block['height'] < lowest_incomplete_block['height']: lowest_incomplete_block = head_block continue tail = b''.join(entry['region'] for entry in sorted(linked_entries[txid], key=operator.itemgetter('index'))) data = head_entry['region'] + tail try: self.process_blockchain(txid, data) except: #FIXME: this can't be what we want? pass self.confirm(lowest_incomplete_block) # FIXME off by one def process_blockchain(self, txid, info): """Load payload into local database.""" self.cloud.data_load(info, txid) def process_database(self, payload): """Publish payload into blockchain.""" self.coin.send_data_address( payload, self.TransactionAddress, self.TransactionAmount) def confirm(self, block): self.cloud.visit_block( max(block["height"] - self.ConfirmationThreshold, 0))
38.155556
145
0.610076