hexsha
stringlengths 40
40
| size
int64 1
1.03M
| ext
stringclasses 10
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 3
239
| max_stars_repo_name
stringlengths 5
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
239
| max_issues_repo_name
stringlengths 5
130
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
239
| max_forks_repo_name
stringlengths 5
130
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 1
1.03M
| avg_line_length
float64 1
958k
| max_line_length
int64 1
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
acfeba09fc329f8bebf73e417bce0ef193bcade7
| 20,991
|
py
|
Python
|
readthedocs/proxito/views/serve.py
|
eric-wieser/readthedocs.org
|
fb01c6d9d78272e3f4fd146697e8760c04e4fbb6
|
[
"MIT"
] | null | null | null |
readthedocs/proxito/views/serve.py
|
eric-wieser/readthedocs.org
|
fb01c6d9d78272e3f4fd146697e8760c04e4fbb6
|
[
"MIT"
] | 6
|
2021-06-09T19:38:56.000Z
|
2022-03-12T00:56:56.000Z
|
readthedocs/proxito/views/serve.py
|
mondeja/readthedocs.org
|
fb01c6d9d78272e3f4fd146697e8760c04e4fbb6
|
[
"MIT"
] | null | null | null |
"""Views for doc serving."""
import itertools
import logging
from urllib.parse import urlparse
from django.conf import settings
from django.core.files.storage import get_storage_class
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import resolve as url_resolve
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.cache import cache_page
from readthedocs.builds.constants import EXTERNAL, LATEST, STABLE
from readthedocs.builds.models import Version
from readthedocs.core.utils.extend import SettingsOverrideObject
from readthedocs.projects import constants
from readthedocs.projects.constants import SPHINX_HTMLDIR
from readthedocs.projects.templatetags.projects_tags import sort_version_aware
from readthedocs.redirects.exceptions import InfiniteRedirectException
from .decorators import map_project_slug
from .mixins import ServeDocsMixin, ServeRedirectMixin
from .utils import _get_project_data_from_request
log = logging.getLogger(__name__) # noqa
class ServePageRedirect(ServeRedirectMixin, ServeDocsMixin, View):
def get(self,
request,
project_slug=None,
subproject_slug=None,
version_slug=None,
filename='',
): # noqa
version_slug = self.get_version_from_host(request, version_slug)
final_project, lang_slug, version_slug, filename = _get_project_data_from_request( # noqa
request,
project_slug=project_slug,
subproject_slug=subproject_slug,
lang_slug=None,
version_slug=version_slug,
filename=filename,
)
return self.system_redirect(request, final_project, lang_slug, version_slug, filename)
class ServeDocsBase(ServeRedirectMixin, ServeDocsMixin, View):
def get(self,
request,
project_slug=None,
subproject_slug=None,
subproject_slash=None,
lang_slug=None,
version_slug=None,
filename='',
): # noqa
"""
Take the incoming parsed URL's and figure out what file to serve.
``subproject_slash`` is used to determine if the subproject URL has a slash,
so that we can decide if we need to serve docs or add a /.
"""
version_slug = self.get_version_from_host(request, version_slug)
final_project, lang_slug, version_slug, filename = _get_project_data_from_request( # noqa
request,
project_slug=project_slug,
subproject_slug=subproject_slug,
lang_slug=lang_slug,
version_slug=version_slug,
filename=filename,
)
log.info(
'Serving docs: project=%s, subproject=%s, lang_slug=%s, version_slug=%s, filename=%s',
final_project.slug, subproject_slug, lang_slug, version_slug, filename
)
# Handle requests that need canonicalizing (eg. HTTP -> HTTPS, redirect to canonical domain)
if hasattr(request, 'canonicalize'):
return self.canonical_redirect(request, final_project, version_slug, filename)
# Handle a / redirect when we aren't a single version
if all([
lang_slug is None,
# External versions/builds will always have a version,
# because it is taken from the host name
version_slug is None or hasattr(request, 'external_domain'),
filename == '',
not final_project.single_version,
]):
return self.system_redirect(request, final_project, lang_slug, version_slug, filename)
# Handle `/projects/subproject` URL redirection:
# when there _is_ a subproject_slug but not a subproject_slash
if all([
final_project.single_version,
filename == '',
subproject_slug,
not subproject_slash,
]):
return self.system_redirect(request, final_project, lang_slug, version_slug, filename)
if all([
(lang_slug is None or version_slug is None),
not final_project.single_version,
self.version_type != EXTERNAL,
]):
log.warning(
'Invalid URL for project with versions. url=%s, project=%s',
filename, final_project.slug
)
raise Http404('Invalid URL for project with versions')
# TODO: un-comment when ready to perform redirect here
# redirect_path, http_status = self.get_redirect(
# final_project,
# lang_slug,
# version_slug,
# filename,
# request.path,
# )
# if redirect_path and http_status:
# return self.get_redirect_response(request, redirect_path, http_status)
# Check user permissions and return an unauthed response if needed
if not self.allowed_user(request, final_project, version_slug):
return self.get_unauthed_response(request, final_project)
storage_path = final_project.get_storage_path(
type_='html',
version_slug=version_slug,
include_file=False,
version_type=self.version_type,
)
storage = get_storage_class(settings.RTD_BUILD_MEDIA_STORAGE)()
# If ``filename`` is empty, serve from ``/``
path = storage.join(storage_path, filename.lstrip('/'))
# Handle our backend storage not supporting directory indexes,
# so we need to append index.html when appropriate.
if path[-1] == '/':
# We need to add the index.html before ``storage.url`` since the
# Signature and Expire time is calculated per file.
path += 'index.html'
# NOTE: calling ``.url`` will remove the trailing slash
storage_url = storage.url(path, http_method=request.method)
# URL without scheme and domain to perform an NGINX internal redirect
parsed_url = urlparse(storage_url)._replace(scheme='', netloc='')
final_url = parsed_url.geturl()
return self._serve_docs(
request,
final_project=final_project,
version_slug=version_slug,
path=final_url,
)
class ServeDocs(SettingsOverrideObject):
_default_class = ServeDocsBase
class ServeError404Base(ServeRedirectMixin, ServeDocsMixin, View):
def get(self, request, proxito_path, template_name='404.html'):
"""
Handler for 404 pages on subdomains.
This does a couple things:
* Handles directory indexing for URLs that don't end in a slash
* Handles directory indexing for README.html (for now)
* Handles custom 404 serving
For 404's, first search for a 404 page in the current version, then continues
with the default version and finally, if none of them are found, the Read
the Docs default page (Maze Found) is rendered by Django and served.
"""
# pylint: disable=too-many-locals
log.info('Executing 404 handler. proxito_path=%s', proxito_path)
# Parse the URL using the normal urlconf, so we get proper subdomain/translation data
_, __, kwargs = url_resolve(
proxito_path,
urlconf='readthedocs.proxito.urls',
)
version_slug = kwargs.get('version_slug')
version_slug = self.get_version_from_host(request, version_slug)
final_project, lang_slug, version_slug, filename = _get_project_data_from_request( # noqa
request,
project_slug=kwargs.get('project_slug'),
subproject_slug=kwargs.get('subproject_slug'),
lang_slug=kwargs.get('lang_slug'),
version_slug=version_slug,
filename=kwargs.get('filename', ''),
)
storage_root_path = final_project.get_storage_path(
type_='html',
version_slug=version_slug,
include_file=False,
version_type=self.version_type,
)
storage = get_storage_class(settings.RTD_BUILD_MEDIA_STORAGE)()
# First, check for dirhtml with slash
for tryfile in ('index.html', 'README.html'):
storage_filename_path = storage.join(
storage_root_path,
f'{filename}/{tryfile}'.lstrip('/'),
)
log.debug(
'Trying index filename: project=%s version=%s, file=%s',
final_project.slug,
version_slug,
storage_filename_path,
)
if storage.exists(storage_filename_path):
log.info(
'Redirecting to index file: project=%s version=%s, storage_path=%s',
final_project.slug,
version_slug,
storage_filename_path,
)
# Use urlparse so that we maintain GET args in our redirect
parts = urlparse(proxito_path)
if tryfile == 'README.html':
new_path = parts.path.rstrip('/') + f'/{tryfile}'
else:
new_path = parts.path.rstrip('/') + '/'
# `proxito_path` doesn't include query params.`
query = urlparse(request.get_full_path()).query
new_parts = parts._replace(
path=new_path,
query=query,
)
redirect_url = new_parts.geturl()
# TODO: decide if we need to check for infinite redirect here
# (from URL == to URL)
return HttpResponseRedirect(redirect_url)
# ``redirect_filename`` is the path without ``/<lang>/<version>`` and
# without query, starting with a ``/``. This matches our old logic:
# https://github.com/readthedocs/readthedocs.org/blob/4b09c7a0ab45cd894c3373f7f07bad7161e4b223/readthedocs/redirects/utils.py#L60
# We parse ``filename`` to remove the query from it
schema, netloc, path, params, query, fragments = urlparse(filename)
redirect_filename = path
# we can't check for lang and version here to decide if we need to add
# the ``/`` or not because ``/install.html`` is a valid path to use as
# redirect and does not include lang and version on it. It should be
# fine always adding the ``/`` to the beginning.
redirect_filename = '/' + redirect_filename.lstrip('/')
# Check and perform redirects on 404 handler
# NOTE: this redirect check must be done after trying files like
# ``index.html`` and ``README.html`` to emulate the behavior we had when
# serving directly from NGINX without passing through Python.
redirect_path, http_status = self.get_redirect(
project=final_project,
lang_slug=lang_slug,
version_slug=version_slug,
filename=redirect_filename,
full_path=proxito_path,
)
if redirect_path and http_status:
try:
return self.get_redirect_response(request, redirect_path, proxito_path, http_status)
except InfiniteRedirectException:
# Continue with our normal 404 handling in this case
pass
# If that doesn't work, attempt to serve the 404 of the current version (version_slug)
# Secondly, try to serve the 404 page for the default version
# (project.get_default_version())
doc_type = (
Version.objects.filter(project=final_project, slug=version_slug)
.values_list('documentation_type', flat=True)
.first()
)
versions = [(version_slug, doc_type)]
default_version_slug = final_project.get_default_version()
if default_version_slug != version_slug:
default_version_doc_type = (
Version.objects.filter(project=final_project, slug=default_version_slug)
.values_list('documentation_type', flat=True)
.first()
)
versions.append((default_version_slug, default_version_doc_type))
for version_slug_404, doc_type_404 in versions:
if not self.allowed_user(request, final_project, version_slug_404):
continue
storage_root_path = final_project.get_storage_path(
type_='html',
version_slug=version_slug_404,
include_file=False,
version_type=self.version_type,
)
tryfiles = ['404.html']
# SPHINX_HTMLDIR is the only builder
# that could output a 404/index.html file.
if doc_type_404 == SPHINX_HTMLDIR:
tryfiles.append('404/index.html')
for tryfile in tryfiles:
storage_filename_path = storage.join(storage_root_path, tryfile)
if storage.exists(storage_filename_path):
log.info(
'Serving custom 404.html page: [project: %s] [version: %s]',
final_project.slug,
version_slug_404,
)
resp = HttpResponse(storage.open(storage_filename_path).read())
resp.status_code = 404
return resp
raise Http404('No custom 404 page found.')
class ServeError404(SettingsOverrideObject):
_default_class = ServeError404Base
class ServeRobotsTXTBase(ServeDocsMixin, View):
@method_decorator(map_project_slug)
@method_decorator(cache_page(60 * 60 * 12)) # 12 hours
def get(self, request, project):
"""
Serve custom user's defined ``/robots.txt``.
If the user added a ``robots.txt`` in the "default version" of the
project, we serve it directly.
"""
# Use the ``robots.txt`` file from the default version configured
version_slug = project.get_default_version()
version = project.versions.get(slug=version_slug)
no_serve_robots_txt = any([
# If the default version is private or,
version.privacy_level == constants.PRIVATE,
# default version is not active or,
not version.active,
# default version is not built
not version.built,
])
if no_serve_robots_txt:
# ... we do return a 404
raise Http404()
storage = get_storage_class(settings.RTD_BUILD_MEDIA_STORAGE)()
storage_path = project.get_storage_path(
type_='html',
version_slug=version_slug,
include_file=False,
version_type=self.version_type,
)
path = storage.join(storage_path, 'robots.txt')
if storage.exists(path):
url = storage.url(path)
url = urlparse(url)._replace(scheme='', netloc='').geturl()
return self._serve_docs(
request,
final_project=project,
path=url,
)
sitemap_url = '{scheme}://{domain}/sitemap.xml'.format(
scheme='https',
domain=project.subdomain(),
)
return HttpResponse(
'User-agent: *\nAllow: /\nSitemap: {}\n'.format(sitemap_url),
content_type='text/plain',
)
class ServeRobotsTXT(SettingsOverrideObject):
_default_class = ServeRobotsTXTBase
class ServeSitemapXMLBase(View):
@method_decorator(map_project_slug)
@method_decorator(cache_page(60 * 60 * 12)) # 12 hours
def get(self, request, project):
"""
Generate and serve a ``sitemap.xml`` for a particular ``project``.
The sitemap is generated from all the ``active`` and public versions of
``project``. These versions are sorted by using semantic versioning
prepending ``latest`` and ``stable`` (if they are enabled) at the beginning.
Following this order, the versions are assigned priorities and change
frequency. Starting from 1 and decreasing by 0.1 for priorities and starting
from daily, weekly to monthly for change frequency.
If the project doesn't have any public version, the view raises ``Http404``.
:param request: Django request object
:param project: Project instance to generate the sitemap
:returns: response with the ``sitemap.xml`` template rendered
:rtype: django.http.HttpResponse
"""
# pylint: disable=too-many-locals
def priorities_generator():
"""
Generator returning ``priority`` needed by sitemap.xml.
It generates values from 1 to 0.1 by decreasing in 0.1 on each
iteration. After 0.1 is reached, it will keep returning 0.1.
"""
priorities = [1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2]
yield from itertools.chain(priorities, itertools.repeat(0.1))
def hreflang_formatter(lang):
"""
sitemap hreflang should follow correct format.
Use hyphen instead of underscore in language and country value.
ref: https://en.wikipedia.org/wiki/Hreflang#Common_Mistakes
"""
if '_' in lang:
return lang.replace('_', '-')
return lang
def changefreqs_generator():
"""
Generator returning ``changefreq`` needed by sitemap.xml.
It returns ``weekly`` on first iteration, then ``daily`` and then it
will return always ``monthly``.
We are using ``monthly`` as last value because ``never`` is too
aggressive. If the tag is removed and a branch is created with the same
name, we will want bots to revisit this.
"""
changefreqs = ['weekly', 'daily']
yield from itertools.chain(changefreqs, itertools.repeat('monthly'))
public_versions = Version.internal.public(
project=project,
only_active=True,
)
if not public_versions.exists():
raise Http404
sorted_versions = sort_version_aware(public_versions)
# This is a hack to swap the latest version with
# stable version to get the stable version first in the sitemap.
# We want stable with priority=1 and changefreq='weekly' and
# latest with priority=0.9 and changefreq='daily'
# More details on this: https://github.com/rtfd/readthedocs.org/issues/5447
if (len(sorted_versions) >= 2 and sorted_versions[0].slug == LATEST and
sorted_versions[1].slug == STABLE):
sorted_versions[0], sorted_versions[1] = sorted_versions[1], sorted_versions[0]
versions = []
for version, priority, changefreq in zip(
sorted_versions,
priorities_generator(),
changefreqs_generator(),
):
element = {
'loc': version.get_subdomain_url(),
'priority': priority,
'changefreq': changefreq,
'languages': [],
}
# Version can be enabled, but not ``built`` yet. We want to show the
# link without a ``lastmod`` attribute
last_build = version.builds.order_by('-date').first()
if last_build:
element['lastmod'] = last_build.date.isoformat()
if project.translations.exists():
for translation in project.translations.all():
translation_versions = (
Version.internal.public(project=translation
).values_list('slug', flat=True)
)
if version.slug in translation_versions:
href = project.get_docs_url(
version_slug=version.slug,
lang_slug=translation.language,
)
element['languages'].append({
'hreflang': hreflang_formatter(translation.language),
'href': href,
})
# Add itself also as protocol requires
element['languages'].append({
'hreflang': project.language,
'href': element['loc'],
})
versions.append(element)
context = {
'versions': versions,
}
return render(
request,
'sitemap.xml',
context,
content_type='application/xml',
)
class ServeSitemapXML(SettingsOverrideObject):
_default_class = ServeSitemapXMLBase
| 39.162313
| 137
| 0.601972
|
acfeba2254b69edf2d5f2681dd483c2d15b43323
| 2,636
|
py
|
Python
|
python/GenomeWorkflows/upload_genomes_folder.py
|
FabricGenomics/omicia_api_examples
|
b761d40744032720bdf1a4f59877e16b8b1dfcf0
|
[
"MIT"
] | 2
|
2017-06-13T13:59:17.000Z
|
2021-12-17T18:52:08.000Z
|
python/GenomeWorkflows/upload_genomes_folder.py
|
FabricGenomics/omicia_api_examples
|
b761d40744032720bdf1a4f59877e16b8b1dfcf0
|
[
"MIT"
] | 1
|
2017-11-22T00:20:19.000Z
|
2017-11-22T00:41:05.000Z
|
python/GenomeWorkflows/upload_genomes_folder.py
|
FabricGenomics/omicia_api_examples
|
b761d40744032720bdf1a4f59877e16b8b1dfcf0
|
[
"MIT"
] | 3
|
2020-03-05T18:41:36.000Z
|
2021-01-14T08:31:30.000Z
|
"""Upload multiple genomes to an existing project from a folder.
"""
import argparse
import os
import requests
from requests.auth import HTTPBasicAuth
import sys
import simplejson as json
# Load environment variables for request authentication parameters
if "FABRIC_API_PASSWORD" not in os.environ:
sys.exit("FABRIC_API_PASSWORD environment variable missing")
if "FABRIC_API_LOGIN" not in os.environ:
sys.exit("FABRIC_API_LOGIN environment variable missing")
FABRIC_API_LOGIN = os.environ['FABRIC_API_LOGIN']
FABRIC_API_PASSWORD = os.environ['FABRIC_API_PASSWORD']
FABRIC_API_URL = os.environ.get('FABRIC_API_URL', 'https://api.fabricgenomics.com')
auth = HTTPBasicAuth(FABRIC_API_LOGIN, FABRIC_API_PASSWORD)
def get_genome_files(folder):
"""Return a dict of .vcf, .vcf.gz, and vcf.bz2 genomes in a given folder
"""
genome_files = []
for file_name in os.listdir(folder):
genome_info = {"name": file_name,
"assembly_version": "hg19",
"genome_sex": "unspecified",
"genome_label": file_name[0:100]}
if 'vcf' in file_name:
genome_files.append(genome_info)
return genome_files
def upload_genomes_to_project(project_id, folder):
"""upload all of the genomes in the given folder to the project with
the given project id
"""
# List where returned genome JSON information will be stored
genome_json_objects = []
for genome_file in get_genome_files(folder):
url = "{}/projects/{}/genomes?genome_label={}&genome_sex={}&external_id=&assembly_version=hg19"
url = url.format(FABRIC_API_URL,
project_id,
genome_file["genome_label"],
genome_file["genome_sex"])
with open(folder + "/" + genome_file["name"], 'rb') as file_handle:
# Post request and store id of newly uploaded genome
result = requests.put(url, auth=auth, data=file_handle)
genome_json_objects.append(result.json())
return genome_json_objects
def main():
"""Main function. Upload VCF files from a folder to a specified project.
"""
parser = argparse.ArgumentParser(description='Upload a folder of genomes.')
parser.add_argument('project_id', metavar='project_id')
parser.add_argument('folder', metavar='folder')
args = parser.parse_args()
project_id = args.project_id
folder = args.folder
genome_objects = upload_genomes_to_project(project_id, folder)
sys.stdout.write(json.dumps(genome_objects, indent=4))
if __name__ == "__main__":
main()
| 35.146667
| 103
| 0.683612
|
acfeba8c6e1987b3c94c706e1e761a7ccccb4078
| 2,674
|
py
|
Python
|
simsimpy/subset.py
|
nishbo/simsimpy
|
54882ba7cd989f9c51ebd8ed06d4138b05d89ee0
|
[
"Apache-2.0"
] | 3
|
2018-07-25T15:31:51.000Z
|
2018-07-26T20:55:09.000Z
|
simsimpy/subset.py
|
nishbo/simsimpy
|
54882ba7cd989f9c51ebd8ed06d4138b05d89ee0
|
[
"Apache-2.0"
] | null | null | null |
simsimpy/subset.py
|
nishbo/simsimpy
|
54882ba7cd989f9c51ebd8ed06d4138b05d89ee0
|
[
"Apache-2.0"
] | null | null | null |
from math import floor, ceil
# from __future__ import print_function
class SubsetStorage(object):
"""Stores portion of input data, to save space.
Does an injection of data of input size into a list of buf size. Supports
__getitem__, __setitem__, __len__, __contains__, __delitem__, __str__
magic, append.
Attributes:
buf_size: size of inner buffer of storage.
Private attributes:
_i: inner position in preallocated buffer.
_j: current position in data for receiving.
_dif: relative movement of _i when _j increases.
_buf: buffer.
"""
def __init__(self, buf_size, input_size):
self.buf_size = buf_size
self._dif = buf_size / (input_size + 1)
self._i = 0
self._j = 0
self._buf = [None]*buf_size
def append(self, d):
self._i = int(floor(self._j * self._dif))
if self._i >= self.buf_size:
self._i -= 1
raise BufferError('Stack is full.')
self._buf[self._i] = d
self._j += 1
def __len__(self):
return self._i + 1
def __getitem__(self, sl):
if isinstance(sl, slice):
start, stop, step = sl.indices(len(self))
sl = slice(start, stop, step)
else:
if sl > len(self):
raise IndexError
if sl < 0:
sl += len(self)
return self._buf[sl]
def __setitem__(self, key, value):
if key > len(self):
raise IndexError
if key < 0:
key += len(self)
self._buf[key] = value
def __iter__(self):
return self._buf[:len(self)]
def __contains__(self, item):
return item in self._buf[:len(self)]
def __delitem__(self, key):
if key > len(self):
raise IndexError
if key < 0:
key += len(self)
# print self._buf
del self._buf[key]
# print self._buf
# print self._j, int(floor(self._j * self._dif)),
self._j -= int(ceil(1./self._dif))
# print 1./self._dif, self._j, int(floor(self._j * self._dif))
self._buf.append(None)
self._i = int(floor(self._j * self._dif))
def __str__(self):
return str(self._buf[:len(self)])
def test():
a = SubsetStorage(5, 13)
for i in range(13):
a.append(i)
print(i, len(a), a[-1], a)
print(a)
a[2] = -11
print(a[1:3], a)
if -11 in a:
print('-11 is in a')
if not 110 in a:
print('but not 110')
print('\n', a)
del a[2]
print(a)
a.append(78)
print(a)
print(a[:], a[-1])
if __name__ == '__main__':
test()
| 23.663717
| 77
| 0.550112
|
acfebb68b95bce8efcb5451057d560908170a03c
| 787
|
py
|
Python
|
bin/pythonista.py
|
carls-app/weekly-movie-tools
|
e6aacbf7488918b103a7476a59f22e61be25884d
|
[
"MIT"
] | 1
|
2020-01-17T07:48:45.000Z
|
2020-01-17T07:48:45.000Z
|
bin/pythonista.py
|
carls-app/weekly-movie-tools
|
e6aacbf7488918b103a7476a59f22e61be25884d
|
[
"MIT"
] | 3
|
2018-02-26T21:27:35.000Z
|
2021-09-07T23:30:37.000Z
|
bin/pythonista.py
|
carls-app/weekly-movie-tools
|
e6aacbf7488918b103a7476a59f22e61be25884d
|
[
"MIT"
] | 1
|
2018-02-26T22:05:10.000Z
|
2018-02-26T22:05:10.000Z
|
#!/usr/bin/env python3
import sys
import dialogs
from datetime import date, timedelta
from lib import get_movie
def main():
today = date.today()
friday = today + timedelta((4 - today.weekday()) % 7)
args = dialogs.form_dialog(title="Movie", fields=[
{
'type': 'text',
'key': 'title',
'title': 'Movie Title',
'placeholder': 'What\'s the movie?',
},
{
'type': 'date',
'key': 'date',
'title': 'First day of movie',
'value': friday,
},
])
if not args:
sys.exit(0)
args['date'] = args['date'].date()
get_movie(title=args['title'], date=args['date'], year=None)
print('done!')
if __name__ == '__main__':
main()
| 19.675
| 64
| 0.503177
|
acfebc0cb76f9f11c7c88df5107bc42b2638c884
| 1,805
|
py
|
Python
|
test_utilities/src/d1_test/mock_api/tests/test_catch_all.py
|
DataONEorg/d1_python
|
dfab267c3adea913ab0e0073ed9dc1ee50b5b8eb
|
[
"Apache-2.0"
] | 15
|
2016-10-28T13:56:52.000Z
|
2022-01-31T19:07:49.000Z
|
test_utilities/src/d1_test/mock_api/tests/test_catch_all.py
|
DataONEorg/d1_python
|
dfab267c3adea913ab0e0073ed9dc1ee50b5b8eb
|
[
"Apache-2.0"
] | 56
|
2017-03-16T03:52:32.000Z
|
2022-03-12T01:05:28.000Z
|
test_utilities/src/d1_test/mock_api/tests/test_catch_all.py
|
DataONEorg/d1_python
|
dfab267c3adea913ab0e0073ed9dc1ee50b5b8eb
|
[
"Apache-2.0"
] | 11
|
2016-05-31T16:22:02.000Z
|
2020-10-05T14:37:10.000Z
|
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# 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 pytest
import d1_common.types.exceptions
import d1_test.d1_test_case
import d1_test.mock_api.catch_all
class TestMockCatchAll(d1_test.d1_test_case.D1TestCase):
@d1_test.mock_api.catch_all.activate
def test_1000(self, cn_client_v2):
"""mock_api.catch_all: Returns a dict correctly echoing the request."""
d1_test.mock_api.catch_all.add_callback(d1_test.d1_test_case.MOCK_CN_BASE_URL)
echo_dict = cn_client_v2.getFormat("valid_format_id")
d1_test.mock_api.catch_all.assert_expected_echo(
echo_dict, "catch_all", cn_client_v2
)
@d1_test.mock_api.catch_all.activate
def test_1010(self, cn_client_v2):
"""mock_api.catch_all(): Passing a trigger header triggers a
DataONEException."""
d1_test.mock_api.catch_all.add_callback(d1_test.d1_test_case.MOCK_CN_BASE_URL)
with pytest.raises(d1_common.types.exceptions.NotFound):
cn_client_v2.getFormat("valid_format_id", vendorSpecific={"trigger": "404"})
| 41.022727
| 88
| 0.753463
|
acfebc95a82dd6b8beee78bcb5c25818d2d93416
| 6,731
|
py
|
Python
|
layernorm/layer_norm_layers.py
|
awesome-archive/nn_playground
|
798418b0ce09d2ec66d45cf436a1d95494e01ef7
|
[
"MIT"
] | 445
|
2016-12-28T13:11:25.000Z
|
2022-03-14T03:05:34.000Z
|
layernorm/layer_norm_layers.py
|
Edresson/nn_playground
|
460b8bb7823047292189f91de3201a7a3d2677a9
|
[
"MIT"
] | 21
|
2017-01-11T09:01:02.000Z
|
2022-02-16T06:35:03.000Z
|
layernorm/layer_norm_layers.py
|
Edresson/nn_playground
|
460b8bb7823047292189f91de3201a7a3d2677a9
|
[
"MIT"
] | 174
|
2016-12-29T06:08:46.000Z
|
2022-02-24T04:29:22.000Z
|
from keras.engine import Layer, InputSpec
from keras.layers import LSTM, GRU
from keras import initializers, regularizers
from keras import backend as K
import numpy as np
def to_list(x):
if type(x) not in [list, tuple]:
return [x]
else:
return list(x)
def LN(x, gamma, beta, epsilon=1e-6, axis=-1):
m = K.mean(x, axis=axis, keepdims=True)
std = K.sqrt(K.var(x, axis=axis, keepdims=True) + epsilon)
x_normed = (x - m) / (std + epsilon)
x_normed = gamma * x_normed + beta
return x_normed
class LayerNormalization(Layer):
def __init__(self, axis=-1,
gamma_init='one', beta_init='zero',
gamma_regularizer=None, beta_regularizer=None,
epsilon=1e-6, **kwargs):
super(LayerNormalization, self).__init__(**kwargs)
self.axis = to_list(axis)
self.gamma_init = initializers.get(gamma_init)
self.beta_init = initializers.get(beta_init)
self.gamma_regularizer = regularizers.get(gamma_regularizer)
self.beta_regularizer = regularizers.get(beta_regularizer)
self.epsilon = epsilon
self.supports_masking = True
def build(self, input_shape):
self.input_spec = [InputSpec(shape=input_shape)]
shape = [1 for _ in input_shape]
for i in self.axis:
shape[i] = input_shape[i]
self.gamma = self.add_weight(shape=shape,
initializer=self.gamma_init,
regularizer=self.gamma_regularizer,
name='gamma')
self.beta = self.add_weight(shape=shape,
initializer=self.beta_init,
regularizer=self.beta_regularizer,
name='beta')
self.built = True
def call(self, inputs, mask=None):
return LN(inputs, gamma=self.gamma, beta=self.beta,
axis=self.axis, epsilon=self.epsilon)
def get_config(self):
config = {'epsilon': self.epsilon,
'axis': self.axis,
'gamma_init': initializers.serialize(self.gamma_init),
'beta_init': initializers.serialize(self.beta_init),
'gamma_regularizer': regularizers.serialize(self.gamma_regularizer),
'beta_regularizer': regularizers.serialize(self.gamma_regularizer)}
base_config = super(LayerNormalization, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
class LayerNormLSTM(LSTM):
def build(self, input_shape):
if isinstance(input_shape, list):
input_shape = input_shape[0]
batch_size = input_shape[0] if self.stateful else None
self.input_dim = input_shape[2]
self.input_spec = InputSpec(shape=(batch_size, None, self.input_dim))
self.state_spec = [InputSpec(shape=(batch_size, self.units)),
InputSpec(shape=(batch_size, self.units))]
# initial states: 2 all-zero tensors of shape (units)
self.states = [None, None]
if self.stateful:
self.reset_states()
self.kernel = self.add_weight(shape=(self.input_dim, 4 * self.units),
initializer=self.kernel_initializer,
name='kernel',
regularizer=self.kernel_regularizer,
constraint=self.kernel_constraint)
self.recurrent_kernel = self.add_weight(shape=(self.units, self.units * 4),
name='recurrent_kernel',
initializer=self.recurrent_initializer,
regularizer=self.recurrent_regularizer,
constraint=self.recurrent_constraint)
self.gamma_1 = self.add_weight(shape=(4 * self.units,),
initializer='one',
name='gamma_1')
self.beta_1 = self.add_weight(shape=(4 * self.units,),
initializer='zero',
name='beta_1')
self.gamma_2 = self.add_weight(shape=(4 * self.units,),
initializer='one',
name='gamma_2')
self.beta_2 = self.add_weight(shape=(4 * self.units,),
initializer='zero',
name='beta_2')
self.gamma_3 = self.add_weight(shape=(self.units,),
initializer='one',
name='gamma_3')
self.beta_3 = self.add_weight((self.units,),
initializer='zero',
name='beta_3')
if self.use_bias:
if self.unit_forget_bias:
def bias_initializer(shape, *args, **kwargs):
return K.concatenate([
self.bias_initializer((self.units,), *args, **kwargs),
initializers.Ones()((self.units,), *args, **kwargs),
self.bias_initializer((self.units * 2,), *args, **kwargs),
])
else:
bias_initializer = self.bias_initializer
self.bias = self.add_weight(shape=(self.units * 4,),
name='bias',
initializer=bias_initializer,
regularizer=self.bias_regularizer,
constraint=self.bias_constraint)
else:
self.bias = None
self.built = True
def preprocess_input(self, inputs, training=None):
return inputs
def step(self, x, states):
h_tm1 = states[0]
c_tm1 = states[1]
B_U = states[2]
B_W = states[3]
z = LN(K.dot(x * B_W[0], self.kernel), self.gamma_1, self.beta_1) + \
LN(K.dot(h_tm1 * B_U[0], self.recurrent_kernel), self.gamma_2, self.beta_2)
if self.use_bias:
z = K.bias_add(z, self.bias)
z0 = z[:, :self.units]
z1 = z[:, self.units: 2 * self.units]
z2 = z[:, 2 * self.units: 3 * self.units]
z3 = z[:, 3 * self.units:]
i = self.recurrent_activation(z0)
f = self.recurrent_activation(z1)
c = f * c_tm1 + i * self.activation(z2)
o = self.recurrent_activation(z3)
h = o * self.activation(LN(c, self.gamma_3, self.beta_3))
return h, [h, c]
| 41.549383
| 87
| 0.522805
|
acfebe2f63060b6505d32c4dc6920f1e5effe402
| 864
|
py
|
Python
|
news-notifier/news.py
|
sudhanshu-jha/Scrapers
|
1203c5ed3ebb4b0664af41e95bde3fc15662af64
|
[
"MIT"
] | null | null | null |
news-notifier/news.py
|
sudhanshu-jha/Scrapers
|
1203c5ed3ebb4b0664af41e95bde3fc15662af64
|
[
"MIT"
] | null | null | null |
news-notifier/news.py
|
sudhanshu-jha/Scrapers
|
1203c5ed3ebb4b0664af41e95bde3fc15662af64
|
[
"MIT"
] | 1
|
2019-05-29T09:54:14.000Z
|
2019-05-29T09:54:14.000Z
|
"""
-*- coding: utf-8 -*-
========================
Python Desktop News Notifier
========================
"""
import feedparser
import notify2
import time
import os
def Parsefeed():
f = feedparser.parse("https://www.thehindubusinessline.com/feeder/default.rss")
# f = feedparser.parse("https://www.coindesk.com/feed/")
ICON_PATH = os.getcwd() + "/icon.ico"
notify2.init("News Notify")
for newsitem in f["items"]:
# print(newsitem['title'])
# print(newsitem['summary'])
# print(newsitem['link'])
# print('\n')
n = notify2.Notification(newsitem["title"], newsitem["summary"], icon=ICON_PATH)
n.set_urgency(notify2.URGENCY_NORMAL)
n.show()
n.set_timeout(15000)
time.sleep(10)
if __name__ == "__main__":
try:
Parsefeed()
except:
print("Error")
| 21.6
| 88
| 0.571759
|
acfebe3683f6c65f0c5ea17d2902e383b907b16a
| 6,092
|
py
|
Python
|
saleor/graphql/core/utils/__init__.py
|
victor-abz/saleor
|
f8e2b49703d995d4304d5a690dbe9c83631419d0
|
[
"CC-BY-4.0"
] | 1
|
2022-03-22T02:54:38.000Z
|
2022-03-22T02:54:38.000Z
|
saleor/graphql/core/utils/__init__.py
|
victor-abz/saleor
|
f8e2b49703d995d4304d5a690dbe9c83631419d0
|
[
"CC-BY-4.0"
] | 86
|
2021-11-01T04:51:55.000Z
|
2022-03-30T16:30:16.000Z
|
saleor/graphql/core/utils/__init__.py
|
victor-abz/saleor
|
f8e2b49703d995d4304d5a690dbe9c83631419d0
|
[
"CC-BY-4.0"
] | 1
|
2021-12-28T18:02:49.000Z
|
2021-12-28T18:02:49.000Z
|
import binascii
import os
import secrets
from typing import TYPE_CHECKING, Type, Union
from uuid import UUID
import graphene
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from graphene import ObjectType
from graphql.error import GraphQLError
from PIL import Image
from ....core.utils import generate_unique_slug
from ....plugins.webhook.utils import APP_ID_PREFIX
if TYPE_CHECKING:
# flake8: noqa
from django.db.models import Model
Image.init()
def clean_seo_fields(data):
"""Extract and assign seo fields to given dictionary."""
seo_fields = data.pop("seo", None)
if seo_fields:
data["seo_title"] = seo_fields.get("title")
data["seo_description"] = seo_fields.get("description")
def snake_to_camel_case(name):
"""Convert snake_case variable name to camelCase."""
if isinstance(name, str):
split_name = name.split("_")
return split_name[0] + "".join(map(str.capitalize, split_name[1:]))
return name
def str_to_enum(name):
"""Create an enum value from a string."""
return name.replace(" ", "_").replace("-", "_").upper()
def validate_image_file(file, field_name, error_class):
"""Validate if the file is an image."""
if not file:
raise ValidationError(
{
field_name: ValidationError(
"File is required.", code=error_class.REQUIRED
)
}
)
if not file.content_type.startswith("image/"):
raise ValidationError(
{
field_name: ValidationError(
"Invalid file type.", code=error_class.INVALID
)
}
)
_validate_image_format(file, field_name, error_class)
def _validate_image_format(file, field_name, error_class):
"""Validate image file format."""
allowed_extensions = [ext.lower() for ext in Image.EXTENSION]
_file_name, format = os.path.splitext(file._name)
if not format:
raise ValidationError(
{
field_name: ValidationError(
"Lack of file extension.", code=error_class.INVALID
)
}
)
elif format not in allowed_extensions:
raise ValidationError(
{
field_name: ValidationError(
"Invalid file extension. Image file required.",
code=error_class.INVALID,
)
}
)
def validate_slug_and_generate_if_needed(
instance: Type["Model"],
slugable_field: str,
cleaned_input: dict,
slug_field_name: str = "slug",
) -> dict:
"""Validate slug from input and generate in create mutation if is not given."""
# update mutation - just check if slug value is not empty
# _state.adding is True only when it's new not saved instance.
if not instance._state.adding: # type: ignore
validate_slug_value(cleaned_input)
return cleaned_input
# create mutation - generate slug if slug value is empty
slug = cleaned_input.get(slug_field_name)
if not slug and slugable_field in cleaned_input:
slug = generate_unique_slug(instance, cleaned_input[slugable_field])
cleaned_input[slug_field_name] = slug
return cleaned_input
def validate_slug_value(cleaned_input, slug_field_name: str = "slug"):
if slug_field_name in cleaned_input:
slug = cleaned_input[slug_field_name]
if not slug:
raise ValidationError(
f"{slug_field_name.capitalize()} value cannot be blank."
)
def get_duplicates_items(first_list, second_list):
"""Return items that appear on both provided lists."""
if first_list and second_list:
return set(first_list) & set(second_list)
return []
def get_duplicated_values(values):
"""Return set of duplicated values."""
return {value for value in values if values.count(value) > 1}
def validate_required_string_field(cleaned_input, field_name: str):
"""Strip and validate field value."""
field_value = cleaned_input.get(field_name)
field_value = field_value.strip() if field_value else ""
if field_value:
cleaned_input[field_name] = field_value
else:
raise ValidationError(f"{field_name.capitalize()} is required.")
return cleaned_input
def validate_if_int_or_uuid(id):
result = True
try:
int(id)
except ValueError:
try:
UUID(id)
except (AttributeError, ValueError):
result = False
return result
def from_global_id_or_error(
global_id: str, only_type: Union[ObjectType, str] = None, raise_error: bool = False
):
"""Resolve global ID or raise GraphQLError.
Validates if given ID is a proper ID handled by Saleor.
Valid IDs formats, base64 encoded:
'app:<int>:<str>' : External app ID with 'app' prefix
'<type>:<int>' : Internal ID containing object type and ID as integer
'<type>:<UUID>' : Internal ID containing object type and UUID
Optionally validate the object type, if `only_type` is provided,
raise GraphQLError when `raise_error` is set to True.
"""
try:
type_, id_ = graphene.Node.from_global_id(global_id)
except (binascii.Error, UnicodeDecodeError, ValueError):
raise GraphQLError(f"Couldn't resolve id: {global_id}.")
if type_ == APP_ID_PREFIX:
id_ = global_id
else:
if not validate_if_int_or_uuid(id_):
raise GraphQLError(f"Error occurred during ID - {global_id} validation.")
if only_type and str(type_) != str(only_type):
if not raise_error:
return type_, None
raise GraphQLError(f"Must receive a {only_type} id.")
return type_, id_
def add_hash_to_file_name(file):
"""Add unique text fragment to the file name to prevent file overriding."""
file_name, format = os.path.splitext(file._name)
hash = secrets.token_hex(nbytes=4)
new_name = f"{file_name}_{hash}{format}"
file._name = new_name
| 31.729167
| 87
| 0.657584
|
acfebe91af6e9fd4bcc2950ff95a64d538fedf93
| 150
|
py
|
Python
|
clientLogic/__init__.py
|
JoelEager/pyTanks.Player
|
a35a653e9df2416c63204aba87a95f33e6815b63
|
[
"MIT"
] | 2
|
2017-03-09T15:32:55.000Z
|
2017-09-04T11:25:41.000Z
|
clientLogic/__init__.py
|
JoelEager/pyTanks.Player
|
a35a653e9df2416c63204aba87a95f33e6815b63
|
[
"MIT"
] | null | null | null |
clientLogic/__init__.py
|
JoelEager/pyTanks.Player
|
a35a653e9df2416c63204aba87a95f33e6815b63
|
[
"MIT"
] | 4
|
2017-05-16T15:10:09.000Z
|
2017-07-06T15:24:50.000Z
|
"""
Contains all the logic for running the player client (websocket io, game clock, gameState data extrapolation, player
commands API, and so on)
"""
| 37.5
| 117
| 0.76
|
acfebe95cdaebb9c774b7f3027cbccfd999321bd
| 3,938
|
py
|
Python
|
keystone/tests/unit/auth/test_controllers.py
|
Afkupuz/4jaewoo
|
fc69258feac7858f5af99d2feab39c86ceb70203
|
[
"Apache-2.0"
] | 1
|
2019-05-08T06:09:35.000Z
|
2019-05-08T06:09:35.000Z
|
keystone/tests/unit/auth/test_controllers.py
|
Afkupuz/4jaewoo
|
fc69258feac7858f5af99d2feab39c86ceb70203
|
[
"Apache-2.0"
] | 4
|
2018-08-22T14:51:02.000Z
|
2018-10-17T14:04:26.000Z
|
keystone/tests/unit/auth/test_controllers.py
|
Afkupuz/4jaewoo
|
fc69258feac7858f5af99d2feab39c86ceb70203
|
[
"Apache-2.0"
] | 5
|
2018-08-03T17:19:34.000Z
|
2019-01-11T15:54:42.000Z
|
# Copyright 2015 IBM Corp.
# 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 uuid
import fixtures
import mock
from oslo_config import cfg
from oslo_config import fixture as config_fixture
from oslo_utils import importutils
import stevedore
from stevedore import extension
from keystone.auth import core
from keystone.tests import unit
class TestLoadAuthMethod(unit.BaseTestCase):
def test_entrypoint_works(self):
method = uuid.uuid4().hex
plugin_name = self.getUniqueString()
# Register the method using the given plugin
cf = self.useFixture(config_fixture.Config())
cf.register_opt(cfg.StrOpt(method), group='auth')
cf.config(group='auth', **{method: plugin_name})
# Setup stevedore.DriverManager to return a driver for the plugin
extension_ = extension.Extension(
plugin_name, entry_point=mock.sentinel.entry_point,
plugin=mock.sentinel.plugin,
obj=mock.sentinel.driver)
auth_plugin_namespace = 'keystone.auth.%s' % method
fake_driver_manager = stevedore.DriverManager.make_test_instance(
extension_, namespace=auth_plugin_namespace)
driver_manager_mock = self.useFixture(fixtures.MockPatchObject(
stevedore, 'DriverManager', return_value=fake_driver_manager)).mock
driver = core.load_auth_method(method)
self.assertEqual(auth_plugin_namespace, fake_driver_manager.namespace)
driver_manager_mock.assert_called_once_with(
auth_plugin_namespace, plugin_name, invoke_on_load=True)
self.assertIs(mock.sentinel.driver, driver)
def test_entrypoint_fails_import_works(self):
method = uuid.uuid4().hex
plugin_name = self.getUniqueString()
# Register the method using the given plugin
cf = self.useFixture(config_fixture.Config())
cf.register_opt(cfg.StrOpt(method), group='auth')
cf.config(group='auth', **{method: plugin_name})
# stevedore.DriverManager raises RuntimeError if it can't load the
# driver.
self.useFixture(fixtures.MockPatchObject(
stevedore, 'DriverManager', side_effect=RuntimeError))
self.useFixture(fixtures.MockPatchObject(
importutils, 'import_object', return_value=mock.sentinel.driver))
log_fixture = self.useFixture(fixtures.FakeLogger())
driver = core.load_auth_method(method)
# Loading entrypoint fails
self.assertIn('Direct import of auth plugin', log_fixture.output)
# Import works
self.assertIs(mock.sentinel.driver, driver)
def test_entrypoint_fails_import_fails(self):
method = uuid.uuid4().hex
plugin_name = self.getUniqueString()
# Register the method using the given plugin
cf = self.useFixture(config_fixture.Config())
cf.register_opt(cfg.StrOpt(method), group='auth')
cf.config(group='auth', **{method: plugin_name})
# stevedore.DriverManager raises RuntimeError if it can't load the
# driver.
self.useFixture(fixtures.MockPatchObject(
stevedore, 'DriverManager', side_effect=RuntimeError))
class TestException(Exception):
pass
self.useFixture(fixtures.MockPatchObject(
importutils, 'import_object', side_effect=TestException))
self.assertRaises(TestException, core.load_auth_method, method)
| 37.150943
| 79
| 0.706704
|
acfebeb50fe77e64e6d96b6d3cd9aa326a98e9c1
| 21,683
|
py
|
Python
|
pytorch3d/io/obj_io.py
|
anuragranj/pytorch3d
|
cdaac5f9c592234e89afbcb7eab88ceb3b4ce816
|
[
"BSD-3-Clause"
] | 1
|
2020-09-06T15:03:10.000Z
|
2020-09-06T15:03:10.000Z
|
pytorch3d/io/obj_io.py
|
anuragranj/pytorch3d
|
cdaac5f9c592234e89afbcb7eab88ceb3b4ce816
|
[
"BSD-3-Clause"
] | null | null | null |
pytorch3d/io/obj_io.py
|
anuragranj/pytorch3d
|
cdaac5f9c592234e89afbcb7eab88ceb3b4ce816
|
[
"BSD-3-Clause"
] | 1
|
2020-05-25T07:19:08.000Z
|
2020-05-25T07:19:08.000Z
|
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
"""This module implements utility functions for loading and saving meshes."""
import os
import warnings
from collections import namedtuple
from typing import Optional
import numpy as np
import torch
from pytorch3d.io.mtl_io import load_mtl, make_mesh_texture_atlas
from pytorch3d.io.utils import _open_file
from pytorch3d.structures import Meshes, Textures, join_meshes_as_batch
def _make_tensor(data, cols: int, dtype: torch.dtype, device="cpu") -> torch.Tensor:
"""
Return a 2D tensor with the specified cols and dtype filled with data,
even when data is empty.
"""
if not data:
return torch.zeros((0, cols), dtype=dtype, device=device)
return torch.tensor(data, dtype=dtype, device=device)
# Faces & Aux type returned from load_obj function.
_Faces = namedtuple("Faces", "verts_idx normals_idx textures_idx materials_idx")
_Aux = namedtuple(
"Properties", "normals verts_uvs material_colors texture_images texture_atlas"
)
def _format_faces_indices(faces_indices, max_index, device, pad_value=None):
"""
Format indices and check for invalid values. Indices can refer to
values in one of the face properties: vertices, textures or normals.
See comments of the load_obj function for more details.
Args:
faces_indices: List of ints of indices.
max_index: Max index for the face property.
Returns:
faces_indices: List of ints of indices.
Raises:
ValueError if indices are not in a valid range.
"""
faces_indices = _make_tensor(
faces_indices, cols=3, dtype=torch.int64, device=device
)
if pad_value:
mask = faces_indices.eq(pad_value).all(-1)
# Change to 0 based indexing.
faces_indices[(faces_indices > 0)] -= 1
# Negative indexing counts from the end.
faces_indices[(faces_indices < 0)] += max_index
if pad_value:
faces_indices[mask] = pad_value
# Check indices are valid.
if torch.any(faces_indices >= max_index) or torch.any(faces_indices < 0):
warnings.warn("Faces have invalid indices")
return faces_indices
def load_obj(
f,
load_textures=True,
create_texture_atlas: bool = False,
texture_atlas_size: int = 4,
texture_wrap: Optional[str] = "repeat",
device="cpu",
):
"""
Load a mesh from a .obj file and optionally textures from a .mtl file.
Currently this handles verts, faces, vertex texture uv coordinates, normals,
texture images and material reflectivity values.
Note .obj files are 1-indexed. The tensors returned from this function
are 0-indexed. OBJ spec reference: http://www.martinreddy.net/gfx/3d/OBJ.spec
Example .obj file format:
::
# this is a comment
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -1.000000
vt 0.748573 0.750412
vt 0.749279 0.501284
vt 0.999110 0.501077
vt 0.999455 0.750380
vn 0.000000 0.000000 -1.000000
vn -1.000000 -0.000000 -0.000000
vn -0.000000 -0.000000 1.000000
f 5/2/1 1/2/1 4/3/1
f 5/1/1 4/3/1 2/4/1
The first character of the line denotes the type of input:
::
- v is a vertex
- vt is the texture coordinate of one vertex
- vn is the normal of one vertex
- f is a face
Faces are interpreted as follows:
::
5/2/1 describes the first vertex of the first triange
- 5: index of vertex [1.000000 1.000000 -1.000000]
- 2: index of texture coordinate [0.749279 0.501284]
- 1: index of normal [0.000000 0.000000 -1.000000]
If there are faces with more than 3 vertices
they are subdivided into triangles. Polygonal faces are assummed to have
vertices ordered counter-clockwise so the (right-handed) normal points
out of the screen e.g. a proper rectangular face would be specified like this:
::
0_________1
| |
| |
3 ________2
The face would be split into two triangles: (0, 2, 1) and (0, 3, 2),
both of which are also oriented counter-clockwise and have normals
pointing out of the screen.
Args:
f: A file-like object (with methods read, readline, tell, and seek),
a pathlib path or a string containing a file name.
load_textures: Boolean indicating whether material files are loaded
create_texture_atlas: Bool, If True a per face texture map is created and
a tensor `texture_atlas` is also returned in `aux`.
texture_atlas_size: Int specifying the resolution of the texture map per face
when `create_texture_atlas=True`. A (texture_size, texture_size, 3)
map is created per face.
texture_wrap: string, one of ["repeat", "clamp"]. This applies when computing
the texture atlas.
If `texture_mode="repeat"`, for uv values outside the range [0, 1] the integer part
is ignored and a repeating pattern is formed.
If `texture_mode="clamp"` the values are clamped to the range [0, 1].
If None, then there is no transformation of the texture values.
device: string or torch.device on which to return the new tensors.
Returns:
6-element tuple containing
- **verts**: FloatTensor of shape (V, 3).
- **faces**: NamedTuple with fields:
- verts_idx: LongTensor of vertex indices, shape (F, 3).
- normals_idx: (optional) LongTensor of normal indices, shape (F, 3).
- textures_idx: (optional) LongTensor of texture indices, shape (F, 3).
This can be used to index into verts_uvs.
- materials_idx: (optional) List of indices indicating which
material the texture is derived from for each face.
If there is no material for a face, the index is -1.
This can be used to retrieve the corresponding values
in material_colors/texture_images after they have been
converted to tensors or Materials/Textures data
structures - see textures.py and materials.py for
more info.
- **aux**: NamedTuple with fields:
- normals: FloatTensor of shape (N, 3)
- verts_uvs: FloatTensor of shape (T, 2), giving the uv coordinate per
vertex. If a vertex is shared between two faces, it can have
a different uv value for each instance. Therefore it is
possible that the number of verts_uvs is greater than
num verts i.e. T > V.
vertex.
- material_colors: if `load_textures=True` and the material has associated
properties this will be a dict of material names and properties of the form:
.. code-block:: python
{
material_name_1: {
"ambient_color": tensor of shape (1, 3),
"diffuse_color": tensor of shape (1, 3),
"specular_color": tensor of shape (1, 3),
"shininess": tensor of shape (1)
},
material_name_2: {},
...
}
If a material does not have any properties it will have an
empty dict. If `load_textures=False`, `material_colors` will None.
- texture_images: if `load_textures=True` and the material has a texture map,
this will be a dict of the form:
.. code-block:: python
{
material_name_1: (H, W, 3) image,
...
}
If `load_textures=False`, `texture_images` will None.
- texture_atlas: if `load_textures=True` and `create_texture_atlas=True`,
this will be a FloatTensor of the form: (F, texture_size, textures_size, 3)
If the material does not have a texture map, then all faces
will have a uniform white texture. Otherwise `texture_atlas` will be
None.
"""
data_dir = "./"
if isinstance(f, (str, bytes, os.PathLike)):
# pyre-fixme[6]: Expected `_PathLike[Variable[typing.AnyStr <: [str,
# bytes]]]` for 1st param but got `Union[_PathLike[typing.Any], bytes, str]`.
data_dir = os.path.dirname(f)
with _open_file(f, "r") as f:
return _load_obj(
f,
data_dir,
load_textures=load_textures,
create_texture_atlas=create_texture_atlas,
texture_atlas_size=texture_atlas_size,
texture_wrap=texture_wrap,
device=device,
)
def load_objs_as_meshes(files: list, device=None, load_textures: bool = True):
"""
Load meshes from a list of .obj files using the load_obj function, and
return them as a Meshes object. This only works for meshes which have a
single texture image for the whole mesh. See the load_obj function for more
details. material_colors and normals are not stored.
Args:
f: A list of file-like objects (with methods read, readline, tell,
and seek), pathlib paths or strings containing file names.
device: Desired device of returned Meshes. Default:
uses the current device for the default tensor type.
load_textures: Boolean indicating whether material files are loaded
Returns:
New Meshes object.
"""
mesh_list = []
for f_obj in files:
# TODO: update this function to support the two texturing options.
verts, faces, aux = load_obj(f_obj, load_textures=load_textures)
verts = verts.to(device)
tex = None
tex_maps = aux.texture_images
if tex_maps is not None and len(tex_maps) > 0:
verts_uvs = aux.verts_uvs[None, ...].to(device) # (1, V, 2)
faces_uvs = faces.textures_idx[None, ...].to(device) # (1, F, 3)
image = list(tex_maps.values())[0].to(device)[None]
tex = Textures(verts_uvs=verts_uvs, faces_uvs=faces_uvs, maps=image)
mesh = Meshes(verts=[verts], faces=[faces.verts_idx.to(device)], textures=tex)
mesh_list.append(mesh)
if len(mesh_list) == 1:
return mesh_list[0]
return join_meshes_as_batch(mesh_list)
def _parse_face(
line,
material_idx,
faces_verts_idx,
faces_normals_idx,
faces_textures_idx,
faces_materials_idx,
):
face = line.split()[1:]
face_list = [f.split("/") for f in face]
face_verts = []
face_normals = []
face_textures = []
for vert_props in face_list:
# Vertex index.
face_verts.append(int(vert_props[0]))
if len(vert_props) > 1:
if vert_props[1] != "":
# Texture index is present e.g. f 4/1/1.
face_textures.append(int(vert_props[1]))
if len(vert_props) > 2:
# Normal index present e.g. 4/1/1 or 4//1.
face_normals.append(int(vert_props[2]))
if len(vert_props) > 3:
raise ValueError(
"Face vertices can ony have 3 properties. \
Face vert %s, Line: %s"
% (str(vert_props), str(line))
)
# Triplets must be consistent for all vertices in a face e.g.
# legal statement: f 4/1/1 3/2/1 2/1/1.
# illegal statement: f 4/1/1 3//1 2//1.
# If the face does not have normals or textures indices
# fill with pad value = -1. This will ensure that
# all the face index tensors will have F values where
# F is the number of faces.
if len(face_normals) > 0:
if not (len(face_verts) == len(face_normals)):
raise ValueError(
"Face %s is an illegal statement. \
Vertex properties are inconsistent. Line: %s"
% (str(face), str(line))
)
else:
face_normals = [-1] * len(face_verts) # Fill with -1
if len(face_textures) > 0:
if not (len(face_verts) == len(face_textures)):
raise ValueError(
"Face %s is an illegal statement. \
Vertex properties are inconsistent. Line: %s"
% (str(face), str(line))
)
else:
face_textures = [-1] * len(face_verts) # Fill with -1
# Subdivide faces with more than 3 vertices.
# See comments of the load_obj function for more details.
for i in range(len(face_verts) - 2):
faces_verts_idx.append((face_verts[0], face_verts[i + 1], face_verts[i + 2]))
faces_normals_idx.append(
(face_normals[0], face_normals[i + 1], face_normals[i + 2])
)
faces_textures_idx.append(
(face_textures[0], face_textures[i + 1], face_textures[i + 2])
)
faces_materials_idx.append(material_idx)
def _load_obj(
f_obj,
data_dir,
load_textures: bool = True,
create_texture_atlas: bool = False,
texture_atlas_size: int = 4,
texture_wrap: Optional[str] = "repeat",
device="cpu",
):
"""
Load a mesh from a file-like object. See load_obj function more details.
Any material files associated with the obj are expected to be in the
directory given by data_dir.
"""
if texture_wrap is not None and texture_wrap not in ["repeat", "clamp"]:
msg = "texture_wrap must be one of ['repeat', 'clamp'] or None, got %s"
raise ValueError(msg % texture_wrap)
lines = [line.strip() for line in f_obj]
verts = []
normals = []
verts_uvs = []
faces_verts_idx = []
faces_normals_idx = []
faces_textures_idx = []
material_names = []
faces_materials_idx = []
f_mtl = None
materials_idx = -1
# startswith expects each line to be a string. If the file is read in as
# bytes then first decode to strings.
if lines and isinstance(lines[0], bytes):
lines = [l.decode("utf-8") for l in lines]
for line in lines:
if line.startswith("mtllib"):
if len(line.split()) < 2:
raise ValueError("material file name is not specified")
# NOTE: only allow one .mtl file per .obj.
# Definitions for multiple materials can be included
# in this one .mtl file.
f_mtl = os.path.join(data_dir, line.split()[1])
elif len(line.split()) != 0 and line.split()[0] == "usemtl":
material_name = line.split()[1]
# materials are often repeated for different parts
# of a mesh.
if material_name not in material_names:
material_names.append(material_name)
materials_idx = len(material_names) - 1
else:
materials_idx = material_names.index(material_name)
elif line.startswith("v "):
# Line is a vertex.
vert = [float(x) for x in line.split()[1:4]]
if len(vert) != 3:
msg = "Vertex %s does not have 3 values. Line: %s"
raise ValueError(msg % (str(vert), str(line)))
verts.append(vert)
elif line.startswith("vt "):
# Line is a texture.
tx = [float(x) for x in line.split()[1:3]]
if len(tx) != 2:
raise ValueError(
"Texture %s does not have 2 values. Line: %s" % (str(tx), str(line))
)
verts_uvs.append(tx)
elif line.startswith("vn "):
# Line is a normal.
norm = [float(x) for x in line.split()[1:4]]
if len(norm) != 3:
msg = "Normal %s does not have 3 values. Line: %s"
raise ValueError(msg % (str(norm), str(line)))
normals.append(norm)
elif line.startswith("f "):
# Line is a face update face properties info.
_parse_face(
line,
materials_idx,
faces_verts_idx,
faces_normals_idx,
faces_textures_idx,
faces_materials_idx,
)
verts = _make_tensor(verts, cols=3, dtype=torch.float32, device=device) # (V, 3)
normals = _make_tensor(
normals, cols=3, dtype=torch.float32, device=device
) # (N, 3)
verts_uvs = _make_tensor(
verts_uvs, cols=2, dtype=torch.float32, device=device
) # (T, 2)
faces_verts_idx = _format_faces_indices(
faces_verts_idx, verts.shape[0], device=device
)
# Repeat for normals and textures if present.
if len(faces_normals_idx) > 0:
faces_normals_idx = _format_faces_indices(
faces_normals_idx, normals.shape[0], device=device, pad_value=-1
)
if len(faces_textures_idx) > 0:
faces_textures_idx = _format_faces_indices(
faces_textures_idx, verts_uvs.shape[0], device=device, pad_value=-1
)
if len(faces_materials_idx) > 0:
faces_materials_idx = torch.tensor(
faces_materials_idx, dtype=torch.int64, device=device
)
# Load materials
material_colors, texture_images, texture_atlas = None, None, None
if load_textures:
if (len(material_names) > 0) and (f_mtl is not None):
# pyre-fixme[6]: Expected `Union[_PathLike[typing.Any], bytes, str]` for
# 1st param but got `Optional[str]`.
if os.path.isfile(f_mtl):
# Texture mode uv wrap
material_colors, texture_images = load_mtl(
f_mtl, material_names, data_dir, device=device
)
if create_texture_atlas:
# Using the images and properties from the
# material file make a per face texture map.
# Create an array of strings of material names for each face.
# If faces_materials_idx == -1 then that face doesn't have a material.
idx = faces_materials_idx.cpu().numpy()
face_material_names = np.array(material_names)[idx] # (F,)
face_material_names[idx == -1] = ""
# Get the uv coords for each vert in each face
faces_verts_uvs = verts_uvs[faces_textures_idx] # (F, 3, 2)
# Construct the atlas.
texture_atlas = make_mesh_texture_atlas(
material_colors,
texture_images,
face_material_names,
faces_verts_uvs,
texture_atlas_size,
texture_wrap,
)
else:
warnings.warn(f"Mtl file does not exist: {f_mtl}")
elif len(material_names) > 0:
warnings.warn("No mtl file provided")
faces = _Faces(
verts_idx=faces_verts_idx,
normals_idx=faces_normals_idx,
textures_idx=faces_textures_idx,
materials_idx=faces_materials_idx,
)
aux = _Aux(
normals=normals if len(normals) > 0 else None,
verts_uvs=verts_uvs if len(verts_uvs) > 0 else None,
material_colors=material_colors,
texture_images=texture_images,
texture_atlas=texture_atlas,
)
return verts, faces, aux
def save_obj(f, verts, faces, decimal_places: Optional[int] = None):
"""
Save a mesh to an .obj file.
Args:
f: File (or path) to which the mesh should be written.
verts: FloatTensor of shape (V, 3) giving vertex coordinates.
faces: LongTensor of shape (F, 3) giving faces.
decimal_places: Number of decimal places for saving.
"""
if len(verts) and not (verts.dim() == 2 and verts.size(1) == 3):
message = "Argument 'verts' should either be empty or of shape (num_verts, 3)."
raise ValueError(message)
if len(faces) and not (faces.dim() == 2 and faces.size(1) == 3):
message = "Argument 'faces' should either be empty or of shape (num_faces, 3)."
raise ValueError(message)
with _open_file(f, "w") as f:
return _save(f, verts, faces, decimal_places)
# TODO (nikhilar) Speed up this function.
def _save(f, verts, faces, decimal_places: Optional[int] = None) -> None:
assert not len(verts) or (verts.dim() == 2 and verts.size(1) == 3)
assert not len(faces) or (faces.dim() == 2 and faces.size(1) == 3)
if not (len(verts) or len(faces)):
warnings.warn("Empty 'verts' and 'faces' arguments provided")
return
verts, faces = verts.cpu(), faces.cpu()
lines = ""
if len(verts):
if decimal_places is None:
float_str = "%f"
else:
float_str = "%" + ".%df" % decimal_places
V, D = verts.shape
for i in range(V):
vert = [float_str % verts[i, j] for j in range(D)]
lines += "v %s\n" % " ".join(vert)
if torch.any(faces >= verts.shape[0]) or torch.any(faces < 0):
warnings.warn("Faces have invalid indices")
if len(faces):
F, P = faces.shape
for i in range(F):
face = ["%d" % (faces[i, j] + 1) for j in range(P)]
if i + 1 < F:
lines += "f %s\n" % " ".join(face)
elif i + 1 == F:
# No newline at the end of the file.
lines += "f %s" % " ".join(face)
f.write(lines)
| 38.445035
| 95
| 0.593414
|
acfebf21056da813c421f8eaaea92e412bb99789
| 2,149
|
py
|
Python
|
IOC/IOC.py
|
Sunzhifeng/pypractice
|
04f3ce8a1771bb25584464d034bf2687e8060ded
|
[
"Apache-2.0"
] | null | null | null |
IOC/IOC.py
|
Sunzhifeng/pypractice
|
04f3ce8a1771bb25584464d034bf2687e8060ded
|
[
"Apache-2.0"
] | null | null | null |
IOC/IOC.py
|
Sunzhifeng/pypractice
|
04f3ce8a1771bb25584464d034bf2687e8060ded
|
[
"Apache-2.0"
] | null | null | null |
class FeatureBroker:
""" Feature Borker
"""
def __init__(self, allowReplace=False):
self.providers = {}
self.allowReplace = allowReplace
def provide(self, feature, provider, *args, **kwargs):
if not self.allowReplace:
assert not self.providers.has_key(feature), 'Duplicate feature: %r' % feature
if callable(provider):
def call(): return provider(*args, **kwargs)
else:
def call (): return provider
self.providers[feature] = call
def __getitem__(self, feature):
try:
provider = self.providers[feature]
except KeyError:
raise KeyError, 'Unknown feature named %r' % feature
return provider()
features = FeatureBroker()
""" Representation of required features and feature assertions
"""
def noAssertion(obj):
return True
def isInstanceOf(*classes):
def test(obj): return isinstance(obj, classes)
return test
def hasAttributes(*attributes):
def test(obj):
for attr in attributes:
if not hasattr(obj, attr):
return False
return True
return test
def hasMethods(*methods):
def test(obj):
for method in methods:
try:
attr = getattr(obj, method)
except AttributeError:
return False
if not callable(attr):
return False
return True
return test
class RequiredFeature(object):
""" An attribute descriptor to 'declare' required features
"""
def __init__(self, feature, assertion=noAssertion):
self.feature = feature
self.assertion = assertion
def __get__(self, obj, T):
return self.result
def __getattr__(self, name):
assert name == 'result', 'Unexpected attribute request other than "result"'
self.result = self.request()
return self.result
def request(self):
obj = features[self.feature]
assert self.assertion(obj), 'The value %r of %r does not match the specified criteria'\
% (obj, self.feature)
return obj
| 26.8625
| 95
| 0.604002
|
acfec0018490d5c43e46fce92e4baece6014af35
| 708
|
py
|
Python
|
store/migrations/0007_productgallery.py
|
sabbirhossain540/Gadget-hub
|
3b16cd61f8d224ef921bfe1056572c569bf80695
|
[
"MIT"
] | 1
|
2022-01-12T11:41:37.000Z
|
2022-01-12T11:41:37.000Z
|
store/migrations/0007_productgallery.py
|
sabbirhossain540/Gadget-hub
|
3b16cd61f8d224ef921bfe1056572c569bf80695
|
[
"MIT"
] | null | null | null |
store/migrations/0007_productgallery.py
|
sabbirhossain540/Gadget-hub
|
3b16cd61f8d224ef921bfe1056572c569bf80695
|
[
"MIT"
] | null | null | null |
# Generated by Django 3.1 on 2022-01-15 15:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('store', '0006_auto_20220115_1728'),
]
operations = [
migrations.CreateModel(
name='ProductGallery',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.ImageField(max_length=255, upload_to='store/products')),
('product', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='store.product')),
],
),
]
| 30.782609
| 126
| 0.622881
|
acfec0ff418123175e6150380a9287e14ac9678a
| 471
|
py
|
Python
|
src/core/migrations/0021_auto_20210217_0939.py
|
metabolism-of-cities/metabolism-of-cities-platform
|
6213de146b1bc7b7c2802531fdcda1e328c32c64
|
[
"MIT"
] | 4
|
2020-10-14T15:35:07.000Z
|
2022-01-13T15:31:16.000Z
|
src/core/migrations/0021_auto_20210217_0939.py
|
metabolism-of-cities/metabolism-of-cities-platform
|
6213de146b1bc7b7c2802531fdcda1e328c32c64
|
[
"MIT"
] | null | null | null |
src/core/migrations/0021_auto_20210217_0939.py
|
metabolism-of-cities/metabolism-of-cities-platform
|
6213de146b1bc7b7c2802531fdcda1e328c32c64
|
[
"MIT"
] | 2
|
2021-01-07T14:39:05.000Z
|
2022-01-18T12:31:50.000Z
|
# Generated by Django 3.1.2 on 2021-02-17 09:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0020_auto_20210215_1240'),
]
operations = [
migrations.AlterField(
model_name='materialdemand',
name='end_date',
field=models.DateField(blank=True, help_text="The end date is optional, leave blank if it's open ended", null=True),
),
]
| 24.789474
| 128
| 0.62845
|
acfec1d12c69488a50c40d349637af603e6c8a65
| 1,715
|
py
|
Python
|
python/v2.6/download_file.py
|
byagihas/googleads-dfa-reporting-samples
|
b525662330e0e2ca863458a4e530eccf868ac7eb
|
[
"Apache-2.0"
] | null | null | null |
python/v2.6/download_file.py
|
byagihas/googleads-dfa-reporting-samples
|
b525662330e0e2ca863458a4e530eccf868ac7eb
|
[
"Apache-2.0"
] | null | null | null |
python/v2.6/download_file.py
|
byagihas/googleads-dfa-reporting-samples
|
b525662330e0e2ca863458a4e530eccf868ac7eb
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example illustrates how to download a report file."""
import argparse
import sys
import dfareporting_utils
from oauth2client import client
# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument(
'report_id', type=int,
help='The ID of the report to get a file for')
argparser.add_argument(
'file_id', type=int,
help='The ID of the file to get')
def main(argv):
# Retrieve command line arguments.
flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser])
# Authenticate and construct service.
service = dfareporting_utils.setup(flags)
report_id = flags.report_id
file_id = flags.file_id
try:
# Construct the request.
request = service.files().get_media(reportId=report_id, fileId=file_id)
# Execute request and print the file contents
print request.execute()
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| 29.067797
| 78
| 0.742857
|
acfec22542ff816821b152d2a9380ac4e53231df
| 4,556
|
py
|
Python
|
src/models/train_model.py
|
jerryan999/character-recognition
|
26af66eff8d6b1d9a485335293e52a92792314b3
|
[
"MIT"
] | null | null | null |
src/models/train_model.py
|
jerryan999/character-recognition
|
26af66eff8d6b1d9a485335293e52a92792314b3
|
[
"MIT"
] | null | null | null |
src/models/train_model.py
|
jerryan999/character-recognition
|
26af66eff8d6b1d9a485335293e52a92792314b3
|
[
"MIT"
] | null | null | null |
# encoding: utf-8
import numpy as np
#from keras.callbacks import callbacks, ModelCheckpoint
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D
from keras.callbacks import ReduceLROnPlateau
from keras.optimizers import RMSprop
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from keras.models import model_from_json
from keras.models import load_model
import os
import sys
import cv2
from time import time
from pathlib import Path
# not used in this stub but often useful for finding various files
project_dir = Path(__file__).resolve().parents[2]
APPEARED_LETTERS = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z'
]
CAPTCHA_TO_CATEGORY = dict(zip(APPEARED_LETTERS, range(len(APPEARED_LETTERS))))
height, width, channel = 40, 40, 1
outout_cate_num = 33
batch_size = 50
epochs = 100
random_seed = 2
X, y = [], []
for char in APPEARED_LETTERS:
path = 'data/processed/{}'.format(char)
for img in os.listdir(path):
if not img.endswith('jpg'):
continue
img_gray = cv2.imread(path+'/'+img,cv2.IMREAD_GRAYSCALE)
img_ = np.expand_dims(img_gray,axis=2)
X.append(img_) # 增加一个dimension
y_ = to_categorical(CAPTCHA_TO_CATEGORY[char], num_classes = len(APPEARED_LETTERS))
y.append(y_)
# convert list to array
X = np.stack(X, axis=0)
y = np.array(y)
X_train, X_val, Y_train, Y_val = train_test_split(X, y, test_size = 0.1, random_state=random_seed)
# Set the CNN model
# my CNN architechture is In -> [
# [Conv2D->relu]*2 -> MaxPool2D -> Dropout]*2 -> Flatten -> Dense -> Dropout -> Out
model = Sequential()
model.add(Conv2D(filters = 32,kernel_size= (5,5),padding = 'Same',
activation ='relu', input_shape = (height, width,channel)))
model.add(Conv2D(filters = 32,kernel_size= (5,5),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.3))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(outout_cate_num, activation = "softmax"))
# look around the nn structure
model.summary()
# serialize model to JSON
# the keras model which is trained is defined as 'model' in this example
model_json = model.to_json()
with open("models/model_num.json", "w") as json_file:
json_file.write(model_json)
# Define the optimizer
# Set a learning rate annealer
optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-06, decay=0.0)
model.compile(optimizer = optimizer , loss = "categorical_crossentropy", metrics=["accuracy"])
# callbacks
learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',
patience=3,
verbose=1,
factor=0.5,
min_lr=0.01)
# With data augmentation to prevent overfitting (accuracy 0.99286)
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180)
zoom_range = 0.1, # Randomly zoom image
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip=False, # randomly flip images
vertical_flip=False) # randomly flip images
datagen.fit(X_train)
history = model.fit_generator(datagen.flow(X_train,Y_train,
batch_size=batch_size),
epochs = epochs,
validation_data = (X_val,Y_val),
verbose = 2,
steps_per_epoch=X_train.shape[0] // batch_size,
callbacks=[
learning_rate_reduction])
# serialize weights to HDF5
model.save_weights("models/model_num-{}.h5".format(time()))
| 35.317829
| 98
| 0.68108
|
acfec23bf66e4455f46bb3c4d8c7a28689491e8a
| 20,342
|
py
|
Python
|
lte/gateway/python/magma/pipelined/app/enforcement_stats.py
|
gurrapualt/magma
|
13e05788fa6c40293a58b6e03cfb394bb79fa98f
|
[
"BSD-3-Clause"
] | null | null | null |
lte/gateway/python/magma/pipelined/app/enforcement_stats.py
|
gurrapualt/magma
|
13e05788fa6c40293a58b6e03cfb394bb79fa98f
|
[
"BSD-3-Clause"
] | 34
|
2021-05-17T21:37:04.000Z
|
2022-03-22T11:29:22.000Z
|
lte/gateway/python/magma/pipelined/app/enforcement_stats.py
|
gurrapualt/magma
|
13e05788fa6c40293a58b6e03cfb394bb79fa98f
|
[
"BSD-3-Clause"
] | null | null | null |
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
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 typing import List
from collections import defaultdict
from lte.protos.pipelined_pb2 import RuleModResult
from lte.protos.session_manager_pb2 import RuleRecord, \
RuleRecordTable
from ryu.controller import dpset, ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, set_ev_cls
from ryu.lib import hub
from ryu.ofproto.ofproto_v1_4 import OFPMPF_REPLY_MORE
from ryu.ofproto.ofproto_v1_4_parser import OFPFlowStats
from magma.pipelined.app.base import MagmaController, ControllerType, \
global_epoch
from magma.pipelined.app.policy_mixin import PolicyMixin
from magma.pipelined.openflow import messages, flows
from magma.pipelined.openflow.exceptions import MagmaOFError
from magma.pipelined.imsi import decode_imsi, encode_imsi
from magma.pipelined.openflow.magma_match import MagmaMatch
from magma.pipelined.openflow.messages import MsgChannel, MessageHub
from magma.pipelined.openflow.registers import Direction, DIRECTION_REG, \
IMSI_REG, RULE_VERSION_REG, SCRATCH_REGS
ETH_FRAME_SIZE_BYTES = 14
PROCESS_STATS = 0x0
IGNORE_STATS = 0x1
class EnforcementStatsController(PolicyMixin, MagmaController):
"""
This openflow controller installs flows for aggregating policy usage
statistics, which are sent to sessiond for tracking.
It periodically polls OVS for flow stats on the its table and reports the
usage records to session manager via RPC. Flows are deleted when their
version (reg4 match) is different from the current version of the rule for
the subscriber maintained by the rule version mapper.
"""
APP_NAME = 'enforcement_stats'
APP_TYPE = ControllerType.LOGICAL
SESSIOND_RPC_TIMEOUT = 10
# 0xffffffffffffffff is reserved in openflow
DEFAULT_FLOW_COOKIE = 0xfffffffffffffffe
_CONTEXTS = {
'dpset': dpset.DPSet,
}
def __init__(self, *args, **kwargs):
super(EnforcementStatsController, self).__init__(*args, **kwargs)
self.tbl_num = self._service_manager.get_table_num(self.APP_NAME)
self.next_table = \
self._service_manager.get_next_table_num(self.APP_NAME)
self.dpset = kwargs['dpset']
self.loop = kwargs['loop']
# Spawn a thread to poll for flow stats
poll_interval = kwargs['config']['enforcement']['poll_interval']
# Create a rpc channel to sessiond
self.sessiond = kwargs['rpc_stubs']['sessiond']
self._msg_hub = MessageHub(self.logger)
self.unhandled_stats_msgs = [] # Store multi-part responses from ovs
self.total_usage = {} # Store total usage
# Store last usage excluding deleted flows for calculating deltas
self.last_usage_for_delta = {}
self.failed_usage = {} # Store failed usage to retry rpc to sessiond
self._unmatched_bytes = 0 # Store bytes matched by default rule if any
self._clean_restart = kwargs['config']['clean_restart']
self.flow_stats_thread = hub.spawn(self._monitor, poll_interval)
def delete_all_flows(self, datapath):
flows.delete_all_flows_from_table(datapath, self.tbl_num)
def cleanup_state(self):
"""
When we remove/reinsert flows we need to remove old usage maps as new
flows will have reset stat counters
"""
self.unhandled_stats_msgs = []
self.total_usage = {}
self.last_usage_for_delta = {}
self.failed_usage = {}
self._unmatched_bytes = 0
def initialize_on_connect(self, datapath):
"""
Install the default flows on datapath connect event.
Args:
datapath: ryu datapath struct
"""
self._datapath = datapath
def _install_default_flows_if_not_installed(self, datapath,
existing_flows: List[OFPFlowStats]) -> List[OFPFlowStats]:
"""
Install default flows(if not already installed) to forward the traffic,
If no other flows are matched.
Returns:
The list of flows that remain after inserting default flows
"""
match = MagmaMatch()
msg = flows.get_add_resubmit_next_service_flow_msg(
datapath, self.tbl_num, match, [],
priority=flows.MINIMUM_PRIORITY,
resubmit_table=self.next_table,
cookie=self.DEFAULT_FLOW_COOKIE)
msg, remaining_flows = \
self._msg_hub.filter_msgs_if_not_in_flow_list([msg], existing_flows)
if msg:
chan = self._msg_hub.send(msg, datapath)
self._wait_for_responses(chan, 1)
return remaining_flows
def cleanup_on_disconnect(self, datapath):
"""
Cleanup flows on datapath disconnect event.
Args:
datapath: ryu datapath struct
"""
if self._clean_restart:
self.delete_all_flows(datapath)
def _install_flow_for_rule(self, imsi, ip_addr, apn_ambr, rule):
"""
Install a flow to get stats for a particular rule. Flows will match on
IMSI, cookie (the rule num), in/out direction
Args:
imsi (string): subscriber to install rule for
ip_addr (string): subscriber session ipv4 address
rule (PolicyRule): policy rule proto
"""
def fail(err):
self.logger.error(
"Failed to install rule %s for subscriber %s: %s",
rule.id, imsi, err)
return RuleModResult.FAILURE
msgs = self._get_rule_match_flow_msgs(imsi, ip_addr, apn_ambr, rule)
chan = self._msg_hub.send(msgs, self._datapath)
for _ in range(len(msgs)):
try:
result = chan.get()
except MsgChannel.Timeout:
return fail("No response from OVS")
if not result.ok():
return fail(result.exception())
return RuleModResult.SUCCESS
@set_ev_cls(ofp_event.EventOFPBarrierReply, MAIN_DISPATCHER)
def _handle_barrier(self, ev):
self._msg_hub.handle_barrier(ev)
@set_ev_cls(ofp_event.EventOFPErrorMsg, MAIN_DISPATCHER)
def _handle_error(self, ev):
self._msg_hub.handle_error(ev)
# pylint: disable=protected-access,unused-argument
def _get_rule_match_flow_msgs(self, imsi, ip_addr, ambr, rule):
"""
Returns flow add messages used for rule matching.
"""
rule_num = self._rule_mapper.get_or_create_rule_num(rule.id)
version = self._session_rule_version_mapper.get_version(imsi, rule.id)
self.logger.debug(
'Installing flow for %s with rule num %s (version %s)', imsi,
rule_num, version)
inbound_rule_match = _generate_rule_match(imsi, rule_num, version,
Direction.IN)
outbound_rule_match = _generate_rule_match(imsi, rule_num, version,
Direction.OUT)
inbound_rule_match._match_kwargs[SCRATCH_REGS[1]] = PROCESS_STATS
outbound_rule_match._match_kwargs[SCRATCH_REGS[1]] = PROCESS_STATS
msgs = [
flows.get_add_resubmit_next_service_flow_msg(
self._datapath,
self.tbl_num,
inbound_rule_match,
[],
priority=flows.DEFAULT_PRIORITY,
cookie=rule_num,
resubmit_table=self.next_table),
flows.get_add_resubmit_next_service_flow_msg(
self._datapath,
self.tbl_num,
outbound_rule_match,
[],
priority=flows.DEFAULT_PRIORITY,
cookie=rule_num,
resubmit_table=self.next_table),
]
if rule.app_name:
inbound_rule_match._match_kwargs[SCRATCH_REGS[1]] = IGNORE_STATS
outbound_rule_match._match_kwargs[SCRATCH_REGS[1]] = IGNORE_STATS
msgs.extend([
flows.get_add_resubmit_next_service_flow_msg(
self._datapath,
self.tbl_num,
inbound_rule_match,
[],
priority=flows.DEFAULT_PRIORITY,
cookie=rule_num,
resubmit_table=self.next_table),
flows.get_add_resubmit_next_service_flow_msg(
self._datapath,
self.tbl_num,
outbound_rule_match,
[],
priority=flows.DEFAULT_PRIORITY,
cookie=rule_num,
resubmit_table=self.next_table),
])
return msgs
def _get_default_flow_msg_for_subscriber(self, _):
return None
def _install_redirect_flow(self, imsi, ip_addr, rule):
pass
def _install_default_flow_for_subscriber(self, imsi):
pass
def get_policy_usage(self, fut):
record_table = RuleRecordTable(
records=self.total_usage.values(),
epoch=global_epoch)
fut.set_result(record_table)
def _monitor(self, poll_interval):
"""
Main thread that sends a stats request at the configured interval in
seconds.
"""
while True:
for _, datapath in self.dpset.get_all():
if self.init_finished:
self._poll_stats(datapath)
else:
# Still send an empty report -> needed for pipelined setup
self._report_usage({})
hub.sleep(poll_interval)
def _poll_stats(self, datapath):
"""
Send a FlowStatsRequest message to the datapath
"""
ofproto, parser = datapath.ofproto, datapath.ofproto_parser
req = parser.OFPFlowStatsRequest(
datapath,
table_id=self.tbl_num,
out_group=ofproto.OFPG_ANY,
out_port=ofproto.OFPP_ANY,
)
try:
messages.send_msg(datapath, req)
except MagmaOFError as e:
self.logger.warning("Couldn't poll datapath stats: %s", e)
@set_ev_cls(ofp_event.EventOFPFlowStatsReply, MAIN_DISPATCHER)
def _flow_stats_reply_handler(self, ev):
"""
Schedule the flow stats handling in the main event loop, so as to
unblock the ryu event loop
"""
if not self.init_finished:
self.logger.debug('Setup not finished, skipping stats reply')
return
self.unhandled_stats_msgs.append(ev.msg.body)
if ev.msg.flags == OFPMPF_REPLY_MORE:
# Wait for more multi-part responses thats received for the
# single stats request.
return
self.loop.call_soon_threadsafe(
self._handle_flow_stats, self.unhandled_stats_msgs)
self.unhandled_stats_msgs = []
def _handle_flow_stats(self, stats_msgs):
"""
Aggregate flow stats by rule, and report to session manager
"""
stat_count = sum(len(flow_stats) for flow_stats in stats_msgs)
if stat_count == 0:
return
self.logger.debug("Processing %s stats responses", len(stats_msgs))
# Aggregate flows into rule records
current_usage = defaultdict(RuleRecord)
for flow_stats in stats_msgs:
self.logger.debug("Processing stats of %d flows", len(flow_stats))
for stat in flow_stats:
if stat.table_id != self.tbl_num:
# this update is not intended for policy
return
current_usage = self._update_usage_from_flow_stat(
current_usage, stat)
# Calculate the delta values from last stat update
delta_usage = _delta_usage_maps(current_usage,
self.last_usage_for_delta)
self.total_usage = current_usage
# Append any records which we couldn't send to session manager earlier
delta_usage = _merge_usage_maps(delta_usage, self.failed_usage)
self.failed_usage = {}
# Send report even if usage is empty. Sessiond uses empty reports to
# recognize when flows have ended
self._report_usage(delta_usage)
self._delete_old_flows(stats_msgs)
def _report_usage(self, delta_usage):
"""
Report usage to sessiond using rpc
"""
record_table = RuleRecordTable(records=delta_usage.values(),
epoch=global_epoch)
future = self.sessiond.ReportRuleStats.future(
record_table, self.SESSIOND_RPC_TIMEOUT)
future.add_done_callback(
lambda future: self.loop.call_soon_threadsafe(
self._report_usage_done, future, delta_usage))
def _report_usage_done(self, future, delta_usage):
"""
Callback after sessiond RPC completion
"""
err = future.exception()
if err:
self.logger.error('Couldnt send flow records to sessiond: %s', err)
self.failed_usage = _merge_usage_maps(
delta_usage, self.failed_usage)
def _update_usage_from_flow_stat(self, current_usage, flow_stat):
"""
Update the rule record map with the flow stat and return the
updated map.
"""
rule_id = self._get_rule_id(flow_stat)
# Rule not found, must be default flow
if rule_id == "":
default_flow_matched = \
flow_stat.cookie == self.DEFAULT_FLOW_COOKIE and \
flow_stat.byte_count != 0 and \
self._unmatched_bytes != flow_stat.byte_count
if default_flow_matched:
self.logger.error('%s bytes total not reported.',
flow_stat.byte_count)
self._unmatched_bytes = flow_stat.byte_count
return current_usage
# If this is a pass through app name flow ignore stats
if flow_stat.match[SCRATCH_REGS[1]] == IGNORE_STATS:
return current_usage
sid = _get_sid(flow_stat)
# use a compound key to separate flows for the same rule but for
# different subscribers
key = sid + "|" + rule_id
record = current_usage[key]
record.rule_id = rule_id
record.sid = sid
if flow_stat.match[DIRECTION_REG] == Direction.IN:
# HACK decrement byte count for downlink packets by the length
# of an ethernet frame. Only IP and below should be counted towards
# a user's data. Uplink does this already because the GTP port is
# an L3 port.
record.bytes_rx += _get_downlink_byte_count(flow_stat)
else:
record.bytes_tx += flow_stat.byte_count
current_usage[key] = record
return current_usage
def _delete_old_flows(self, stats_msgs):
"""
Check if the version of any flow is older than the current version. If
so, delete the flow and update last_usage_for_delta so we calculate the
correct usage delta for the next poll.
"""
deleted_flow_usage = defaultdict(RuleRecord)
for deletable_stat in self._old_flow_stats(stats_msgs):
stat_rule_id = self._get_rule_id(deletable_stat)
stat_sid = _get_sid(deletable_stat)
rule_version = _get_version(deletable_stat)
try:
self._delete_flow(deletable_stat, stat_sid, rule_version)
# Only remove the usage of the deleted flow if deletion
# is successful.
self._update_usage_from_flow_stat(deleted_flow_usage,
deletable_stat)
except MagmaOFError as e:
self.logger.error(
'Failed to delete rule %s for subscriber %s '
'(version: %s): %s', stat_rule_id,
stat_sid, rule_version, e)
self.last_usage_for_delta = _delta_usage_maps(self.total_usage,
deleted_flow_usage)
def _old_flow_stats(self, stats_msgs):
"""
Generator function to filter the flow stats that should be deleted from
the stats messages.
"""
for flow_stats in stats_msgs:
for stat in flow_stats:
if stat.table_id != self.tbl_num:
# this update is not intended for policy
return
rule_id = self._get_rule_id(stat)
sid = _get_sid(stat)
rule_version = _get_version(stat)
if rule_id == "":
continue
current_ver = \
self._session_rule_version_mapper.get_version(sid, rule_id)
if current_ver != rule_version:
yield stat
def _delete_flow(self, flow_stat, sid, version):
cookie, mask = (
flow_stat.cookie, flows.OVS_COOKIE_MATCH_ALL)
match = _generate_rule_match(
sid, flow_stat.cookie, version,
Direction(flow_stat.match[DIRECTION_REG]))
flows.delete_flow(self._datapath,
self.tbl_num,
match,
cookie=cookie,
cookie_mask=mask)
def _get_rule_id(self, flow):
"""
Return the rule id from the rule cookie
"""
# the default rule will have a cookie of 0
rule_num = flow.cookie
if rule_num == 0 or rule_num == self.DEFAULT_FLOW_COOKIE:
return ""
try:
return self._rule_mapper.get_rule_id(rule_num)
except KeyError as e:
self.logger.error('Could not find rule id for num %d: %s',
rule_num, e)
return ""
def _generate_rule_match(imsi, rule_num, version, direction):
"""
Return a MagmaMatch that matches on the rule num and the version.
"""
return MagmaMatch(imsi=encode_imsi(imsi), direction=direction,
reg2=rule_num, rule_version=version)
def _delta_usage_maps(current_usage, last_usage):
"""
Calculate the delta between the 2 usage maps and returns a new
usage map.
"""
if len(last_usage) == 0:
return current_usage
new_usage = {}
for key, current in current_usage.items():
last = last_usage.get(key, None)
if last is not None:
rec = RuleRecord()
rec.MergeFrom(current) # copy metadata
rec.bytes_rx = current.bytes_rx - last.bytes_rx
rec.bytes_tx = current.bytes_tx - last.bytes_tx
new_usage[key] = rec
else:
new_usage[key] = current
return new_usage
def _merge_usage_maps(current_usage, last_usage):
"""
Merge the usage records from 2 map into a single map
"""
if len(last_usage) == 0:
return current_usage
new_usage = {}
for key, current in current_usage.items():
last = last_usage.get(key, None)
if last is not None:
rec = RuleRecord()
rec.MergeFrom(current) # copy metadata
rec.bytes_rx = current.bytes_rx + last.bytes_rx
rec.bytes_tx = current.bytes_tx + last.bytes_tx
new_usage[key] = rec
else:
new_usage[key] = current
return new_usage
def _get_sid(flow):
if IMSI_REG not in flow.match:
return None
return decode_imsi(flow.match[IMSI_REG])
def _get_version(flow):
if RULE_VERSION_REG not in flow.match:
return None
return flow.match[RULE_VERSION_REG]
def _get_downlink_byte_count(flow_stat):
total_bytes = flow_stat.byte_count
packet_count = flow_stat.packet_count
return total_bytes - ETH_FRAME_SIZE_BYTES * packet_count
| 37.600739
| 80
| 0.619703
|
acfec2ce63b61257adf036e6feb4fbd14478cc66
| 287
|
py
|
Python
|
Programs/completed/codons_done.py
|
AlanAloha/Learning_MCB185
|
5f88bd05a816da9a7c2430fbcb777ad49c314aee
|
[
"MIT"
] | null | null | null |
Programs/completed/codons_done.py
|
AlanAloha/Learning_MCB185
|
5f88bd05a816da9a7c2430fbcb777ad49c314aee
|
[
"MIT"
] | null | null | null |
Programs/completed/codons_done.py
|
AlanAloha/Learning_MCB185
|
5f88bd05a816da9a7c2430fbcb777ad49c314aee
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# Print out all the codons for the sequence below in reading frame 1
# Use a 'for' loop
dna = 'ATAGCGAATATCTCTCATGAGAGGGAA'
# your code goes here
for i in range(0,len(dna)-2,3):
print(dna[i:i+3])
"""
python3 codons.py
ATA
GCG
AAT
ATC
TCT
CAT
GAG
AGG
GAA
"""
| 11.958333
| 68
| 0.696864
|
acfec52bb408806344b8bf40684d96d794c780cd
| 2,840
|
py
|
Python
|
character/migrations/0014_bond_featuresandtraits_flaw_ideal_nametextcharacterfield_personalitytrait.py
|
scottBowles/dnd
|
a1ef333f1a865d51b5426dc4b3493e8437584565
|
[
"MIT"
] | null | null | null |
character/migrations/0014_bond_featuresandtraits_flaw_ideal_nametextcharacterfield_personalitytrait.py
|
scottBowles/dnd
|
a1ef333f1a865d51b5426dc4b3493e8437584565
|
[
"MIT"
] | null | null | null |
character/migrations/0014_bond_featuresandtraits_flaw_ideal_nametextcharacterfield_personalitytrait.py
|
scottBowles/dnd
|
a1ef333f1a865d51b5426dc4b3493e8437584565
|
[
"MIT"
] | null | null | null |
# Generated by Django 3.2.5 on 2021-08-18 00:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('character', '0013_auto_20210818_0049'),
]
operations = [
migrations.CreateModel(
name='NameTextCharacterField',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(default='', max_length=500)),
('text', models.TextField(default='')),
('character', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='character.character')),
],
),
migrations.CreateModel(
name='Bond',
fields=[
('nametextcharacterfield_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='character.nametextcharacterfield')),
],
bases=('character.nametextcharacterfield',),
),
migrations.CreateModel(
name='FeaturesAndTraits',
fields=[
('nametextcharacterfield_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='character.nametextcharacterfield')),
],
options={
'verbose_name_plural': 'features and traits',
},
bases=('character.nametextcharacterfield',),
),
migrations.CreateModel(
name='Flaw',
fields=[
('nametextcharacterfield_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='character.nametextcharacterfield')),
],
bases=('character.nametextcharacterfield',),
),
migrations.CreateModel(
name='Ideal',
fields=[
('nametextcharacterfield_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='character.nametextcharacterfield')),
],
bases=('character.nametextcharacterfield',),
),
migrations.CreateModel(
name='PersonalityTrait',
fields=[
('nametextcharacterfield_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='character.nametextcharacterfield')),
],
bases=('character.nametextcharacterfield',),
),
]
| 45.806452
| 225
| 0.628169
|
acfec5477e23ff4d5fd3ad3e2abdeb459f864e7c
| 1,197
|
py
|
Python
|
court_scraper/platforms/odyssey/pages/portal.py
|
ericjohannes/court-scraper
|
0ff73683d3facc2178d7bcbda67ab62ee35d62e4
|
[
"0BSD"
] | 30
|
2020-09-08T23:59:34.000Z
|
2022-03-24T03:02:47.000Z
|
court_scraper/platforms/odyssey/pages/portal.py
|
ericjohannes/court-scraper
|
0ff73683d3facc2178d7bcbda67ab62ee35d62e4
|
[
"0BSD"
] | 111
|
2020-09-16T23:42:40.000Z
|
2022-02-19T01:25:55.000Z
|
court_scraper/platforms/odyssey/pages/portal.py
|
ericjohannes/court-scraper
|
0ff73683d3facc2178d7bcbda67ab62ee35d62e4
|
[
"0BSD"
] | 9
|
2020-10-05T13:19:03.000Z
|
2021-12-11T12:12:13.000Z
|
from selenium.webdriver.common.by import By
from court_scraper.base.selenium_helpers import SeleniumHelpers
class PortalPageLocators:
PORTAL_BUTTONS = (By.CSS_SELECTOR, '.portlet-buttons')
IMAGES = (By.TAG_NAME, 'img')
class PortalPage(SeleniumHelpers):
locators = PortalPageLocators
@property
def is_current_page(self):
return len(
self.driver.find_elements(*self.locators.PORTAL_BUTTONS)
) > 0
def go_to_hearings_search(self):
self._click_port_button('hearings')
def go_to_smart_search(self):
self._click_port_button('smart_search')
def _click_port_button(self, name):
images = self.driver.find_elements(*self.locators.IMAGES)
img_names = {
'hearings': 'Icon_SearchHearing.svg',
'smart_search': 'Icon_SmartSearch.svg'
}
image_name = img_names['smart_search']
button = None
for img in images:
src = img.get_attribute('src')
if src.endswith(image_name):
# If image matches, get parent anchor tag
button = img.find_element_by_xpath('..')
break
button.click()
| 27.837209
| 68
| 0.638262
|
acfec5bc7e4efcee44459b8671da818414664344
| 4,079
|
py
|
Python
|
settings.py
|
wekko/bove
|
8f89e00f7367bc6e86783e3c3fea50b800df57c9
|
[
"MIT"
] | null | null | null |
settings.py
|
wekko/bove
|
8f89e00f7367bc6e86783e3c3fea50b800df57c9
|
[
"MIT"
] | null | null | null |
settings.py
|
wekko/bove
|
8f89e00f7367bc6e86783e3c3fea50b800df57c9
|
[
"MIT"
] | null | null | null |
class BaseSettings:
# Заполнять ниже `BotSettings`
USERS = ()
PROXIES = ()
CONF_CODE = ""
SCOPE = 140489887
APP_ID = 5982451
CAPTCHA_KEY = ""
CAPTCHA_SERVER = "rucaptcha"
READ_OUT = False
PLUGINS = ()
DEBUG = False
# Importing all the plugins to allow including to PLUGINS
from plugins import *
# Edit this settings
class BotSettings(BaseSettings):
USERS = (
("user", "aqvaweko@yandex.ru", "weko159753",),
)
PROXIES = (
# ("ADDRESS", "LOGIN", "PASSWORD", "ENCODING),
)
# Code for Callback Api (if you use it)
CONF_CODE = ""
# VK information
SCOPE = 140489887
APP_ID = 5982451
# Captcha solver's data
CAPTCHA_KEY = ""
CAPTCHA_SERVER = "rucaptcha"
# Other
READ_OUT = False
# Plugins
# Plugin's main class names must by unique!
# You can import needed plugins in any way possible by Python
# Exmaple: `from plugins.about import AboutPlugin`
#
# You can import any plugins inside `plugins` using special bot-specific package:
# from plugin import AboutPlugin
#
# You can import all plugins at once using `from plugins import *` at module-level.
prefixes = ("!", "бот ", "бот, ", "бот,")
admins = (87641997, )
hp = HelpPlugin("помощь", "команды", "?", short=False, prefixes=prefixes)
PLUGINS = (
# Leave only "PostgreSQL" or "MySQL", host is adress of your database, port is a number
# PeeweePlugin("host", "database's name", "user", "password", port, "PostgreSQL" or "MySQL"),
AdminPlugin(prefixes=prefixes, admins=admins, setadmins=True),
ChatMetaPlugin(),
# Requires `PeeweePlugin`:
# DuelerPlugin(prefixes=prefixes),
# AzinoPlugin("азино", prefixes=prefixes),
# RussianRoulettePlugin(prefixes=prefixes),
# LockChatPlugin("сохранять", prefixes=prefixes),
# Can use `PeeweePlugin`:
RememberPlugin("напомни",prefixes=prefixes), # use_db=True, if you can use PeeweePlugin
# Plugins:
VoterPlugin(prefixes=prefixes),
FacePlugin("сделай", prefixes=prefixes),
SmileWritePlugin("смайлами", prefixes=prefixes),
JokePlugin("а", "анекдот", prefixes=prefixes),
GraffitiPlugin("граффити", prefixes=prefixes),
QuotePlugin("цитатка"),
WikiPlugin("что такое", prefixes=prefixes),
AnagramsPlugin(["анаграмма", "анаграммы"], prefixes=prefixes),
HangmanPlugin(["виселица"], prefixes=prefixes),
MembersPlugin("кто тут", prefixes=prefixes),
PairPlugin("кто кого", prefixes=prefixes),
WhoIsPlugin("кто", prefixes=prefixes),
YandexNewsPlugin(["новости"], ["помощь", "категории", "?"], prefixes=prefixes),
AboutPlugin("о боте", "инфа", prefixes=prefixes),
BirthdayPlugin("дни рождения", "др", prefixes=prefixes),
TimePlugin("время", prefixes=prefixes),
ToptextbottomtextPlugin("мем", "свой текст", prefixes=prefixes),
QRCodePlugin("qr", "кр", prefixes=prefixes),
ChatKickerPlugin(["кик"], ["фри", "анкик"], prefixes=prefixes, admins=admins, admins_only=True),
RandomPostPlugin({"random": "-111759315", "memes": "-77127883", "мемы": "-77127883"}, prefixes=prefixes),
CalculatorPlugin("посчитай", "посч", prefixes=prefixes),
VideoPlugin("видео", prefixes=prefixes),
DispatchPlugin("рассылка", prefixes=prefixes, admins=admins),
hp,
# Needs tokens (see plugin's codes, some have defaults):
SayerPlugin(prefixes=prefixes),
# Audio2TextPlugin(key="token for api", prefixes=prefixes),
# WeatherPlugin("погода", token="token for api", prefixes=prefixes),
# EmotionsDetectorPlugin("лицо", key="token for api", prefixes=prefixes),
DialogflowPlugin(prefixes=prefixes), # plugin for DialogflowPlugin (chatting, learning etc)
# Plugins for bot's control
AntifloodPlugin(),
ResendCommanderPlugin(),
# ResendCheckerPlugin(),
)
hp.add_plugins(PLUGINS)
| 33.991667
| 113
| 0.640353
|
acfec5e59c71ba492e028fd57ec80483fa1ff1df
| 3,758
|
py
|
Python
|
elvis/modeling/models/cnn_bert/cnn_bert.py
|
seo-95/elvis
|
a89c759acdf6ce64c7e6863aeb68dc0ba3293fed
|
[
"Apache-2.0"
] | 1
|
2021-08-01T13:55:27.000Z
|
2021-08-01T13:55:27.000Z
|
elvis/modeling/models/cnn_bert/cnn_bert.py
|
seo-95/elvis
|
a89c759acdf6ce64c7e6863aeb68dc0ba3293fed
|
[
"Apache-2.0"
] | null | null | null |
elvis/modeling/models/cnn_bert/cnn_bert.py
|
seo-95/elvis
|
a89c759acdf6ce64c7e6863aeb68dc0ba3293fed
|
[
"Apache-2.0"
] | null | null | null |
import pdb
from typing import Dict, List, TypeVar
import timm
import torch
import torch.nn as nn
import torch.nn.functional as F
from elvis.modeling.models.build import NET_REGISTRY
from transformers import BertModel, BertTokenizer
from .dispatcher import build_data_interface
Tensor = TypeVar('torch.tensor')
class CNN_BERT(nn.Module):
"""CNN followed by Transformer
"""
def __init__(self, resnet_model, max_n_vfeat, max_n_tokens, pretrained_bert, freeze_resnet=False):
super(CNN_BERT, self).__init__()
self.max_n_pixels = max_n_vfeat
self.max_n_tokens = max_n_tokens
#resnet
fn = 'timm.models.{}'
self.resnet = eval(fn.format(resnet_model))(pretrained=True)
del self.resnet.fc
del self.resnet.global_pool
if freeze_resnet:
for param in self.resnet.parameters():
param.requires_grad = False
#bert
self.tokenizer = BertTokenizer.from_pretrained(pretrained_bert)
bert = BertModel.from_pretrained(pretrained_bert)
self.bert_encoder = bert.encoder
self.w_embeddings = bert.embeddings.word_embeddings
self.pos_embeddings = nn.Parameter(bert.embeddings.position_embeddings.weight)
self.embeddings_norm = bert.embeddings.LayerNorm
self.embeddings_drop = bert.embeddings.dropout
self.embed_dim = bert.encoder.layer[0].output.dense.out_features
self.v_mod_emb = nn.Parameter(torch.randn(1, 1, self.embed_dim))
self.t_mod_emb = nn.Parameter(torch.randn(1, 1, self.embed_dim))
self.fmaps_size = self.resnet.layer4[-1].conv3.out_channels
self.v_projection = nn.Linear(in_features=self.fmaps_size, out_features=self.embed_dim)
def forward(self, vis_in: Tensor, txt_in: Tensor, txt_mask: Tensor, vis_mask=None):
#vis_mask is set to None in order to keep compatibility with meta architecture
B_SIZE = vis_in.shape[0]
#compute visual features
fmaps = self.resnet.forward_features(vis_in)
vis_feats = fmaps.view(B_SIZE, fmaps.shape[1], -1).permute(0, 2, 1)
v_emb = self.v_projection(vis_feats) #2048 -> 768
V_LEN = vis_feats.shape[1]
vis_mask = torch.ones(B_SIZE, V_LEN).to(txt_in.device)
#prepare text embeddings
t_emb = self.w_embeddings(txt_in)
T_LEN = txt_in.shape[1]
#prepare positional and modal-aware embeddings
v_emb = self.embeddings_norm(v_emb + self.pos_embeddings[:V_LEN] + self.v_mod_emb)
t_emb = self.embeddings_norm(t_emb + self.pos_embeddings[:T_LEN] + self.t_mod_emb)
v_emb = self.embeddings_drop(v_emb)
t_emb = self.embeddings_drop(t_emb)
#build transformer input sequence and attention mask
x = torch.cat((t_emb, v_emb), dim=1)
attn_mask = torch.cat((txt_mask, vis_mask), dim=-1)
#attention mask for encoder has to be broadcastable
out = self.bert_encoder(x, attention_mask=attn_mask[:, None, None, :])
out = out['last_hidden_state']
return out
@NET_REGISTRY.register()
def build_cnn_bert_model(cfg, get_interface=None, **kwargs):
model = CNN_BERT(resnet_model=cfg.NET.RESNET_MODEL,
max_n_vfeat=cfg.MAX_N_VISUAL,
max_n_tokens=cfg.MAX_N_TOKENS,
pretrained_bert=cfg.NET.PRETRAINED_BERT,
freeze_resnet=cfg.NET.FREEZE_RESNET)
if get_interface is not None:
args_dict = {'cfg': cfg, 'tokenizer': model.tokenizer}
args_dict.update(kwargs)
interface = build_data_interface(get_interface, **args_dict)
return model, interface
| 40.408602
| 102
| 0.664715
|
acfec736fc6441070d47a84735aa127fecb0e5e8
| 1,240
|
py
|
Python
|
cp/introductory_problems/trailing_zeros.py
|
hauntarl/real-python
|
6ffb535648bf5c79c90e2ed7def842078bc7807f
|
[
"MIT"
] | 2
|
2020-12-15T18:11:00.000Z
|
2021-03-01T11:43:16.000Z
|
cp/introductory_problems/trailing_zeros.py
|
hauntarl/real_python
|
6ffb535648bf5c79c90e2ed7def842078bc7807f
|
[
"MIT"
] | null | null | null |
cp/introductory_problems/trailing_zeros.py
|
hauntarl/real_python
|
6ffb535648bf5c79c90e2ed7def842078bc7807f
|
[
"MIT"
] | null | null | null |
from util import timeit
@timeit
def trailing_zeros(n: int) -> int:
"""
[Easy] https://cses.fi/problemset/task/1618
[Help] https://www.geeksforgeeks.org/count-trailing-zeroes-factorial-number/
[Solution] https://cses.fi/paste/e30a1f7b61c0770e239417/
Your task is to calculate the number of trailing zeros in the factorial n!.
For example, 20!=2432902008176640000 and it has 4 trailing zeros.
The only input line has an integer n.
Print the number of trailing zeros in n!.
Constraints: 1 ≤ n ≤ 10^9
Example
Input: 20
Output: 4
"""
c, d = 0, 5
while n >= d:
c += n // d
d *= 5
return c
if __name__ == '__main__':
trailing_zeros(20)
trailing_zeros(11)
trailing_zeros(5)
trailing_zeros(395)
trailing_zeros(374960399)
trailing_zeros(100000000)
''' terminal
run trailing_zeros(20)
got 4 in 0.0000219000 secs.
run trailing_zeros(11)
got 2 in 0.0000067000 secs.
run trailing_zeros(5)
got 1 in 0.0000068000 secs.
run trailing_zeros(395)
got 97 in 0.0000071000 secs.
run trailing_zeros(374960399)
got 93740092 in 0.0000095000 secs.
run trailing_zeros(100000000)
got 24999999 in 0.0000100000 secs.
'''
| 21.754386
| 80
| 0.669355
|
acfec7e58ff18ced64feccaf75a8b13e21a4da0a
| 19,204
|
py
|
Python
|
src/sentry/south_migrations/0063_auto.py
|
seukjung/sentry-custom
|
c5f6bb2019aef3caff7f3e2b619f7a70f2b9b963
|
[
"BSD-3-Clause"
] | 20
|
2016-10-01T04:29:24.000Z
|
2020-10-09T07:23:34.000Z
|
src/sentry/south_migrations/0063_auto.py
|
fotinakis/sentry
|
c5cfa5c5e47475bf5ef41e702548c2dfc7bb8a7c
|
[
"BSD-3-Clause"
] | 8
|
2019-12-28T23:49:55.000Z
|
2022-03-02T04:34:18.000Z
|
src/sentry/south_migrations/0063_auto.py
|
fotinakis/sentry
|
c5cfa5c5e47475bf5ef41e702548c2dfc7bb8a7c
|
[
"BSD-3-Clause"
] | 7
|
2016-10-27T05:12:45.000Z
|
2021-05-01T14:29:53.000Z
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding index on 'MessageCountByMinute', fields ['date']
db.create_index('sentry_messagecountbyminute', ['date'])
def backwards(self, orm):
# Removing index on 'MessageCountByMinute', fields ['date']
db.delete_index('sentry_messagecountbyminute', ['date'])
models = {
'sentry.user': {
'Meta': {'object_name': 'User', 'db_table': "'auth_user'"},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'sentry.event': {
'Meta': {'unique_together': "(('project', 'event_id'),)", 'object_name': 'Event', 'db_table': "'sentry_message'"},
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}),
'culprit': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True'}),
'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'db_column': "'message_id'"}),
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'event_set'", 'null': 'True', 'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}),
'logger': ('django.db.models.fields.CharField', [], {'default': "'root'", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'server_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'db_index': 'True'}),
'site': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'db_index': 'True'}),
'time_spent': ('django.db.models.fields.FloatField', [], {'null': 'True'})
},
'sentry.filterkey': {
'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'FilterKey'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"})
},
'sentry.filtervalue': {
'Meta': {'unique_together': "(('project', 'key', 'value'),)", 'object_name': 'FilterValue'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'sentry.group': {
'Meta': {'unique_together': "(('project', 'logger', 'culprit', 'checksum'),)", 'object_name': 'Group', 'db_table': "'sentry_groupedmessage'"},
'active_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}),
'culprit': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True'}),
'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'is_public': ('django.db.models.fields.NullBooleanField', [], {'default': 'False', 'null': 'True', 'blank': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}),
'logger': ('django.db.models.fields.CharField', [], {'default': "'root'", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'resolved_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'}),
'time_spent_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'time_spent_total': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}),
'views': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.View']", 'symmetrical': 'False', 'blank': 'True'})
},
'sentry.groupbookmark': {
'Meta': {'unique_together': "(('project', 'user', 'group'),)", 'object_name': 'GroupBookmark'},
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'bookmark_set'", 'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'bookmark_set'", 'to': "orm['sentry.Project']"}),
'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'sentry_bookmark_set'", 'to': "orm['sentry.User']"})
},
'sentry.groupmeta': {
'Meta': {'unique_together': "(('group', 'key'),)", 'object_name': 'GroupMeta'},
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'value': ('django.db.models.fields.TextField', [], {})
},
'sentry.messagecountbyminute': {
'Meta': {'unique_together': "(('project', 'group', 'date'),)", 'object_name': 'MessageCountByMinute'},
'date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}),
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'time_spent_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'time_spent_total': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'})
},
'sentry.messagefiltervalue': {
'Meta': {'unique_together': "(('project', 'key', 'value', 'group'),)", 'object_name': 'MessageFilterValue'},
'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}),
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'sentry.messageindex': {
'Meta': {'unique_together': "(('column', 'value', 'object_id'),)", 'object_name': 'MessageIndex'},
'column': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
'sentry.option': {
'Meta': {'object_name': 'Option'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'}),
'value': ('picklefield.fields.PickledObjectField', [], {})
},
'sentry.pendingteammember': {
'Meta': {'unique_together': "(('team', 'email'),)", 'object_name': 'PendingTeamMember'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'team': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'pending_member_set'", 'to': "orm['sentry.Team']"}),
'type': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'sentry.project': {
'Meta': {'object_name': 'Project'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'owner': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'sentry_owned_project_set'", 'null': 'True', 'to': "orm['sentry.User']"}),
'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'unique': 'True', 'null': 'True'}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'}),
'team': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Team']", 'null': 'True'})
},
'sentry.projectcountbyminute': {
'Meta': {'unique_together': "(('project', 'date'),)", 'object_name': 'ProjectCountByMinute'},
'date': ('django.db.models.fields.DateTimeField', [], {}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'time_spent_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'time_spent_total': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'})
},
'sentry.projectkey': {
'Meta': {'object_name': 'ProjectKey'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'key_set'", 'to': "orm['sentry.Project']"}),
'public_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}),
'secret_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}),
'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True'})
},
'sentry.projectoption': {
'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'ProjectOption', 'db_table': "'sentry_projectoptions'"},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'value': ('picklefield.fields.PickledObjectField', [], {})
},
'sentry.searchdocument': {
'Meta': {'unique_together': "(('project', 'group'),)", 'object_name': 'SearchDocument'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'date_changed': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'total_events': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'})
},
'sentry.searchtoken': {
'Meta': {'unique_together': "(('document', 'field', 'token'),)", 'object_name': 'SearchToken'},
'document': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'token_set'", 'to': "orm['sentry.SearchDocument']"}),
'field': ('django.db.models.fields.CharField', [], {'default': "'text'", 'max_length': '64'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}),
'token': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
'sentry.team': {
'Meta': {'object_name': 'Team'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'owner': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'})
},
'sentry.teammember': {
'Meta': {'unique_together': "(('team', 'user'),)", 'object_name': 'TeamMember'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'team': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'member_set'", 'to': "orm['sentry.Team']"}),
'type': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'sentry_teammember_set'", 'to': "orm['sentry.User']"})
},
'sentry.useroption': {
'Meta': {'unique_together': "(('user', 'project', 'key'),)", 'object_name': 'UserOption'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}),
'value': ('picklefield.fields.PickledObjectField', [], {})
},
'sentry.view': {
'Meta': {'object_name': 'View'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'path': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'verbose_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}),
'verbose_name_plural': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'})
}
}
complete_apps = ['sentry']
| 81.029536
| 167
| 0.565351
|
acfec8fefdfdb862efe35edf1cd8418ead0e21f2
| 3,624
|
py
|
Python
|
crawling/Wp_list_all_review.py
|
Soooyeon-Kim/Python
|
e9e7e94e4a5a4ac94ff55347201cb4d24a5bb768
|
[
"MIT"
] | null | null | null |
crawling/Wp_list_all_review.py
|
Soooyeon-Kim/Python
|
e9e7e94e4a5a4ac94ff55347201cb4d24a5bb768
|
[
"MIT"
] | null | null | null |
crawling/Wp_list_all_review.py
|
Soooyeon-Kim/Python
|
e9e7e94e4a5a4ac94ff55347201cb4d24a5bb768
|
[
"MIT"
] | null | null | null |
# link list all
# import list
import requests
from urllib.request import urlopen
import time, re, csv
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
import pandas as pd
# 크롬창(웹드라이버) 열기
driver = webdriver.Chrome('C:/Users/sooyeon/Downloads/chromedriver.exe')
# 최종 리뷰 수집 리스트
resultw=[]
# 한 페이지 내부의 영화 모음 링크
linkl = []
# 2019년 개봉 영화 수록 url
url = 'https://pedia.watcha.com/ko-KR/decks/rjNrOHQZF45G'
re = requests.get(url)
soup = BeautifulSoup(re.text, "html.parser")
#div = soup.find('div', class_='css-1gkas1x-Grid e1689zdh0').find('ul', class_='css-27z1qm-VisualUl-ContentGrid')
#li = soup.find('div',class_='css-1y901al-Row emmoxnt0').find_all('li',class_='css-1hp6p72')
# 각 영화마다 선택할 박스들
li = soup.find_all('li',class_='css-1hp6p72')
# 링크 리스트 안담겼던 오류 수정
links = [url + tag.find('a').get('href','') if tag.find('a') else '' for tag in li]
# css selector로 얻어진 href 정보로는 영화 상세 페이지로 접근할 수 없었음
# 출력해서 확인해보니 추가적인 str 정보가 붙어있어서 반복문을 사용하여 각 링크마다 replace로 제거해서 link 리스트에 다시 담아주는 과정을 거침
for link in links:
linkl.append(link.replace('/decks/rjNrOHQZF45G/ko-KR',''))
# 2021 페이지 접속
driver.get(url)
# 시간 지연
# time.sleep(2)
# 한 페이지에 보여지는 영화의 수는 12개 4X3
for i in range(0,12):
# i번째 링크 접속하기
driver.get(linkl[i])
# 시간 지연
time.sleep(1)
try:
# 영화 제목
title = driver.find_element_by_css_selector("#root > div > div.css-1fgu4u8 > section > div > div > div > section > div.css-p3jnjc-Pane.e1svyhwg12 > div > div > div > div > h1").text
# 리뷰 더보기 클릭
driver.find_element_by_xpath('//*[@id="root"]/div/div[1]/section/div/div/div/div/div/div[1]/div[1]/div/div/section[5]/div[1]/div/header/div/div/a').click()
# 평점
score = []
# 리뷰 내용
content= []
# 각 리뷰에 해당하는 박스 선택
boxes = driver.find_elements_by_css_selector("#root > div > div.css-1fgu4u8 > section > section > div > div > div > ul")
# 대기 시간 정의
SCROLL_PAUSE_SEC = 1
# 스크롤 높이 가져옴
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# 끝까지 스크롤 다운
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# 1초 대기
time.sleep(SCROLL_PAUSE_SEC)
# 스크롤 다운 후 스크롤 높이 다시 가져옴
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
# 최대 가져올 수 있는 리뷰 개수를 지정 후 반복문
# chrome에서 제공해주는 영화 리뷰는 최대 20개
for i in range(1,20):
try:
for box in boxes:
score.append(box.find_element_by_css_selector(f"div:nth-child({i}) > div.css-4obf01 > div.css-yqs4xl > span").text)
contentpre = box.find_element_by_css_selector(f"div:nth-child({i}) > div.css-4tkoly > div > span").text
contentpre = contentpre.replace('\n','')
content.append(contentpre)
except:
continue
# 데이터 프레임 생성
df = pd.DataFrame({'title':title,'score':score,'content':content})
resultw.append(df)
# 예외 처리
except NoSuchElementException:
continue
except IndexError:
continue
| 30.974359
| 190
| 0.606512
|
acfec9a2776fe8642370752a124818bb1783508e
| 505
|
py
|
Python
|
pandemic_response_analyzer/explore/models.py
|
sedatozturke/swe-573-2020f
|
3368b352076a57eadcfd40ea408666cc8a00d8df
|
[
"MIT"
] | null | null | null |
pandemic_response_analyzer/explore/models.py
|
sedatozturke/swe-573-2020f
|
3368b352076a57eadcfd40ea408666cc8a00d8df
|
[
"MIT"
] | 6
|
2020-11-02T19:47:46.000Z
|
2020-11-10T15:31:04.000Z
|
pandemic_response_analyzer/explore/models.py
|
sedatozturke/swe-573-2020f
|
3368b352076a57eadcfd40ea408666cc8a00d8df
|
[
"MIT"
] | null | null | null |
from django.db import models
# Create your models here.
class Subreddit(models.Model):
title = models.CharField(max_length=500)
reddit_id = models.CharField(max_length=500)
created_utc = models.DateTimeField()
score = models.IntegerField(default=0)
name = models.CharField(max_length=500)
upvote_ratio = models.FloatField(default=0.0)
polarity = models.FloatField(default=0.0)
subjectivity = models.FloatField(default=0.0)
def __str__(self):
return self.title
| 33.666667
| 49
| 0.728713
|
acfeca245fe2beb44ec7884bc11b1d34d807fa1d
| 1,055
|
py
|
Python
|
imageprocessingstream/imageprocessingstream_client.py
|
LukasMaly/grpc-playground
|
fc67a9b4e47cc7a18954ad66023c771328edb428
|
[
"MIT"
] | null | null | null |
imageprocessingstream/imageprocessingstream_client.py
|
LukasMaly/grpc-playground
|
fc67a9b4e47cc7a18954ad66023c771328edb428
|
[
"MIT"
] | null | null | null |
imageprocessingstream/imageprocessingstream_client.py
|
LukasMaly/grpc-playground
|
fc67a9b4e47cc7a18954ad66023c771328edb428
|
[
"MIT"
] | null | null | null |
from __future__ import print_function
import logging
import cv2
import grpc
import numpy as np
import imageprocessing_pb2
import imageprocessing_pb2_grpc
def generate_stream():
src = cv2.imread('../data/lena.png')
height, width = src.shape[:2]
channels = src.shape[2]
for i in range(100):
img = src.copy()
img = cv2.putText(img, str(i), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))
data = img.tobytes()
yield imageprocessing_pb2.Image(height=height, width=width, channels=channels, data=data)
def run():
with grpc.insecure_channel('localhost:50051') as channel:
stub = imageprocessing_pb2_grpc.ImageProcessingStreamStub(channel)
responses = stub.ToGrayscale(generate_stream())
for response in responses:
dst = np.frombuffer(response.data, dtype=np.uint8)
dst = dst.reshape((response.height, response.width))
cv2.imshow('Output', dst)
cv2.waitKey(42)
if __name__ == '__main__':
logging.basicConfig()
run()
| 29.305556
| 97
| 0.669194
|
acfecaf6e29365a978f362652edf3aa9f3ec3afe
| 1,953
|
py
|
Python
|
examples/schoolOntology.py
|
Kieran-Bacon/InfoGain
|
621ccd111d474f96f0ba19a8972821becea0c5db
|
[
"Apache-2.0"
] | 1
|
2019-10-14T00:49:04.000Z
|
2019-10-14T00:49:04.000Z
|
examples/schoolOntology.py
|
Kieran-Bacon/InfoGain
|
621ccd111d474f96f0ba19a8972821becea0c5db
|
[
"Apache-2.0"
] | 2
|
2018-06-12T12:46:35.000Z
|
2019-02-22T10:52:15.000Z
|
examples/schoolOntology.py
|
Kieran-Bacon/InfoGain
|
621ccd111d474f96f0ba19a8972821becea0c5db
|
[
"Apache-2.0"
] | null | null | null |
from infogain.artefact import Entity, Annotation, Document
from infogain.knowledge import *
from infogain.extraction import ExtractionEngine
# Define the ontology base
schoolOntology = Ontology("School")
# Define concepts
person = Concept("Person")
_class = Concept("Class")
beingTheoldesInClass = Concept("Oldest", category="static")
for con in [person, _class, beingTheoldesInClass]: schoolOntology.concepts.add(con)
# Define the relationships
rel_attends = Relation({person}, "attends", {_class})
rel_oldest = Relation({person}, "isOldestWithin", {_class}, rules=[
Rule({person}, {_class}, 100, conditions = [
Condition("#Person=attends=@"),
Condition("f(%.age, #Person.age, (x > y)*100)")
])
])
for rel in [rel_attends, rel_oldest]: schoolOntology.relations.add(rel)
# Define the example documents - training + test
training = Document(
"Kieran attends an english class in the evenings. He's enjoying the class, but, its very late int he evening..."
)
kieran, english = Entity("Person", "Kieran"), Entity("Class", "english class")
training.entities.add(kieran)
training.entities.add(english, 18)
training.annotations.add(Annotation(kieran, "attends", english, annotation=Annotation.POSITIVE))
training.annotations.add(Annotation(kieran, 'isOldestWithin', english, annotation=Annotation.INSUFFICIENT))
testing = Document(
"I think that Kieran attends an english class at UCL after work. I've overheard him talking about it."
)
# Create extraction engine for this
extraction = ExtractionEngine(ontology=schoolOntology)
extraction.fit(training)
print(list(extraction.concepts.keys()))
print(extraction.concepts['Person'].aliases)
testing = extraction.predict(testing)
print("Entities:")
for entity in testing.entities:
print(entity)
print("Annotations:")
for ann in testing.annotations:
print(ann)
#a person is the oldes in a class if their age is greater than all the other students ages.
| 29.149254
| 116
| 0.747056
|
acfecb3ee19364482eba49dff6fb7037f7990cdb
| 2,912
|
py
|
Python
|
manage.py
|
open-contracting/public-private-partnerships
|
d75eb0af4e347415d56aa8194b603b0645815cd1
|
[
"Apache-2.0"
] | 1
|
2018-03-04T22:20:28.000Z
|
2018-03-04T22:20:28.000Z
|
manage.py
|
open-contracting/public-private-partnerships
|
d75eb0af4e347415d56aa8194b603b0645815cd1
|
[
"Apache-2.0"
] | 121
|
2016-06-08T11:49:59.000Z
|
2018-11-27T18:01:15.000Z
|
manage.py
|
open-contracting/public-private-partnerships
|
d75eb0af4e347415d56aa8194b603b0645815cd1
|
[
"Apache-2.0"
] | 6
|
2017-05-18T18:21:09.000Z
|
2017-12-08T22:49:41.000Z
|
#!/usr/bin/env python
import os.path
import re
import sys
from glob import glob
from pathlib import Path
from textwrap import dedent
import click
from ocdsextensionregistry import build_profile
basedir = Path(__file__).resolve().parent
sys.path.append(str(basedir / 'docs'))
def update_codelist_urls(text, codelists):
"""
If the profile defines a codelist, replaces any links to the OCDS codelist with a link to the profile's codelist.
"""
def replace(match):
codelist = match.group(2).replace('-', '')
if any(name for name in codelists if name.lower()[:-4] == codelist):
return match.group(1) + 'profiles/ppp/latest/{{lang}}/reference/codelists/#' + codelist
return match.group()
return re.sub(r'(://standard\.open-contracting\.org/)[^/]+/[^/]+/schema/codelists/#([a-z-]+)', replace, text)
@click.group()
def cli():
pass
@cli.command()
def update():
"""
Update the profile to the latest versions of extensions. If conf.py sets managed_codelist to True, regenerate
docs/reference/codelists.md to list all codelists from OCDS and extensions.
"""
import conf
path_prefix = conf.html_theme_options['root_url']
ref = conf.release.replace('-', '__').replace('.', '__')
schema_base_url = f'https://standard.open-contracting.org{path_prefix}/schema/{ref}/'
build_profile(basedir / 'schema', conf.standard_tag, conf.extension_versions, schema_base_url=schema_base_url,
update_codelist_urls=update_codelist_urls)
if not getattr(conf, 'managed_codelist', False):
return
file = basedir / 'docs' / 'reference' / 'codelists.md'
with file.open('w+') as f:
filenames = glob(str(basedir / 'schema' / 'patched' / 'codelists' / '*.csv'))
codelists = [os.path.basename(filename) for filename in filenames]
f.write(dedent(f"""\
# Codelists
<!-- Do not edit this file. This file is managed by manage.py -->
For more information on codelists, refer to the [codelists reference](https://standard.open-contracting.org/1.1/en/schema/codelists/) in the OCDS documentation.
The codelists below are from the OCDS and its extensions, and are provided here for convenience only.
The codelists can be downloaded as CSV files from <https://standard.open-contracting.org/profiles/{conf.profile_identifier}/latest/en/_static/patched/codelists/>.
""")) # noqa: E501
for filename in sorted(codelists):
heading = re.sub(r'(?<=[a-z])(?=[A-Z])', ' ', filename.replace('.csv', '')).title()
f.write(f'\n## {heading}\n\n')
f.write(dedent(f"""\
```{{csv-table-no-translate}}
:header-rows: 1
:class: codelist-table
:file: ../_static/patched/codelists/{filename}
```
"""))
if __name__ == '__main__':
cli()
| 33.860465
| 170
| 0.643887
|
acfecbd748648536ed4b9ecb1a39c1f5924c3e6d
| 2,540
|
py
|
Python
|
ci/scripts/python/nrf5_cmake/version.py
|
perfectco/cmake-nRF5x
|
08b9158fa7bfa0c8641df468d48917dec46fb115
|
[
"MIT"
] | 111
|
2017-11-21T06:21:18.000Z
|
2022-03-30T07:40:03.000Z
|
ci/scripts/python/nrf5_cmake/version.py
|
perfectco/cmake-nRF5x
|
08b9158fa7bfa0c8641df468d48917dec46fb115
|
[
"MIT"
] | 41
|
2018-01-09T15:44:11.000Z
|
2021-10-31T08:45:24.000Z
|
ci/scripts/python/nrf5_cmake/version.py
|
giuliocorradini/cmake-nRF5x
|
a5b5d489768dc397a7eddc57d4ad65e6b3039b08
|
[
"MIT"
] | 39
|
2018-03-13T14:03:10.000Z
|
2022-02-28T17:46:17.000Z
|
from unittest import TestCase
class Version:
def __init__(self, major: int, minor: int, patch: int):
self._major = major
self._minor = minor
self._patch = patch
@staticmethod
def from_string(version: str):
return Version(*(int(x) for x in version.split('.')))
def __str__(self):
return str(self._major) + "." + str(self._minor) + "." + str(self._patch)
def __cmp__(self, other):
major_diff = self._major - other._major
if major_diff != 0:
return major_diff
minor_diff = self._minor - other._minor
if minor_diff != 0:
return minor_diff
return self._patch - other._patch
def __eq__(self, other):
if not isinstance(other, Version):
return False
return self.__cmp__(other) == 0
def __lt__(self, other):
return self.__cmp__(other) < 0
def __le__(self, other):
return self.__cmp__(other) <= 0
def __gt__(self, other):
return self.__cmp__(other) > 0
def __ge__(self, other):
return self.__cmp__(other) >= 0
def __hash__(self) -> int:
return hash((self._major, self._minor, self._patch))
@property
def major(self) -> int:
return self._major
@property
def minor(self) -> int:
return self._minor
@property
def patch(self) -> int:
return self._patch
class VersionTestCase(TestCase):
def test_equality(self):
self.assertEqual(Version(16, 0, 0), Version(16, 0, 0))
self.assertNotEqual(Version(16, 0, 0), Version(16, 0, 1))
self.assertNotEqual(Version(16, 0, 0), Version(16, 1, 0))
self.assertNotEqual(Version(16, 0, 0), Version(17, 0, 0))
def test_less(self):
self.assertLess(Version(16, 0, 0), Version(16, 0, 1))
self.assertLess(Version(16, 0, 0), Version(16, 1, 0))
self.assertLess(Version(16, 0, 0), Version(17, 0, 0))
def test_greater(self):
self.assertGreater(Version(16, 0, 1), Version(16, 0, 0))
self.assertGreater(Version(16, 1, 0), Version(16, 0, 0))
self.assertGreater(Version(17, 0, 0), Version(16, 0, 0))
def test_text_format(self):
self.assertEqual(Version.from_string("13.4.5"), Version(13, 4, 5))
self.assertEqual("13.4.5", str(Version(13, 4, 5)))
def test_getters(self):
version = Version(13, 4, 5)
self.assertEqual(version.major, 13)
self.assertEqual(version.minor, 4)
self.assertEqual(version.patch, 5)
| 29.882353
| 81
| 0.601181
|
acfecc2c4c33fa78688fa531617baa01ec302723
| 23,709
|
py
|
Python
|
spark_fhir_schemas/r4/complex_types/evidencevariable_characteristic.py
|
icanbwell/SparkFhirSchemas
|
8c828313c39850b65f8676e67f526ee92b7d624e
|
[
"Apache-2.0"
] | null | null | null |
spark_fhir_schemas/r4/complex_types/evidencevariable_characteristic.py
|
icanbwell/SparkFhirSchemas
|
8c828313c39850b65f8676e67f526ee92b7d624e
|
[
"Apache-2.0"
] | null | null | null |
spark_fhir_schemas/r4/complex_types/evidencevariable_characteristic.py
|
icanbwell/SparkFhirSchemas
|
8c828313c39850b65f8676e67f526ee92b7d624e
|
[
"Apache-2.0"
] | null | null | null |
from typing import Union, List, Optional
from pyspark.sql.types import (
StructType,
StructField,
StringType,
ArrayType,
BooleanType,
DataType,
TimestampType,
)
# This file is auto-generated by generate_schema so do not edit it manually
# noinspection PyPep8Naming
class EvidenceVariable_CharacteristicSchema:
"""
The EvidenceVariable resource describes a "PICO" element that knowledge
(evidence, assertion, recommendation) is about.
"""
# noinspection PyDefaultArgument
@staticmethod
def get_schema(
max_nesting_depth: Optional[int] = 6,
nesting_depth: int = 0,
nesting_list: List[str] = [],
max_recursion_limit: Optional[int] = 2,
include_extension: Optional[bool] = False,
extension_fields: Optional[List[str]] = None,
extension_depth: int = 0,
max_extension_depth: Optional[int] = 2,
include_modifierExtension: Optional[bool] = False,
use_date_for: Optional[List[str]] = None,
parent_path: Optional[str] = "",
) -> Union[StructType, DataType]:
"""
The EvidenceVariable resource describes a "PICO" element that knowledge
(evidence, assertion, recommendation) is about.
id: Unique id for the element within a resource (for internal references). This
may be any string value that does not contain spaces.
extension: May be used to represent additional information that is not part of the basic
definition of the element. To make the use of extensions safe and manageable,
there is a strict set of governance applied to the definition and use of
extensions. Though any implementer can define an extension, there is a set of
requirements that SHALL be met as part of the definition of the extension.
modifierExtension: May be used to represent additional information that is not part of the basic
definition of the element and that modifies the understanding of the element
in which it is contained and/or the understanding of the containing element's
descendants. Usually modifier elements provide negation or qualification. To
make the use of extensions safe and manageable, there is a strict set of
governance applied to the definition and use of extensions. Though any
implementer can define an extension, there is a set of requirements that SHALL
be met as part of the definition of the extension. Applications processing a
resource are required to check for modifier extensions.
Modifier extensions SHALL NOT change the meaning of any elements on Resource
or DomainResource (including cannot change the meaning of modifierExtension
itself).
description: A short, natural language description of the characteristic that could be used
to communicate the criteria to an end-user.
definitionReference: Define members of the evidence element using Codes (such as condition,
medication, or observation), Expressions ( using an expression language such
as FHIRPath or CQL) or DataRequirements (such as Diabetes diagnosis onset in
the last year).
definitionCanonical: Define members of the evidence element using Codes (such as condition,
medication, or observation), Expressions ( using an expression language such
as FHIRPath or CQL) or DataRequirements (such as Diabetes diagnosis onset in
the last year).
definitionCodeableConcept: Define members of the evidence element using Codes (such as condition,
medication, or observation), Expressions ( using an expression language such
as FHIRPath or CQL) or DataRequirements (such as Diabetes diagnosis onset in
the last year).
definitionExpression: Define members of the evidence element using Codes (such as condition,
medication, or observation), Expressions ( using an expression language such
as FHIRPath or CQL) or DataRequirements (such as Diabetes diagnosis onset in
the last year).
definitionDataRequirement: Define members of the evidence element using Codes (such as condition,
medication, or observation), Expressions ( using an expression language such
as FHIRPath or CQL) or DataRequirements (such as Diabetes diagnosis onset in
the last year).
definitionTriggerDefinition: Define members of the evidence element using Codes (such as condition,
medication, or observation), Expressions ( using an expression language such
as FHIRPath or CQL) or DataRequirements (such as Diabetes diagnosis onset in
the last year).
usageContext: Use UsageContext to define the members of the population, such as Age Ranges,
Genders, Settings.
exclude: When true, members with this characteristic are excluded from the element.
participantEffectiveDateTime: Indicates what effective period the study covers.
participantEffectivePeriod: Indicates what effective period the study covers.
participantEffectiveDuration: Indicates what effective period the study covers.
participantEffectiveTiming: Indicates what effective period the study covers.
timeFromStart: Indicates duration from the participant's study entry.
groupMeasure: Indicates how elements are aggregated within the study effective period.
"""
if extension_fields is None:
extension_fields = [
"valueBoolean",
"valueCode",
"valueDate",
"valueDateTime",
"valueDecimal",
"valueId",
"valueInteger",
"valuePositiveInt",
"valueString",
"valueTime",
"valueUnsignedInt",
"valueUri",
"valueUrl",
"valueReference",
"valueCodeableConcept",
"valueAddress",
]
from spark_fhir_schemas.r4.complex_types.extension import ExtensionSchema
from spark_fhir_schemas.r4.complex_types.reference import ReferenceSchema
from spark_fhir_schemas.r4.complex_types.codeableconcept import (
CodeableConceptSchema,
)
from spark_fhir_schemas.r4.complex_types.expression import ExpressionSchema
from spark_fhir_schemas.r4.complex_types.datarequirement import (
DataRequirementSchema,
)
from spark_fhir_schemas.r4.complex_types.triggerdefinition import (
TriggerDefinitionSchema,
)
from spark_fhir_schemas.r4.complex_types.usagecontext import UsageContextSchema
from spark_fhir_schemas.r4.complex_types.period import PeriodSchema
from spark_fhir_schemas.r4.complex_types.duration import DurationSchema
from spark_fhir_schemas.r4.complex_types.timing import TimingSchema
if (
max_recursion_limit
and nesting_list.count("EvidenceVariable_Characteristic")
>= max_recursion_limit
) or (max_nesting_depth and nesting_depth >= max_nesting_depth):
return StructType([StructField("id", StringType(), True)])
# add my name to recursion list for later
my_nesting_list: List[str] = nesting_list + ["EvidenceVariable_Characteristic"]
my_parent_path = (
parent_path + ".evidencevariable_characteristic"
if parent_path
else "evidencevariable_characteristic"
)
schema = StructType(
[
# Unique id for the element within a resource (for internal references). This
# may be any string value that does not contain spaces.
StructField("id", StringType(), True),
# May be used to represent additional information that is not part of the basic
# definition of the element. To make the use of extensions safe and manageable,
# there is a strict set of governance applied to the definition and use of
# extensions. Though any implementer can define an extension, there is a set of
# requirements that SHALL be met as part of the definition of the extension.
StructField(
"extension",
ArrayType(
ExtensionSchema.get_schema(
max_nesting_depth=max_nesting_depth,
nesting_depth=nesting_depth + 1,
nesting_list=my_nesting_list,
max_recursion_limit=max_recursion_limit,
include_extension=include_extension,
extension_fields=extension_fields,
extension_depth=extension_depth,
max_extension_depth=max_extension_depth,
include_modifierExtension=include_modifierExtension,
use_date_for=use_date_for,
parent_path=my_parent_path,
)
),
True,
),
# May be used to represent additional information that is not part of the basic
# definition of the element and that modifies the understanding of the element
# in which it is contained and/or the understanding of the containing element's
# descendants. Usually modifier elements provide negation or qualification. To
# make the use of extensions safe and manageable, there is a strict set of
# governance applied to the definition and use of extensions. Though any
# implementer can define an extension, there is a set of requirements that SHALL
# be met as part of the definition of the extension. Applications processing a
# resource are required to check for modifier extensions.
#
# Modifier extensions SHALL NOT change the meaning of any elements on Resource
# or DomainResource (including cannot change the meaning of modifierExtension
# itself).
StructField(
"modifierExtension",
ArrayType(
ExtensionSchema.get_schema(
max_nesting_depth=max_nesting_depth,
nesting_depth=nesting_depth + 1,
nesting_list=my_nesting_list,
max_recursion_limit=max_recursion_limit,
include_extension=include_extension,
extension_fields=extension_fields,
extension_depth=extension_depth,
max_extension_depth=max_extension_depth,
include_modifierExtension=include_modifierExtension,
use_date_for=use_date_for,
parent_path=my_parent_path,
)
),
True,
),
# A short, natural language description of the characteristic that could be used
# to communicate the criteria to an end-user.
StructField("description", StringType(), True),
# Define members of the evidence element using Codes (such as condition,
# medication, or observation), Expressions ( using an expression language such
# as FHIRPath or CQL) or DataRequirements (such as Diabetes diagnosis onset in
# the last year).
StructField(
"definitionReference",
ReferenceSchema.get_schema(
max_nesting_depth=max_nesting_depth,
nesting_depth=nesting_depth + 1,
nesting_list=my_nesting_list,
max_recursion_limit=max_recursion_limit,
include_extension=include_extension,
extension_fields=extension_fields,
extension_depth=extension_depth + 1,
max_extension_depth=max_extension_depth,
include_modifierExtension=include_modifierExtension,
use_date_for=use_date_for,
parent_path=my_parent_path,
),
True,
),
# Define members of the evidence element using Codes (such as condition,
# medication, or observation), Expressions ( using an expression language such
# as FHIRPath or CQL) or DataRequirements (such as Diabetes diagnosis onset in
# the last year).
StructField("definitionCanonical", StringType(), True),
# Define members of the evidence element using Codes (such as condition,
# medication, or observation), Expressions ( using an expression language such
# as FHIRPath or CQL) or DataRequirements (such as Diabetes diagnosis onset in
# the last year).
StructField(
"definitionCodeableConcept",
CodeableConceptSchema.get_schema(
max_nesting_depth=max_nesting_depth,
nesting_depth=nesting_depth + 1,
nesting_list=my_nesting_list,
max_recursion_limit=max_recursion_limit,
include_extension=include_extension,
extension_fields=extension_fields,
extension_depth=extension_depth + 1,
max_extension_depth=max_extension_depth,
include_modifierExtension=include_modifierExtension,
use_date_for=use_date_for,
parent_path=my_parent_path,
),
True,
),
# Define members of the evidence element using Codes (such as condition,
# medication, or observation), Expressions ( using an expression language such
# as FHIRPath or CQL) or DataRequirements (such as Diabetes diagnosis onset in
# the last year).
StructField(
"definitionExpression",
ExpressionSchema.get_schema(
max_nesting_depth=max_nesting_depth,
nesting_depth=nesting_depth + 1,
nesting_list=my_nesting_list,
max_recursion_limit=max_recursion_limit,
include_extension=include_extension,
extension_fields=extension_fields,
extension_depth=extension_depth + 1,
max_extension_depth=max_extension_depth,
include_modifierExtension=include_modifierExtension,
use_date_for=use_date_for,
parent_path=my_parent_path,
),
True,
),
# Define members of the evidence element using Codes (such as condition,
# medication, or observation), Expressions ( using an expression language such
# as FHIRPath or CQL) or DataRequirements (such as Diabetes diagnosis onset in
# the last year).
StructField(
"definitionDataRequirement",
DataRequirementSchema.get_schema(
max_nesting_depth=max_nesting_depth,
nesting_depth=nesting_depth + 1,
nesting_list=my_nesting_list,
max_recursion_limit=max_recursion_limit,
include_extension=include_extension,
extension_fields=extension_fields,
extension_depth=extension_depth + 1,
max_extension_depth=max_extension_depth,
include_modifierExtension=include_modifierExtension,
use_date_for=use_date_for,
parent_path=my_parent_path,
),
True,
),
# Define members of the evidence element using Codes (such as condition,
# medication, or observation), Expressions ( using an expression language such
# as FHIRPath or CQL) or DataRequirements (such as Diabetes diagnosis onset in
# the last year).
StructField(
"definitionTriggerDefinition",
TriggerDefinitionSchema.get_schema(
max_nesting_depth=max_nesting_depth,
nesting_depth=nesting_depth + 1,
nesting_list=my_nesting_list,
max_recursion_limit=max_recursion_limit,
include_extension=include_extension,
extension_fields=extension_fields,
extension_depth=extension_depth + 1,
max_extension_depth=max_extension_depth,
include_modifierExtension=include_modifierExtension,
use_date_for=use_date_for,
parent_path=my_parent_path,
),
True,
),
# Use UsageContext to define the members of the population, such as Age Ranges,
# Genders, Settings.
StructField(
"usageContext",
ArrayType(
UsageContextSchema.get_schema(
max_nesting_depth=max_nesting_depth,
nesting_depth=nesting_depth + 1,
nesting_list=my_nesting_list,
max_recursion_limit=max_recursion_limit,
include_extension=include_extension,
extension_fields=extension_fields,
extension_depth=extension_depth,
max_extension_depth=max_extension_depth,
include_modifierExtension=include_modifierExtension,
use_date_for=use_date_for,
parent_path=my_parent_path,
)
),
True,
),
# When true, members with this characteristic are excluded from the element.
StructField("exclude", BooleanType(), True),
# Indicates what effective period the study covers.
StructField("participantEffectiveDateTime", TimestampType(), True),
# Indicates what effective period the study covers.
StructField(
"participantEffectivePeriod",
PeriodSchema.get_schema(
max_nesting_depth=max_nesting_depth,
nesting_depth=nesting_depth + 1,
nesting_list=my_nesting_list,
max_recursion_limit=max_recursion_limit,
include_extension=include_extension,
extension_fields=extension_fields,
extension_depth=extension_depth + 1,
max_extension_depth=max_extension_depth,
include_modifierExtension=include_modifierExtension,
use_date_for=use_date_for,
parent_path=my_parent_path,
),
True,
),
# Indicates what effective period the study covers.
StructField(
"participantEffectiveDuration",
DurationSchema.get_schema(
max_nesting_depth=max_nesting_depth,
nesting_depth=nesting_depth + 1,
nesting_list=my_nesting_list,
max_recursion_limit=max_recursion_limit,
include_extension=include_extension,
extension_fields=extension_fields,
extension_depth=extension_depth + 1,
max_extension_depth=max_extension_depth,
include_modifierExtension=include_modifierExtension,
use_date_for=use_date_for,
parent_path=my_parent_path,
),
True,
),
# Indicates what effective period the study covers.
StructField(
"participantEffectiveTiming",
TimingSchema.get_schema(
max_nesting_depth=max_nesting_depth,
nesting_depth=nesting_depth + 1,
nesting_list=my_nesting_list,
max_recursion_limit=max_recursion_limit,
include_extension=include_extension,
extension_fields=extension_fields,
extension_depth=extension_depth + 1,
max_extension_depth=max_extension_depth,
include_modifierExtension=include_modifierExtension,
use_date_for=use_date_for,
parent_path=my_parent_path,
),
True,
),
# Indicates duration from the participant's study entry.
StructField(
"timeFromStart",
DurationSchema.get_schema(
max_nesting_depth=max_nesting_depth,
nesting_depth=nesting_depth + 1,
nesting_list=my_nesting_list,
max_recursion_limit=max_recursion_limit,
include_extension=include_extension,
extension_fields=extension_fields,
extension_depth=extension_depth + 1,
max_extension_depth=max_extension_depth,
include_modifierExtension=include_modifierExtension,
use_date_for=use_date_for,
parent_path=my_parent_path,
),
True,
),
# Indicates how elements are aggregated within the study effective period.
StructField("groupMeasure", StringType(), True),
]
)
if not include_extension:
schema.fields = [
c
if c.name != "extension"
else StructField("extension", StringType(), True)
for c in schema.fields
]
if not include_modifierExtension:
schema.fields = [
c
if c.name != "modifierExtension"
else StructField("modifierExtension", StringType(), True)
for c in schema.fields
]
return schema
| 51.87965
| 107
| 0.575773
|
acfecce744eede54a0fe9ce6a9cc3efaa9d9fbf3
| 3,776
|
py
|
Python
|
example.py
|
devp4/PyAPIReference
|
8ebb758f17e15960adf0dce5a8dca37eec43bff8
|
[
"MIT"
] | 5
|
2021-09-14T23:34:31.000Z
|
2021-11-19T01:08:08.000Z
|
example.py
|
devp4/PyAPIReference
|
8ebb758f17e15960adf0dce5a8dca37eec43bff8
|
[
"MIT"
] | 4
|
2021-09-17T00:23:06.000Z
|
2021-09-29T21:47:50.000Z
|
example.py
|
devp4/PyAPIReference
|
8ebb758f17e15960adf0dce5a8dca37eec43bff8
|
[
"MIT"
] | 3
|
2021-09-26T14:34:21.000Z
|
2021-12-06T14:23:08.000Z
|
"""Example file with classes, iheritance, functions, imported members and constants to test PyAPIReference.
This is the docstring for example.py.
"""
from time import sleep
from PyQt5 import *
BLACK = "#000000"
WHITE = "#ffffff"
class Person:
"""Class person that requires name, last name and age.
Allows you to display some info about it.
"""
human = True
def __init__(self, name: str, last_name: str, age: str):
self.name = name
self.last_name = last_name
self.age = age
pineapple = False
def display_info(self):
print(f"Hello, my name is {self.name} {self.last_name} I have {self.age} years old.\n")
class Student(Person):
"""Class Student that inherits from Person and requires grade and institution (besides the Person ones).
Allows you to display some info about it.
"""
studying = True
def __init__(self, grade: int, institution: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self.grade = grade
self.institution = institution
def display_info(self):
print(f"Hello, my name is {self.name} {self.last_name} I have {self.age} years old.\nI'm a student of grade {self.grade} in {self.institution}\n")
class Teacher(Person):
"""Class Teacher that inherits from Person and requires instituiton and classes (besides Person ones).
Alloes you to display some info about it.
"""
def __init__(self, institution: str, classes: tuple, *args, **kwargs):
super().__init__(*args, **kwargs)
self.institution = institution
self.classes = classes
def display_info(self):
print(f"Hello, my name is {self.name} {self.last_name} I have {self.age} years old.\nI'm a teacher of {''.join(self.classes)} in {self.institution}\n")
class SchoolTeacher(Teacher):
"""Class SchoolTeacher that inherits from Teacher and requires grades.
Allows you to display some info about it."""
def __init__(self, grades: tuple, *args, **kwargs):
super().__init__(*args, **kwargs)
self.grades = grades
def display_info(self):
print(f"Hello, my name is {self.name} {self.last_name} I have {self.age} years old.\nI'm a teacher of {''.join(self.classes)} in {''.join(self.grades)} at {self.institution}\n")
class CollegeStudent(Student):
"""Class CollegeStudent that inherits from Student and requires career and semester (besides the Student ones).
Allows you to display some info about it.
"""
def __init__(self, career: str, semester: int, *args, **kwargs):
super().__init__(*args, **kwargs)
self.career = career
self.semester = semester
def display_info(self):
print(f"Hello, my name is {self.name} {self.last_name} I have {self.age} years old.\nI'm a college student of {self.career}, I'm on {self.semester} semester\n")
class Me(Teacher, CollegeStudent):
"""I'm a teacher on a school but a student in a college."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def caesar_cipher(text: str, shift: int=5) -> str:
"""Simple caesar cipher function that encrypts a string with using caesar cipher.
"""
result = ""
for char in text:
if (char.isupper()):
result += chr((ord(char) + shift - 65) % 26 + 65)
continue
result += chr((ord(char) + shift - 97) % 26 + 97)
return result
def foo(param1, param2=None, param3: str="Hello world"):
"""foo function docstring"""
pass
def emtpy():
pass
'''
unsafe tests. Delete if name == main
emtpy()
x = Person("name", "last_name", "age").display_info()
foo(1)
y = foo
y()
'''
if __name__ == "__main__":
person = Person("William", "Polo", 15)
student = Student(6, "Harward", "Jack", "Sparrow", 45)
college_student = CollegeStudent("Computer science", 4, 0, "Harvard", "Will", "Miles", 23)
person.display_info()
student.display_info()
college_student.display_info()
print(caesar_cipher(person.name))
| 29.046154
| 179
| 0.697564
|
acfecddc4fadef7ce280de57da8e710cc34a1dc1
| 2,453
|
py
|
Python
|
oslo_messaging/serializer.py
|
sapcc/oslo.messaging
|
feb72de7b81e3919dedc697f9fb5484a92f85ad8
|
[
"Apache-1.1"
] | 131
|
2015-01-23T23:37:05.000Z
|
2022-02-21T01:38:46.000Z
|
oslo_messaging/serializer.py
|
sapcc/oslo.messaging
|
feb72de7b81e3919dedc697f9fb5484a92f85ad8
|
[
"Apache-1.1"
] | 3
|
2015-10-01T14:30:01.000Z
|
2017-03-31T10:51:29.000Z
|
oslo_messaging/serializer.py
|
sapcc/oslo.messaging
|
feb72de7b81e3919dedc697f9fb5484a92f85ad8
|
[
"Apache-1.1"
] | 154
|
2015-01-08T08:47:08.000Z
|
2022-03-23T08:37:17.000Z
|
# Copyright 2013 IBM Corp.
#
# 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.
"""Provides the definition of a message serialization handler"""
import abc
from oslo_serialization import jsonutils
__all__ = ['Serializer', 'NoOpSerializer', 'JsonPayloadSerializer']
class Serializer(object, metaclass=abc.ABCMeta):
"""Generic (de-)serialization definition base class."""
@abc.abstractmethod
def serialize_entity(self, ctxt, entity):
"""Serialize something to primitive form.
:param ctxt: Request context, in deserialized form
:param entity: Entity to be serialized
:returns: Serialized form of entity
"""
@abc.abstractmethod
def deserialize_entity(self, ctxt, entity):
"""Deserialize something from primitive form.
:param ctxt: Request context, in deserialized form
:param entity: Primitive to be deserialized
:returns: Deserialized form of entity
"""
@abc.abstractmethod
def serialize_context(self, ctxt):
"""Serialize a request context into a dictionary.
:param ctxt: Request context
:returns: Serialized form of context
"""
@abc.abstractmethod
def deserialize_context(self, ctxt):
"""Deserialize a dictionary into a request context.
:param ctxt: Request context dictionary
:returns: Deserialized form of entity
"""
class NoOpSerializer(Serializer):
"""A serializer that does nothing."""
def serialize_entity(self, ctxt, entity):
return entity
def deserialize_entity(self, ctxt, entity):
return entity
def serialize_context(self, ctxt):
return ctxt
def deserialize_context(self, ctxt):
return ctxt
class JsonPayloadSerializer(NoOpSerializer):
@staticmethod
def serialize_entity(context, entity):
return jsonutils.to_primitive(entity, convert_instances=True)
| 29.914634
| 78
| 0.692621
|
acfece708704f82b8d8706749552c5f0fa54e4a2
| 5,445
|
py
|
Python
|
maelas/relax.py
|
Xavier-ML/MAELAS
|
e7eab7281026451fc93a58fbe36f4c2d69e8bac9
|
[
"BSD-3-Clause"
] | 12
|
2020-09-05T06:35:58.000Z
|
2022-03-31T09:27:57.000Z
|
maelas/relax.py
|
Xavier-ML/MAELAS
|
e7eab7281026451fc93a58fbe36f4c2d69e8bac9
|
[
"BSD-3-Clause"
] | null | null | null |
maelas/relax.py
|
Xavier-ML/MAELAS
|
e7eab7281026451fc93a58fbe36f4c2d69e8bac9
|
[
"BSD-3-Clause"
] | 3
|
2021-06-11T06:55:02.000Z
|
2022-01-23T19:18:29.000Z
|
from pymatgen import Structure
from pymatgen.io.vasp import Poscar
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from maelas.data import SymmetryData
import os
import stat
class Relaxation:
delec_list = ['Sc', 'Y', 'Ti', 'Zr', 'Hf', 'V', 'Nb', 'Ta', 'Cr', 'Mo', 'W', 'Mn', 'Tc', 'Re', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'Hg', 'Au', 'Ir', 'Pt', 'Os']
felec_list = ['La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu','Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'U', 'Ac', 'Th', 'Pa', 'Np', 'Pu', 'Am']
def __init__(self,args):
self.lmax = 2
self.inc_rlx_list = []
self.args = args
self.symData = SymmetryData()
def poscar(self):
""" generating poscar for relaxation calculations """
print('--------------------------------------------------------------------------------------------------------')
print("Generation of VASP files for the cell relaxation:")
print('--------------------------------------------------------------------------------------------------------')
self.symData.structure = Structure.from_file(self.args.pos[0])
sym1 = float(self.args.sympre[0])
sym2 = float(self.args.symang[0])
aa = SpacegroupAnalyzer(self.symData.structure,symprec=sym1, angle_tolerance=sym2)
self.symData.space_group = aa.get_space_group_number()
print("Space group number =", self.symData.space_group)
spg = aa.get_space_group_symbol()
print("Space group symbol =", str(spg))
self.symData.number_of_species = len(self.symData.structure.species)
print("Number of atoms = {}".format(len(self.symData.structure.species)))
pos_name = "POSCAR"
structure00 = Poscar(self.symData.structure)
structure00.write_file(filename = pos_name,significant_figures=16)
return self.symData
def incar(self):
""" generating INCAR file for cell relaxation """
for i in range(self.symData.number_of_species):
for j in range(len(self.delec_list)):
if str(self.symData.structure.species[i]) == str(self.delec_list[j]):
#print('Material contains a d-element =', str(structure2.species[i]))
self.lmax = 4
for i in range(self.symData.number_of_species):
for j in range(len(self.felec_list)):
if str(self.symData.structure.species[i]) == str(self.felec_list[j]):
#print('Material contains a f-element =', str(structure2.species[i]))
self.lmax = 6
self.inc_rlx_list = ['ISTART = 0\n', 'NSW = 40\n', 'ENCUT = 520\n','IBRION = 1\n', 'ISIF = 3\n', 'EDIFFG = -0.001\n', '# LDAU = .TRUE.\n', '# LDAUL =\n', '# LDAUU =\n', '# LDAUJ = \n', '# LDAUTYPE = 2\n', 'LCHARG = FALSE\n', 'LWAVE = FALSE\n', 'PREC = Normal\n', 'EDIFF = 1.e-06\n', 'NELM = 100\n', 'NELMIN = 4\n', 'ISMEAR = 1\n', 'SIGMA = 0.10\n', 'ISPIN = 2\n', 'LMAXMIX = ', self.lmax, ' ! for d-elements increase LMAXMIX to 4, f-elements: LMAXMIX = 6\n']
path_inc_rlx = 'INCAR'
inc_rlx = open(path_inc_rlx,'w')
for entry in self.inc_rlx_list:
inc_rlx.write(str(entry))
mom_rlx = 'MAGMOM = ' + str(self.symData.number_of_species) + '*5'
inc_rlx.write(mom_rlx)
inc_rlx.close()
def kpoints(self):
""" KPOINT file """
path_kp = 'KPOINTS'
kp_file = open(path_kp,'w')
kp_file.write('k-points\n')
kp_file.write('0\n')
kp_file.write('Auto\n')
kp_file.write(str(self.args.kp[0]))
kp_file.close()
def scripts(self):
""" bash script to run vasp: vasp_jsub_rlx """
path_vasp_jsub = 'vasp_jsub_rlx'
vasp_jsub = open(path_vasp_jsub,'w')
vasp_jsub.write('#!/bin/bash\n')
vasp_jsub.write('#PBS -A ')
vasp_jsub.write(str(self.args.p_id[0]))
vasp_jsub.write('\n')
vasp_jsub.write('#PBS -q ')
vasp_jsub.write(str(self.args.queue[0]))
vasp_jsub.write('\n')
vasp_jsub.write('#PBS -l select=1:ncpus=')
vasp_jsub.write(str(self.args.core[0]))
vasp_jsub.write(':mpiprocs=')
vasp_jsub.write(str(self.args.core[0]))
vasp_jsub.write(':ompthreads=1\n')
vasp_jsub.write('#PBS -l walltime=')
vasp_jsub.write(str(self.args.time[0]))
vasp_jsub.write(':00:00\n')
vasp_jsub.write('#PBS -N job_rlx\n')
vasp_jsub.write('#PBS -j oe\n')
vasp_jsub.write('#PBS -S /bin/bash\n')
vasp_jsub.write('\n')
vasp_jsub.write('cd ${PBS_O_WORKDIR}\n')
vasp_jsub.write('SCRDIR=')
vasp_jsub.write(str(self.args.vasp_fold[0]))
vasp_jsub.write('\n')
vasp_jsub.write('mkdir -p $SCRDIR\n')
vasp_jsub.write('cd $SCRDIR || exit\n')
vasp_jsub.write('cp -f -r $PBS_O_WORKDIR/* .\n')
vasp_jsub.write('ml purge\n')
vasp_jsub.write('ml ')
vasp_jsub.write(str(self.args.load_module[0]))
vasp_jsub.write('\n')
vasp_jsub.write(str(self.args.mpi[0]))
vasp_jsub.write(' -np ')
vasp_jsub.write(str(self.args.core[0]))
vasp_jsub.write(' vasp_std > vasp.out\n')
vasp_jsub.write('exit\n')
vasp_jsub.close()
st = os.stat(path_vasp_jsub)
os.chmod(path_vasp_jsub, st.st_mode | stat.S_IEXEC)
| 44.631148
| 472
| 0.554454
|
acfecf8dd9abad44a3f1ec2afacf85d0652dbbef
| 564
|
py
|
Python
|
legacy/cli/helper.py
|
hashnfv/hashnfv-qtip
|
2c79d3361fdb1fcbe67682f8a205011b3ccf5e72
|
[
"Apache-2.0"
] | null | null | null |
legacy/cli/helper.py
|
hashnfv/hashnfv-qtip
|
2c79d3361fdb1fcbe67682f8a205011b3ccf5e72
|
[
"Apache-2.0"
] | null | null | null |
legacy/cli/helper.py
|
hashnfv/hashnfv-qtip
|
2c79d3361fdb1fcbe67682f8a205011b3ccf5e72
|
[
"Apache-2.0"
] | null | null | null |
##############################################################################
# Copyright (c) 2016 ZTE Corp and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
##############################################################################
import os
def fetch_root():
return os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'benchmarks/')
| 37.6
| 87
| 0.542553
|
acfecf8e31d8fafd7a8105e42defe2e11b2de904
| 756
|
py
|
Python
|
app/__init__.py
|
medsci-tech/mime_analysis_flask_2017
|
4a927219f31db433f4af6a7af3085e05c08b5c3e
|
[
"MIT"
] | null | null | null |
app/__init__.py
|
medsci-tech/mime_analysis_flask_2017
|
4a927219f31db433f4af6a7af3085e05c08b5c3e
|
[
"MIT"
] | null | null | null |
app/__init__.py
|
medsci-tech/mime_analysis_flask_2017
|
4a927219f31db433f4af6a7af3085e05c08b5c3e
|
[
"MIT"
] | null | null | null |
from flask import Flask
from .config import configs
from .models import db
from .vendors import bcrypt
from .vendors import login_manager
from .blueprint_auth import blueprint_auth
from .blueprint_time import blueprint_time
from .blueprint_region import blueprint_region
from .blueprint_doctor import blueprint_doctor
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(configs[config_name])
# init vendors here.
db.init_app(app)
bcrypt.init_app(app)
login_manager.init_app(app)
# register blueprints here.
app.register_blueprint(blueprint_auth)
app.register_blueprint(blueprint_time)
app.register_blueprint(blueprint_region)
app.register_blueprint(blueprint_doctor)
return app
| 24.387097
| 48
| 0.78836
|
acfecfe092784ad222c4a4eb160b98039b1944ba
| 774
|
py
|
Python
|
tests/models/DeepFM_test.py
|
jiqiujia/DeepCTR-Torch
|
687a094135fa597697d926782a5634c79b627dac
|
[
"Apache-2.0"
] | 1
|
2020-02-19T07:48:46.000Z
|
2020-02-19T07:48:46.000Z
|
tests/models/DeepFM_test.py
|
praysunday/DeepCTR-Torch
|
abb3a825d8d8e02aa9afaf935d4526e19214c855
|
[
"Apache-2.0"
] | null | null | null |
tests/models/DeepFM_test.py
|
praysunday/DeepCTR-Torch
|
abb3a825d8d8e02aa9afaf935d4526e19214c855
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
import pytest
from deepctr_torch.models import DeepFM
from ..utils import get_test_data, SAMPLE_SIZE, check_model
@pytest.mark.parametrize(
'use_fm,hidden_size,sparse_feature_num',
[(True, (32, ), 3),
(False, (32, ), 3),
(False, (32, ), 2), (False, (32,), 1), (True, (), 1), (False, (), 2)
]
)
def test_DeepFM(use_fm, hidden_size, sparse_feature_num):
model_name = "DeepFM"
sample_size = SAMPLE_SIZE
x, y, feature_columns = get_test_data(
sample_size, sparse_feature_num, sparse_feature_num)
model = DeepFM(feature_columns, feature_columns, use_fm=use_fm,
dnn_hidden_units=hidden_size, dnn_dropout=0.5)
check_model(model, model_name, x, y)
if __name__ == "__main__":
pass
| 29.769231
| 73
| 0.661499
|
acfed09d45e9ff9174a53a6eaa2e8b3d71ba6a18
| 2,839
|
py
|
Python
|
tests/test_allrecipes.py
|
gloriousDan/recipe-scrapers
|
4e11b04db92abe11b75d373a147cc566629f265b
|
[
"MIT"
] | null | null | null |
tests/test_allrecipes.py
|
gloriousDan/recipe-scrapers
|
4e11b04db92abe11b75d373a147cc566629f265b
|
[
"MIT"
] | null | null | null |
tests/test_allrecipes.py
|
gloriousDan/recipe-scrapers
|
4e11b04db92abe11b75d373a147cc566629f265b
|
[
"MIT"
] | null | null | null |
from recipe_scrapers.allrecipes import AllRecipes
from tests import ScraperTest
class TestAllRecipesScraper(ScraperTest):
scraper_class = AllRecipes
def test_host(self):
self.assertEqual("allrecipes.com", self.harvester_class.host())
def test_author(self):
self.assertEqual("Michelle", self.harvester_class.author())
def test_canonical_url(self):
self.assertEqual(
"https://www.allrecipes.com/recipe/133948/four-cheese-margherita-pizza/",
self.harvester_class.canonical_url(),
)
def test_title(self):
self.assertEqual(self.harvester_class.title(), "Four Cheese Margherita Pizza")
def test_cook_time(self):
self.assertEqual(10, self.harvester_class.cook_time())
def test_prep_time(self):
self.assertEqual(15, self.harvester_class.prep_time())
def test_total_time(self):
self.assertEqual(40, self.harvester_class.total_time())
def test_yields(self):
self.assertEqual("2 servings", self.harvester_class.yields())
def test_image(self):
self.assertEqual(
"https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fimages.media-allrecipes.com%2Fuserphotos%2F694708.jpg",
self.harvester_class.image(),
)
def test_ingredients(self):
self.assertCountEqual(
[
"¼ cup olive oil",
"1 tablespoon minced garlic",
"½ teaspoon sea salt",
"8 Roma tomatoes, sliced",
"2 (12 inch) pre-baked pizza crusts",
"8 ounces shredded Mozzarella cheese",
"4 ounces shredded Fontina cheese",
"10 fresh basil leaves, washed, dried",
"½ cup freshly grated Parmesan cheese",
"½ cup crumbled feta cheese",
],
self.harvester_class.ingredients(),
)
def test_instructions(self):
return self.assertEqual(
"Stir together olive oil, garlic, and salt; toss with tomatoes, and allow to stand for 15 minutes. Preheat oven to 400 degrees F (200 degrees C).\nBrush each pizza crust with some of the tomato marinade. Sprinkle the pizzas evenly with Mozzarella and Fontina cheeses. Arrange tomatoes overtop, then sprinkle with shredded basil, Parmesan, and feta cheese.\nBake in preheated oven until the cheese is bubbly and golden brown, about 10 minutes.",
self.harvester_class.instructions(),
)
def test_ratings(self):
self.assertEqual(4.8, self.harvester_class.ratings())
def test_cuisine(self):
self.assertEqual("", self.harvester_class.cuisine())
def test_category(self):
self.assertEqual(
"World Cuisine Recipes,European,Italian", self.harvester_class.category()
)
| 37.853333
| 456
| 0.652695
|
acfed21010dd73c1468794a0a5e6f61db8fc0474
| 6,253
|
py
|
Python
|
clients/python-flask/generated/openapi_server/models/saml_configuration_property_items_array.py
|
hoomaan-kh/swagger-aem
|
0b19225bb6e071df761d176cbc13565891fe895f
|
[
"Apache-2.0"
] | null | null | null |
clients/python-flask/generated/openapi_server/models/saml_configuration_property_items_array.py
|
hoomaan-kh/swagger-aem
|
0b19225bb6e071df761d176cbc13565891fe895f
|
[
"Apache-2.0"
] | null | null | null |
clients/python-flask/generated/openapi_server/models/saml_configuration_property_items_array.py
|
hoomaan-kh/swagger-aem
|
0b19225bb6e071df761d176cbc13565891fe895f
|
[
"Apache-2.0"
] | null | null | null |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from openapi_server.models.base_model_ import Model
from openapi_server import util
class SamlConfigurationPropertyItemsArray(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
"""
def __init__(self, name: str=None, optional: bool=None, is_set: bool=None, type: int=None, values: List[str]=None, description: str=None): # noqa: E501
"""SamlConfigurationPropertyItemsArray - a model defined in OpenAPI
:param name: The name of this SamlConfigurationPropertyItemsArray. # noqa: E501
:type name: str
:param optional: The optional of this SamlConfigurationPropertyItemsArray. # noqa: E501
:type optional: bool
:param is_set: The is_set of this SamlConfigurationPropertyItemsArray. # noqa: E501
:type is_set: bool
:param type: The type of this SamlConfigurationPropertyItemsArray. # noqa: E501
:type type: int
:param values: The values of this SamlConfigurationPropertyItemsArray. # noqa: E501
:type values: List[str]
:param description: The description of this SamlConfigurationPropertyItemsArray. # noqa: E501
:type description: str
"""
self.openapi_types = {
'name': str,
'optional': bool,
'is_set': bool,
'type': int,
'values': List[str],
'description': str
}
self.attribute_map = {
'name': 'name',
'optional': 'optional',
'is_set': 'is_set',
'type': 'type',
'values': 'values',
'description': 'description'
}
self._name = name
self._optional = optional
self._is_set = is_set
self._type = type
self._values = values
self._description = description
@classmethod
def from_dict(cls, dikt) -> 'SamlConfigurationPropertyItemsArray':
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The SamlConfigurationPropertyItemsArray of this SamlConfigurationPropertyItemsArray. # noqa: E501
:rtype: SamlConfigurationPropertyItemsArray
"""
return util.deserialize_model(dikt, cls)
@property
def name(self) -> str:
"""Gets the name of this SamlConfigurationPropertyItemsArray.
property name # noqa: E501
:return: The name of this SamlConfigurationPropertyItemsArray.
:rtype: str
"""
return self._name
@name.setter
def name(self, name: str):
"""Sets the name of this SamlConfigurationPropertyItemsArray.
property name # noqa: E501
:param name: The name of this SamlConfigurationPropertyItemsArray.
:type name: str
"""
self._name = name
@property
def optional(self) -> bool:
"""Gets the optional of this SamlConfigurationPropertyItemsArray.
True if optional # noqa: E501
:return: The optional of this SamlConfigurationPropertyItemsArray.
:rtype: bool
"""
return self._optional
@optional.setter
def optional(self, optional: bool):
"""Sets the optional of this SamlConfigurationPropertyItemsArray.
True if optional # noqa: E501
:param optional: The optional of this SamlConfigurationPropertyItemsArray.
:type optional: bool
"""
self._optional = optional
@property
def is_set(self) -> bool:
"""Gets the is_set of this SamlConfigurationPropertyItemsArray.
True if property is set # noqa: E501
:return: The is_set of this SamlConfigurationPropertyItemsArray.
:rtype: bool
"""
return self._is_set
@is_set.setter
def is_set(self, is_set: bool):
"""Sets the is_set of this SamlConfigurationPropertyItemsArray.
True if property is set # noqa: E501
:param is_set: The is_set of this SamlConfigurationPropertyItemsArray.
:type is_set: bool
"""
self._is_set = is_set
@property
def type(self) -> int:
"""Gets the type of this SamlConfigurationPropertyItemsArray.
Property type, 1=String, 3=long, 11=boolean, 12=Password # noqa: E501
:return: The type of this SamlConfigurationPropertyItemsArray.
:rtype: int
"""
return self._type
@type.setter
def type(self, type: int):
"""Sets the type of this SamlConfigurationPropertyItemsArray.
Property type, 1=String, 3=long, 11=boolean, 12=Password # noqa: E501
:param type: The type of this SamlConfigurationPropertyItemsArray.
:type type: int
"""
self._type = type
@property
def values(self) -> List[str]:
"""Gets the values of this SamlConfigurationPropertyItemsArray.
Property value # noqa: E501
:return: The values of this SamlConfigurationPropertyItemsArray.
:rtype: List[str]
"""
return self._values
@values.setter
def values(self, values: List[str]):
"""Sets the values of this SamlConfigurationPropertyItemsArray.
Property value # noqa: E501
:param values: The values of this SamlConfigurationPropertyItemsArray.
:type values: List[str]
"""
self._values = values
@property
def description(self) -> str:
"""Gets the description of this SamlConfigurationPropertyItemsArray.
Property description # noqa: E501
:return: The description of this SamlConfigurationPropertyItemsArray.
:rtype: str
"""
return self._description
@description.setter
def description(self, description: str):
"""Sets the description of this SamlConfigurationPropertyItemsArray.
Property description # noqa: E501
:param description: The description of this SamlConfigurationPropertyItemsArray.
:type description: str
"""
self._description = description
| 30.207729
| 156
| 0.638094
|
acfed25ce5b7306375856c7d96681ff337db493d
| 19,695
|
py
|
Python
|
tests/test_transform.py
|
civodlu/trw
|
b9a1cf045f61d6df9c65c014ef63b4048972dcdc
|
[
"MIT"
] | 3
|
2019-07-04T01:20:41.000Z
|
2020-01-27T02:36:12.000Z
|
tests/test_transform.py
|
civodlu/trw
|
b9a1cf045f61d6df9c65c014ef63b4048972dcdc
|
[
"MIT"
] | null | null | null |
tests/test_transform.py
|
civodlu/trw
|
b9a1cf045f61d6df9c65c014ef63b4048972dcdc
|
[
"MIT"
] | 2
|
2020-10-19T13:46:06.000Z
|
2021-12-27T02:18:10.000Z
|
import collections
from unittest import TestCase
import trw.train
import trw.transforms
import numpy as np
import torch
import functools
import trw.utils
class TransformRecorder(trw.transforms.Transform):
def __init__(self, kvp, tfm_id):
self.kvp = kvp
self.tfm_id = tfm_id
def __call__(self, batch):
self.kvp[self.tfm_id] += 1
return batch
class TestTransform(TestCase):
def test_batch_pad_constant_numpy(self):
d = np.asarray([[4], [5], [6]], dtype=int)
d_transformed = trw.utils.batch_pad_numpy(d, [2], mode='constant', constant_value=9)
self.assertTrue(d_transformed.shape == (3, 5))
assert (d_transformed[0] == [9, 9, 4, 9, 9]).all()
assert (d_transformed[1] == [9, 9, 5, 9, 9]).all()
assert (d_transformed[2] == [9, 9, 6, 9, 9]).all()
def test_batch_pad_constant_torch(self):
d = np.asarray([[4], [5], [6]], dtype=int)
d = torch.from_numpy(d)
d_transformed = trw.utils.batch_pad_torch(d, [2], mode='constant', constant_value=9)
d_transformed = d_transformed.data.numpy()
self.assertTrue(d_transformed.shape == (3, 5))
assert (d_transformed[0] == [9, 9, 4, 9, 9]).all()
assert (d_transformed[1] == [9, 9, 5, 9, 9]).all()
assert (d_transformed[2] == [9, 9, 6, 9, 9]).all()
def test_batch_pad_symmetric_numpy(self):
d = np.asarray([[10, 11, 12], [20, 21, 22], [30, 31, 32]], dtype=int)
d_transformed = trw.utils.batch_pad_numpy(d, [2], mode='symmetric')
self.assertTrue(d_transformed.shape == (3, 7))
def test_batch_pad_edge_torch(self):
i1 = [[10, 11, 12], [20, 21, 22], [30, 31, 32]]
i2 = [[40, 41, 42], [50, 51, 52], [60, 61, 62]]
d = np.asarray([i1, i2], dtype=float)
d = d.reshape((2, 1, 3, 3))
d = torch.from_numpy(d)
d_transformed = trw.utils.batch_pad_torch(d, [0, 2, 3], mode='edge')
d_transformed = d_transformed.data.numpy()
self.assertTrue(d_transformed.shape == (2, 1, 7, 9))
def test_batch_pad_replicate_numpy(self):
i1 = [[10, 11, 12], [20, 21, 22], [30, 31, 32]]
i2 = [[40, 41, 42], [50, 51, 52], [60, 61, 62]]
d = np.asarray([i1, i2], dtype=float)
d = d.reshape((2, 1, 3, 3))
d_transformed = trw.utils.batch_pad_numpy(d, [0, 2, 3], mode='edge')
self.assertTrue(d_transformed.shape == (2, 1, 7, 9))
def test_batch_pad_constant_2d_numpy(self):
i1 = [[10, 11, 12], [20, 21, 22], [30, 31, 32]]
i2 = [[40, 41, 42], [50, 51, 52], [60, 61, 62]]
d = np.asarray([i1, i2], dtype=int)
d_transformed = trw.utils.batch_pad_numpy(d, [2, 3], mode='constant')
self.assertTrue(d_transformed.shape == (2, 7, 9))
def test_batch_pad_constant_2d_torch(self):
i1 = [[10, 11, 12], [20, 21, 22], [30, 31, 32]]
i2 = [[40, 41, 42], [50, 51, 52], [60, 61, 62]]
d = np.asarray([i1, i2], dtype=int)
d = torch.from_numpy(d)
d_transformed = trw.utils.batch_pad_torch(d, [2, 3], mode='constant')
d_transformed = d_transformed.data.numpy()
self.assertTrue(d_transformed.shape == (2, 7, 9))
def test_random_crop_numpy(self):
d = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=int)
d_transformed = trw.transforms.transform_batch_random_crop(d, [2])
self.assertTrue((d_transformed[0] == [1, 2]).all() or (d_transformed[0] == [2, 3]).all())
self.assertTrue((d_transformed[1] == [4, 5]).all() or (d_transformed[1] == [5, 6]).all())
self.assertTrue((d_transformed[2] == [7, 8]).all() or (d_transformed[2] == [8, 9]).all())
def test_random_crop_torch(self):
d = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=int)
d = torch.from_numpy(d)
d_transformed = trw.transforms.transform_batch_random_crop(d, [2])
d_transformed = d_transformed.data.numpy()
self.assertTrue((d_transformed[0] == [1, 2]).all() or (d_transformed[0] == [2, 3]).all())
self.assertTrue((d_transformed[1] == [4, 5]).all() or (d_transformed[1] == [5, 6]).all())
self.assertTrue((d_transformed[2] == [7, 8]).all() or (d_transformed[2] == [8, 9]).all())
def test_random_crop_padd_transform_numpy(self):
size = [1, 46, 63]
d = np.zeros([60000] + size, dtype=np.float)
d[:, size[0] // 2, size[1] // 2, size[2] // 2] = 1
transform = trw.transforms.TransformRandomCropPad(padding=[0, 8, 8])
batch = transform({'d': d})
assert batch['d'].shape == (60000, 1, 46, 63)
d_summed = np.sum(batch['d'], axis=0).squeeze()
ys, xs = np.where(d_summed > 0)
# we have set one's at the center of a 2D image, test the maximum and
# minimum displacement
self.assertTrue(min(ys) == size[1] // 2 - 8)
self.assertTrue(max(ys) == size[1] // 2 + 8)
self.assertTrue(min(xs) == size[2] // 2 - 8)
self.assertTrue(max(xs) == size[2] // 2 + 8)
def test_random_crop_padd_transform_torch(self):
size = [1, 46, 63]
nb = 60000
d = np.zeros([nb] + size, dtype=np.float)
d[:, size[0] // 2, size[1] // 2, size[2] // 2] = 1.0
d = torch.from_numpy(d)
transform = trw.transforms.TransformRandomCropPad(padding=[0, 8, 8])
batch = transform({'d': d})
d_transformed = batch['d'].data.numpy()
assert d_transformed.shape == (nb, size[0], size[1], size[2])
d_summed = np.sum(d_transformed, axis=0).squeeze()
ys, xs = np.where(d_summed > 0)
# we have set one's at the center of a 2D image, test the maximum and
# minimum displacement
self.assertTrue(min(ys) == size[1] // 2 - 8)
self.assertTrue(max(ys) == size[1] // 2 + 8)
self.assertTrue(min(xs) == size[2] // 2 - 8)
self.assertTrue(max(xs) == size[2] // 2 + 8)
def test_random_crop_no_padding(self):
size = [1, 31, 63]
d = np.zeros([1000] + size, dtype=np.float)
d[:, size[0] // 2, size[1] // 2, size[2] // 2] = 1.0
d = torch.from_numpy(d)
transform = trw.transforms.TransformRandomCropPad(padding=None, shape=[1, 16, 32])
batch = transform({'d': d})
d_transformed = batch['d'].data.numpy()
assert d_transformed.shape == (1000, 1, 16, 32)
def test_random_crop_resize(self):
size = [1, 31, 63]
d = np.zeros([1000] + size, dtype=np.float)
d[:, size[0] // 2, size[1] // 2, size[2] // 2] = 1.0
d = torch.from_numpy(d)
transform = trw.transforms.TransformRandomCropResize([16, 32])
batch = transform({'d': d})
d_transformed = batch['d'].data.numpy()
assert d_transformed.shape == (1000, 1, 31, 63)
def test_transform_base_criteria(self):
# filter by name
batch = {
'test_1': 0,
'test_2': 42,
}
criteria_fn = functools.partial(trw.transforms.criteria_feature_name, feature_names=['test_2'])
def transform_fn(features_to_transform, batch):
for name, value in batch.items():
if name in features_to_transform:
batch[name] = 43
return batch
transformer = trw.transforms.TransformBatchWithCriteria(criteria_fn=criteria_fn, transform_fn=transform_fn)
transformed_batch = transformer(batch)
assert transformed_batch['test_1'] == 0
assert transformed_batch['test_2'] == 43
def test_transform_random_flip_numpy(self):
batch = {
'images': np.asarray([
[1, 2, 3],
[4, 5, 6]
])
}
criteria_fn = functools.partial(trw.transforms.criteria_feature_name, feature_names=['images'])
transformer = trw.transforms.TransformRandomFlip(criteria_fn=criteria_fn, axis=1, flip_probability=1.0)
transformed_batch = transformer(batch)
image_fliped = transformed_batch['images']
assert len(image_fliped) == 2
assert image_fliped.shape == (2, 3)
assert image_fliped[0, 0] == 3
assert image_fliped[0, 1] == 2
assert image_fliped[0, 2] == 1
assert image_fliped[1, 0] == 6
assert image_fliped[1, 1] == 5
assert image_fliped[1, 2] == 4
# make sure the original images are NOT flipped!
image = batch['images']
assert image[0, 0] == 1
assert image[0, 1] == 2
assert image[0, 2] == 3
def test_transform_random_flip_torch(self):
batch = {
'images': torch.from_numpy(np.asarray([
[1, 2, 3],
[4, 5, 6]
]))
}
criteria_fn = functools.partial(trw.transforms.criteria_feature_name, feature_names=['images'])
transformer = trw.transforms.TransformRandomFlip(criteria_fn=criteria_fn, axis=1, flip_probability=1.0)
transformed_batch = transformer(batch)
image_fliped = transformed_batch['images']
assert len(image_fliped) == 2
assert image_fliped.shape == (2, 3)
assert image_fliped[0, 0] == 3
assert image_fliped[0, 1] == 2
assert image_fliped[0, 2] == 1
assert image_fliped[1, 0] == 6
assert image_fliped[1, 1] == 5
assert image_fliped[1, 2] == 4
# make sure the original images are NOT flipped!
image = batch['images']
assert image[0, 0] == 1
assert image[0, 1] == 2
assert image[0, 2] == 3
def test_cutout_numpy(self):
batch = {
'images': np.ones([50, 3, 64, 128], dtype=np.uint8) * 255
}
transformer = trw.transforms.TransformRandomCutout(cutout_size=(3, 16, 32))
transformed_batch = transformer(batch)
assert np.min(batch['images']) == 255, 'original image was modified!'
assert np.min(transformed_batch['images']) == 0, 'transformed image was NOT modified!'
for i in transformed_batch['images']:
nb_0 = np.where(i == 0)
assert len(nb_0[0]) == 3 * 16 * 32
def test_cutout_torch(self):
batch = {
'images': torch.ones([50, 3, 64, 128], dtype=torch.uint8) * 255
}
transformer = trw.transforms.TransformRandomCutout(cutout_size=(3, 16, 32))
transformed_batch = transformer(batch)
assert torch.min(batch['images']) == 255, 'original image was modified!'
assert torch.min(transformed_batch['images']) == 0, 'transformed image was NOT modified!'
for i in transformed_batch['images']:
nb_0 = np.where(i.numpy() == 0)
assert len(nb_0[0]) == 3 * 16 * 32
def test_cutout_size_functor(self):
batch = {
'images': torch.ones([50, 3, 64, 128], dtype=torch.uint8) * 255
}
size_functor_called = 0
def cutout_size_fn():
nonlocal size_functor_called
s = trw.transforms.cutout_random_size([3, 5, 5], [3, 10, 10])
assert s[0] == 3
assert s[1] >= 5
assert s[2] >= 5
assert s[1] <= 10
assert s[2] <= 10
size_functor_called += 1
return s
transformer = trw.transforms.TransformRandomCutout(
cutout_size=cutout_size_fn,
cutout_value_fn=trw.transforms.cutout_random_ui8_torch)
_ = transformer(batch)
assert size_functor_called == 50
def test_random_crop_pad_joint(self):
batch = {
'images': torch.zeros([50, 3, 64, 128], dtype=torch.int64),
'segmentations': torch.zeros([50, 1, 64, 128], dtype=torch.float32),
'something_else': 42,
}
batch['images'][:, :, 32, 64] = 42
batch['segmentations'][:, :, 32, 64] = 42
transformer = trw.transforms.TransformRandomCropPad(
criteria_fn=lambda batch, names: ['images', 'segmentations'],
padding=[0, 16, 16],
mode='constant')
transformed_batch = transformer(batch)
indices_images_42 = np.where(transformed_batch['images'].numpy()[:, 0, :, :] == 42)
indices_segmentations_42 = np.where(transformed_batch['segmentations'].numpy()[:, 0, :, :] == 42)
assert (indices_segmentations_42[2] == indices_images_42[2]).all()
assert (indices_segmentations_42[1] == indices_images_42[1]).all()
def test_random_flipped_joint(self):
batch = {
'images': torch.randint(high=42, size=[50, 3, 64, 128], dtype=torch.int64),
}
batch['segmentation'] = batch['images'].float()
transformer = trw.transforms.TransformRandomFlip(criteria_fn=lambda _: ['images', 'segmentation'], axis=2)
transformed_batch = transformer(batch)
images = transformed_batch['images'].float()
segmentations = transformed_batch['segmentation'].float()
assert (images == segmentations).all()
def test_random_resize_torch(self):
batch = {
'images': torch.randint(high=42, size=[50, 3, 16, 32], dtype=torch.int64),
}
transformer = trw.transforms.TransformResize(size=[32, 64])
transformed_batch = transformer(batch)
images = transformed_batch['images']
assert images.shape == (50, 3, 32, 64)
assert np.average(batch['images'].numpy()) == np.average(transformed_batch['images'].numpy())
def test_random_resize_numpy(self):
batch = {
'images': np.random.randint(low=0, high=42, size=[50, 3, 16, 32], dtype=np.int64),
}
transformer = trw.transforms.TransformResize(size=[32, 64], mode='nearest')
transformed_batch = transformer(batch)
images = transformed_batch['images']
assert images.shape == (50, 3, 32, 64)
assert np.average(batch['images']) == np.average(transformed_batch['images'])
def test_normalize_numpy(self):
images = np.random.randint(low=0, high=42, size=[10, 3, 5, 6], dtype=np.int64)
images[:, 1] *= 2
images[:, 2] *= 3
batch = {
'images': images,
}
mean = np.mean(images, axis=(0, 2, 3))
std = np.std(images, axis=(0, 2, 3))
transformer = trw.transforms.TransformNormalizeIntensity(mean=mean, std=std)
transformed_batch = transformer(batch)
normalized_images = transformed_batch['images']
mean_normalized = np.mean(normalized_images, axis=(0, 2, 3))
std_normalized = np.std(normalized_images, axis=(0, 2, 3))
assert abs(np.average(mean_normalized)) < 0.1
assert abs(np.average(std_normalized) - 1) < 0.1
def test_normalize_torch(self):
images = torch.randint(high=42, size=[10, 3, 5, 6], dtype=torch.float32)
images[:, 1] *= 2
images[:, 2] *= 3
batch = {
'images': images,
}
mean = np.mean(images.numpy(), axis=(0, 2, 3), dtype=np.float32)
std = np.std(images.numpy(), axis=(0, 2, 3), dtype=np.float32)
transformer = trw.transforms.TransformNormalizeIntensity(mean=mean, std=std)
transformed_batch = transformer(batch)
normalized_images = transformed_batch['images']
mean_normalized = np.mean(normalized_images.numpy(), axis=(0, 2, 3))
std_normalized = np.std(normalized_images.numpy(), axis=(0, 2, 3))
assert abs(np.average(mean_normalized)) < 0.1
assert abs(np.average(std_normalized) - 1) < 0.1
def test_transform_compose(self):
batch = {
'images': torch.randint(high=42, size=[10, 3, 5, 6], dtype=torch.int64).float()
}
transforms = [
trw.transforms.TransformNormalizeIntensity(mean=[np.float32(10), np.float32(10), np.float32(10)], std=[np.float32(1), np.float32(1), np.float32(1)]),
trw.transforms.TransformNormalizeIntensity(mean=[np.float32(100), np.float32(100), np.float32(100)], std=[np.float32(1), np.float32(1), np.float32(1)]),
]
transformer = trw.transforms.TransformCompose(transforms)
transformed_batch = transformer(batch)
max_error = torch.max(torch.abs(batch['images'] - transformed_batch['images'] - 110))
assert float(max_error) < 1e-5
def test_transform_random_flip_joint(self):
np.random.seed(0)
batch = {
'images': np.asarray([
[1, 2, 3],
[4, 5, 6],
]),
'images2': np.asarray([
[1, 2, 3],
[4, 5, 6],
])
}
transformer = trw.transforms.TransformRandomFlip(
criteria_fn=lambda _: ['images', 'images2'],
axis=1,
flip_probability=0.5)
transformed_batch = transformer(batch)
image_fliped = transformed_batch['images']
image_fliped2 = transformed_batch['images2']
assert len(image_fliped) == 2
assert image_fliped.shape == (2, 3)
assert (image_fliped == image_fliped2).all()
# make sure the original images are NOT flipped!
image = batch['images']
assert image[0, 0] == 1
assert image[0, 1] == 2
assert image[0, 2] == 3
def test_batch_crop(self):
i = np.random.randint(0, 100, [16, 20, 24, 28])
c = trw.transforms.batch_crop(i, [10, 11, 12], [12, 15, 20])
assert c.shape == (16, 2, 4, 8)
assert (c == i[:, 10:12, 11:15, 12:20]).all()
def test_cast_numpy(self):
batch = {
'float': np.zeros([10], dtype=np.long),
'long': np.zeros([10], dtype=np.long),
'byte': np.zeros([10], dtype=np.long),
}
transforms = [
trw.transforms.TransformCast(['float'], 'float'),
trw.transforms.TransformCast(['long'], 'long'),
trw.transforms.TransformCast(['byte'], 'byte'),
]
tfm = trw.transforms.TransformCompose(transforms)
batch_tfm = tfm(batch)
assert batch_tfm['float'].dtype == np.float32
assert batch_tfm['long'].dtype == np.long
assert batch_tfm['byte'].dtype == np.byte
def test_cast_torch(self):
batch = {
'float': torch.zeros([10], dtype=torch.long),
'long': torch.zeros([10], dtype=torch.float),
'byte': torch.zeros([10], dtype=torch.long),
}
transforms = [
trw.transforms.TransformCast(['float'], 'float'),
trw.transforms.TransformCast(['long'], 'long'),
trw.transforms.TransformCast(['byte'], 'byte'),
]
tfm = trw.transforms.TransformCompose(transforms)
batch_tfm = tfm(batch)
assert batch_tfm['float'].dtype == torch.float32
assert batch_tfm['long'].dtype == torch.long
assert batch_tfm['byte'].dtype == torch.int8
def test_one_of(self):
np.random.seed(0)
nb_samples = 10000
split = {
'float': torch.zeros([nb_samples], dtype=torch.long),
}
kvp = collections.defaultdict(lambda: 0)
transforms = [
TransformRecorder(kvp, 0),
TransformRecorder(kvp, 1),
TransformRecorder(kvp, 2),
]
tfm = trw.transforms.TransformOneOf(transforms)
for b in trw.train.SequenceArray(split):
_ = tfm(b)
nb_transforms_applied = sum(kvp.values())
assert nb_transforms_applied == nb_samples
tolerance = 0.01 * nb_samples
for tfm, tfm_count in kvp.items():
deviation = abs(tfm_count - nb_samples / len(transforms))
assert deviation < tolerance, f'deviation={deviation}, tolerance={tolerance}'
| 37.875
| 164
| 0.576593
|
acfed3fb3ce5d583d7390a9cd8e5d4c7b1d8cb06
| 615
|
py
|
Python
|
posts/management/commands/cleanup_post_views.py
|
dimabory/vas3k.club
|
178154a8d6d2925fb392599d65da3e60082c8f37
|
[
"MIT"
] | 1
|
2021-04-12T13:38:41.000Z
|
2021-04-12T13:38:41.000Z
|
posts/management/commands/cleanup_post_views.py
|
dimabory/vas3k.club
|
178154a8d6d2925fb392599d65da3e60082c8f37
|
[
"MIT"
] | null | null | null |
posts/management/commands/cleanup_post_views.py
|
dimabory/vas3k.club
|
178154a8d6d2925fb392599d65da3e60082c8f37
|
[
"MIT"
] | null | null | null |
import logging
from datetime import datetime, timedelta
from django.core.management import BaseCommand
from posts.models import PostView
log = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Cleans up old and useless post views"
def handle(self, *args, **options):
day_ago = datetime.utcnow() - timedelta(days=1)
PostView.objects.filter(unread_comments=0, registered_view_at__lte=day_ago).delete()
# month_ago = datetime.utcnow() - timedelta(days=30)
# PostView.objects.filter(last_view_at__lte=month_ago).delete()
self.stdout.write("Done 🥙")
| 27.954545
| 92
| 0.721951
|
acfed4bd2bd036d6a1398f4da0fd9e42903c9c3e
| 11,439
|
py
|
Python
|
dymos/examples/brachistochrone/test/test_brachistochrone_undecorated_ode.py
|
naylor-b/dymos
|
56ee72041056ae20c3332d060e291c4da93844b1
|
[
"Apache-2.0"
] | null | null | null |
dymos/examples/brachistochrone/test/test_brachistochrone_undecorated_ode.py
|
naylor-b/dymos
|
56ee72041056ae20c3332d060e291c4da93844b1
|
[
"Apache-2.0"
] | null | null | null |
dymos/examples/brachistochrone/test/test_brachistochrone_undecorated_ode.py
|
naylor-b/dymos
|
56ee72041056ae20c3332d060e291c4da93844b1
|
[
"Apache-2.0"
] | null | null | null |
from __future__ import print_function, division, absolute_import
import unittest
import numpy as np
from openmdao.api import ExplicitComponent
class BrachistochroneODE(ExplicitComponent):
def initialize(self):
self.options.declare('num_nodes', types=int)
def setup(self):
nn = self.options['num_nodes']
# Inputs
self.add_input('v', val=np.zeros(nn), desc='velocity', units='m/s')
self.add_input('g', val=9.80665 * np.ones(nn), desc='grav. acceleration', units='m/s/s')
self.add_input('theta', val=np.zeros(nn), desc='angle of wire', units='rad')
self.add_output('xdot', val=np.zeros(nn), desc='velocity component in x', units='m/s')
self.add_output('ydot', val=np.zeros(nn), desc='velocity component in y', units='m/s')
self.add_output('vdot', val=np.zeros(nn), desc='acceleration magnitude', units='m/s**2')
self.add_output('check', val=np.zeros(nn), desc='check solution: v/sin(theta) = constant',
units='m/s')
# Setup partials
arange = np.arange(self.options['num_nodes'])
self.declare_partials(of='vdot', wrt='g', rows=arange, cols=arange)
self.declare_partials(of='vdot', wrt='theta', rows=arange, cols=arange)
self.declare_partials(of='xdot', wrt='v', rows=arange, cols=arange)
self.declare_partials(of='xdot', wrt='theta', rows=arange, cols=arange)
self.declare_partials(of='ydot', wrt='v', rows=arange, cols=arange)
self.declare_partials(of='ydot', wrt='theta', rows=arange, cols=arange)
self.declare_partials(of='check', wrt='v', rows=arange, cols=arange)
self.declare_partials(of='check', wrt='theta', rows=arange, cols=arange)
def compute(self, inputs, outputs):
theta = inputs['theta']
cos_theta = np.cos(theta)
sin_theta = np.sin(theta)
g = inputs['g']
v = inputs['v']
outputs['vdot'] = g * cos_theta
outputs['xdot'] = v * sin_theta
outputs['ydot'] = -v * cos_theta
outputs['check'] = v / sin_theta
def compute_partials(self, inputs, jacobian):
theta = inputs['theta']
cos_theta = np.cos(theta)
sin_theta = np.sin(theta)
g = inputs['g']
v = inputs['v']
jacobian['vdot', 'g'] = cos_theta
jacobian['vdot', 'theta'] = -g * sin_theta
jacobian['xdot', 'v'] = sin_theta
jacobian['xdot', 'theta'] = v * cos_theta
jacobian['ydot', 'v'] = -cos_theta
jacobian['ydot', 'theta'] = v * sin_theta
jacobian['check', 'v'] = 1 / sin_theta
jacobian['check', 'theta'] = -v * cos_theta / sin_theta**2
class TestBrachistochroneUndecoratedODE(unittest.TestCase):
def test_brachistochrone_undecorated_ode_gl(self):
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from openmdao.api import Problem, Group, ScipyOptimizeDriver, DirectSolver
from openmdao.utils.assert_utils import assert_rel_error
from dymos import Phase, GaussLobatto
p = Problem(model=Group())
p.driver = ScipyOptimizeDriver()
phase = Phase(ode_class=BrachistochroneODE, transcription=GaussLobatto(num_segments=10))
p.model.add_subsystem('phase0', phase)
phase.set_time_options(initial_bounds=(0, 0), duration_bounds=(.5, 10), units='s')
phase.set_state_options('x', fix_initial=True, fix_final=True, rate_source='xdot', units='m')
phase.set_state_options('y', fix_initial=True, fix_final=True, rate_source='ydot', units='m')
phase.set_state_options('v', fix_initial=True, rate_source='vdot', targets=['v'], units='m/s')
phase.add_control('theta', units='deg', rate_continuity=False, lower=0.01, upper=179.9, targets=['theta'])
phase.add_design_parameter('g', units='m/s**2', opt=False, val=9.80665, targets=['g'])
# Minimize time at the end of the phase
phase.add_objective('time', loc='final', scaler=10)
p.model.linear_solver = DirectSolver()
p.setup()
p['phase0.t_initial'] = 0.0
p['phase0.t_duration'] = 2.0
p['phase0.states:x'] = phase.interpolate(ys=[0, 10], nodes='state_input')
p['phase0.states:y'] = phase.interpolate(ys=[10, 5], nodes='state_input')
p['phase0.states:v'] = phase.interpolate(ys=[0, 9.9], nodes='state_input')
p['phase0.controls:theta'] = phase.interpolate(ys=[5, 100.5], nodes='control_input')
# Solve for the optimal trajectory
p.run_driver()
# Test the results
assert_rel_error(self, p.get_val('phase0.timeseries.time')[-1], 1.8016, tolerance=1.0E-3)
def test_brachistochrone_undecorated_ode_radau(self):
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from openmdao.api import Problem, Group, ScipyOptimizeDriver, DirectSolver
from openmdao.utils.assert_utils import assert_rel_error
from dymos import Phase, Radau
p = Problem(model=Group())
p.driver = ScipyOptimizeDriver()
phase = Phase(ode_class=BrachistochroneODE, transcription=Radau(num_segments=10))
p.model.add_subsystem('phase0', phase)
phase.set_time_options(initial_bounds=(0, 0), duration_bounds=(.5, 10), units='s')
phase.set_state_options('x', fix_initial=True, fix_final=True, rate_source='xdot', units='m')
phase.set_state_options('y', fix_initial=True, fix_final=True, rate_source='ydot', units='m')
phase.set_state_options('v', fix_initial=True, rate_source='vdot', targets=['v'], units='m/s')
phase.add_control('theta', units='deg', rate_continuity=False, lower=0.01, upper=179.9, targets=['theta'])
phase.add_design_parameter('g', units='m/s**2', opt=False, val=9.80665, targets=['g'])
# Minimize time at the end of the phase
phase.add_objective('time', loc='final', scaler=10)
p.model.linear_solver = DirectSolver()
p.setup()
p['phase0.t_initial'] = 0.0
p['phase0.t_duration'] = 2.0
p['phase0.states:x'] = phase.interpolate(ys=[0, 10], nodes='state_input')
p['phase0.states:y'] = phase.interpolate(ys=[10, 5], nodes='state_input')
p['phase0.states:v'] = phase.interpolate(ys=[0, 9.9], nodes='state_input')
p['phase0.controls:theta'] = phase.interpolate(ys=[5, 100.5], nodes='control_input')
# Solve for the optimal trajectory
p.run_driver()
# Test the results
assert_rel_error(self, p.get_val('phase0.timeseries.time')[-1], 1.8016, tolerance=1.0E-3)
def test_brachistochrone_undecorated_ode_rk(self):
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from openmdao.api import Problem, Group, ScipyOptimizeDriver, DirectSolver
from openmdao.utils.assert_utils import assert_rel_error
from dymos import Phase, RungeKutta
p = Problem(model=Group())
p.driver = ScipyOptimizeDriver()
phase = Phase(ode_class=BrachistochroneODE, transcription=RungeKutta(num_segments=20))
p.model.add_subsystem('phase0', phase)
phase.set_time_options(initial_bounds=(0, 0), duration_bounds=(.5, 10), units='s')
phase.set_state_options('x', fix_initial=True, rate_source='xdot', units='m')
phase.set_state_options('y', fix_initial=True, rate_source='ydot', units='m')
phase.set_state_options('v', fix_initial=True, rate_source='vdot', targets=['v'], units='m/s')
phase.add_control('theta', units='deg', rate_continuity=False, lower=0.01, upper=179.9, targets=['theta'])
phase.add_design_parameter('g', units='m/s**2', opt=False, val=9.80665, targets=['g'])
phase.add_boundary_constraint('x', loc='final', equals=10)
phase.add_boundary_constraint('y', loc='final', equals=5)
# Minimize time at the end of the phase
phase.add_objective('time', loc='final', scaler=10)
p.model.linear_solver = DirectSolver()
p.setup()
p['phase0.t_initial'] = 0.0
p['phase0.t_duration'] = 2.0
p['phase0.states:x'] = phase.interpolate(ys=[0, 10], nodes='state_input')
p['phase0.states:y'] = phase.interpolate(ys=[10, 5], nodes='state_input')
p['phase0.states:v'] = phase.interpolate(ys=[0, 9.9], nodes='state_input')
p['phase0.controls:theta'] = phase.interpolate(ys=[5, 100.5], nodes='control_input')
# Solve for the optimal trajectory
p.run_driver()
# Test the results
assert_rel_error(self, p.get_val('phase0.timeseries.time')[-1], 1.8016, tolerance=1.0E-3)
class TestBrachistochroneBasePhaseClass(unittest.TestCase):
def test_brachistochrone_base_phase_class_gl(self):
from openmdao.api import Problem, Group, ScipyOptimizeDriver, DirectSolver
from openmdao.utils.assert_utils import assert_rel_error
from dymos import Phase, GaussLobatto
class BrachistochronePhase(Phase):
def setup(self):
self.options['ode_class'] = BrachistochroneODE
self.set_time_options(initial_bounds=(0, 0), duration_bounds=(.5, 10), units='s')
self.set_state_options('x', fix_initial=True, rate_source='xdot', units='m')
self.set_state_options('y', fix_initial=True, rate_source='ydot', units='m')
self.set_state_options('v', fix_initial=True, rate_source='vdot', targets=['v'],
units='m/s')
self.add_control('theta', units='deg', rate_continuity=False,
lower=0.01, upper=179.9, targets=['theta'])
self.add_design_parameter('g', units='m/s**2', opt=False, val=9.80665,
targets=['g'])
super(BrachistochronePhase, self).setup()
p = Problem(model=Group())
p.driver = ScipyOptimizeDriver()
phase = BrachistochronePhase(transcription=GaussLobatto(num_segments=20, order=3))
p.model.add_subsystem('phase0', phase)
phase.add_boundary_constraint('x', loc='final', equals=10)
phase.add_boundary_constraint('y', loc='final', equals=5)
# Minimize time at the end of the phase
phase.add_objective('time', loc='final', scaler=10)
p.model.linear_solver = DirectSolver()
p.setup()
p['phase0.t_initial'] = 0.0
p['phase0.t_duration'] = 2.0
p['phase0.states:x'] = phase.interpolate(ys=[0, 10], nodes='state_input')
p['phase0.states:y'] = phase.interpolate(ys=[10, 5], nodes='state_input')
p['phase0.states:v'] = phase.interpolate(ys=[0, 9.9], nodes='state_input')
p['phase0.controls:theta'] = phase.interpolate(ys=[5, 100.5], nodes='control_input')
# Solve for the optimal trajectory
p.run_driver()
# Test the results
assert_rel_error(self, p.get_val('phase0.timeseries.time')[-1], 1.8016, tolerance=1.0E-3)
exp_out = phase.simulate()
assert_rel_error(self, exp_out.get_val('phase0.timeseries.states:x')[-1], 10, tolerance=1.0E-3)
assert_rel_error(self, exp_out.get_val('phase0.timeseries.states:y')[-1], 5, tolerance=1.0E-3)
| 40.278169
| 114
| 0.634496
|
acfed52bb6497ce5fb06e49460f94e77f3a7ee78
| 7,306
|
py
|
Python
|
VideoTranscriptClassification/video_indexer.py
|
MACEL94/media-services-video-indexer
|
b4076daa7a7cdad456ce696b50f77ce2f21ead22
|
[
"MIT"
] | 54
|
2020-01-16T22:18:07.000Z
|
2022-03-24T15:58:16.000Z
|
VideoTranscriptClassification/video_indexer.py
|
MACEL94/media-services-video-indexer
|
b4076daa7a7cdad456ce696b50f77ce2f21ead22
|
[
"MIT"
] | 10
|
2020-07-19T19:01:31.000Z
|
2022-02-09T09:49:00.000Z
|
VideoTranscriptClassification/video_indexer.py
|
MACEL94/media-services-video-indexer
|
b4076daa7a7cdad456ce696b50f77ce2f21ead22
|
[
"MIT"
] | 43
|
2020-02-13T05:36:42.000Z
|
2022-03-09T15:39:57.000Z
|
# Original source code: https://github.com/bklim5/python_video_indexer_lib
import os
import re
import time
import datetime
import requests
def get_retry_after_from_message(message):
match = re.search(r'Try again in (\d+) second', message or '')
if match:
return int(match.group(1))
return 30 # default to retry in 30 seconds
class VideoIndexer():
def __init__(self, vi_subscription_key, vi_location, vi_account_id):
self.vi_subscription_key = vi_subscription_key
self.vi_location = vi_location
self.vi_account_id = vi_account_id
self.access_token = None
self.access_token_timestamp = None
self.video_name_to_id_dict = None
self.get_access_token()
def del_video(self, video_id):
self.check_access_token()
params = {
'accessToken': self.access_token
}
delete_video = requests.delete(
'https://api.videoindexer.ai/{loc}/Accounts/{acc_id}/Videos/{videoId}?{access_token}'.format( # NOQA E501
loc=self.vi_location,
acc_id=self.vi_account_id,
videoId=video_id,
access_token=self.access_token
),
params=params
)
try:
print(delete_video.json())
except Exception as ex:
print("Response:", delete_video)
return delete_video
def get_access_token(self):
print('Getting video indexer access token...')
headers = {
'Ocp-Apim-Subscription-Key': self.vi_subscription_key
}
params = {
'allowEdit': 'true'
}
access_token_req = requests.get(
'https://api.videoindexer.ai/auth/{loc}/Accounts/{acc_id}/AccessToken'.format( # NOQA E501
loc=self.vi_location,
acc_id=self.vi_account_id
),
params=params,
headers=headers
)
access_token = access_token_req.text[1:-1]
print('Access Token: {}'.format(access_token))
self.access_token = access_token
self.access_token_timestamp = datetime.datetime.now()
return access_token
def get_all_videos_list(self):
all_videos_list = []
done = False
skip = 0
page_size = 200
while(not done):
response = self.get_videos_list(page_size=page_size, skip=skip)
all_videos_list.extend(response['results'])
next_page = response['nextPage']
skip = next_page['skip']
page_size = next_page['pageSize']
done = next_page['done']
return all_videos_list
def get_videos_list(self, page_size=25, skip=0):
self.check_access_token()
params = {
'accessToken': self.access_token,
'pageSize': page_size,
'skip': skip
}
print('Getting videos list..')
get_videos_list = requests.get(
'https://api.videoindexer.ai/{loc}/Accounts/{acc_id}/Videos'.format( # NOQA E501
loc=self.vi_location,
acc_id=self.vi_account_id
),
params=params
)
response = get_videos_list.json()
return response
def check_access_token(self):
delta = datetime.datetime.now() - self.access_token_timestamp
if delta > datetime.timedelta(minutes=50):
self.get_access_token()
def upload_to_video_indexer(
self, video_url, name,
force_upload_if_exists=False,
video_language='English', streaming_preset='Default',
indexing_preset='Default',
verbose=False
):
self.check_access_token()
# file_name = os.path.basename(os.path.splitext(video_url)[0])
if self.video_name_to_id_dict is None:
self.get_video_name_to_id_dict()
if name in self.video_name_to_id_dict.keys():
if verbose:
print("Video with the same name already exists in current Video Indexer account.") # NOQA E501
if not force_upload_if_exists:
return self.video_name_to_id_dict[name]
if verbose:
print("'force_upload_if_exists' set to 'True' so uploading the file anyway.")
if verbose:
print('Uploading video to video indexer...')
params = {
'streamingPreset': streaming_preset,
'indexingPreset': indexing_preset,
'language': video_language,
'name': name,
'accessToken': self.access_token
}
files = {}
if "http" in video_url.lower():
params['videoUrl'] = video_url
else:
files = {
'file': open(video_url, 'rb')
}
retry = True
while retry:
upload_video_req = requests.post(
'https://api.videoindexer.ai/{loc}/Accounts/{acc_id}/Videos'.format( # NOQA E501
loc=self.vi_location,
acc_id=self.vi_account_id
),
params=params,
files=files
)
if upload_video_req.status_code == 200:
retry = False
break
# hit throttling limit, sleep and retry
if upload_video_req.status_code == 429:
error_resp = upload_video_req.json()
if verbose:
print('Throttling limit hit. Error message: {}'.format(
error_resp.get('message')))
retry_after = get_retry_after_from_message(
error_resp.get('message'))
time.sleep(retry_after + 1)
continue
if verbose:
print('Error uploading video to video indexer: {}'.format(
upload_video_req.json()))
raise Exception('Error uploading video to video indexer')
response = upload_video_req.json()
return response['id']
def get_video_info(self, video_id, video_language='English', verbose=False):
self.check_access_token()
params = {
'accessToken': self.access_token,
'language': video_language
}
if verbose:
print('Getting video info for: {}'.format(video_id))
get_video_info_req = requests.get(
'https://api.videoindexer.ai/{loc}/Accounts/{acc_id}/Videos/{video_id}/Index'.format( # NOQA E501
loc=self.vi_location,
acc_id=self.vi_account_id,
video_id=video_id
),
params=params
)
response = get_video_info_req.json()
if response['state'] == 'Processing':
if verbose:
print('Video still processing, current status: {}'.format(
response['videos'][0]['processingProgress'],
))
return response
def get_video_name_to_id_dict(self):
all_videos = self.get_all_videos_list()
names = [video['name'] for video in all_videos]
ids = [video['id'] for video in all_videos]
self.video_name_to_id_dict = dict(zip(names, ids))
return self.video_name_to_id_dict
| 33.668203
| 118
| 0.571722
|
acfed5aaf4b83a8eed69ad9ccc18a0818f0b4dcb
| 2,930
|
py
|
Python
|
flTile/input/genericInputMapper.py
|
rpwagner/tiled-display
|
52d135bc163360fe55ce5521784b0ef48a8c82c9
|
[
"Apache-2.0"
] | 1
|
2020-12-11T17:11:45.000Z
|
2020-12-11T17:11:45.000Z
|
flTile/input/genericInputMapper.py
|
rpwagner/tiled-display
|
52d135bc163360fe55ce5521784b0ef48a8c82c9
|
[
"Apache-2.0"
] | null | null | null |
flTile/input/genericInputMapper.py
|
rpwagner/tiled-display
|
52d135bc163360fe55ce5521784b0ef48a8c82c9
|
[
"Apache-2.0"
] | null | null | null |
import traceback
from inputMapper import InputMapper
class GenericMsgCallback:
# Holds a callback function, a "type" and "arguments" for it, and
# whether the callback expects the type and arguments.
def __init__(self, callback, passMsgType=False, passMsgArgs=True, extraArgs=None):
self.callback = callback
self.passMsgType=passMsgType
self.passMsgArgs=passMsgArgs
if extraArgs == None:
self.extraArgs = []
else:
self.extraArgs=extraArgs
# only self.call will be used
# setup a simpler callback to avoid if tree for every input msg.
if passMsgType and passMsgArgs:
self.call = self._callWithMsgTypeAndArgs
elif passMsgType and not passMsgArgs:
self.call = self._callWithMsgTypeNoArgs
elif not passMsgType and passMsgArgs:
self.call = self._callWithNoMsgTypeWithArgs
elif not passMsgType and not passMsgArgs:
self.call = self._callWithNoMsgTypeNoArgs
def _callWithMsgTypeAndArgs(self, msgType, msgArgList):
argList = [msgType] + msgArgList + self.extraArgs
self.callback(*argList)
def _callWithMsgTypeNoArgs(self, msgType, msgArgList):
argList = [msgType] + self.extraArgs
print "CALLING WITH ARGLIST:", argList
self.callback(*argList)
def _callWithNoMsgTypeWithArgs(self, msgType, msgArgList):
argList = msgArgList + self.extraArgs
self.callback(*argList)
def _callWithNoMsgTypeNoArgs(self, msgType, msgArgList):
self.callback(*self.extraArgs)
call = _callWithNoMsgTypeWithArgs # overridden during initialization
class GenericInputMapper(InputMapper):
# Maps an input type to a callback
# Will processInput() to call the callback()
def __init__(self, target=None):
InputMapper.__init__(self)
self.target = target
self.inputMap = {} # maps inputs to controls
def mapMsgTypeToTargetControl(self, msgType, controlName, passMsgType = False, passMsgArgs = True, extraArgs=None):
callbackFunc = getattr(self.target, controlName)
callback = GenericMsgCallback( callbackFunc, passMsgType=passMsgType, passMsgArgs=passMsgArgs, extraArgs=extraArgs)
self.inputMap[msgType] = callback
def mapMsgTypeToCallback(self, msgType, callbackFunc, passMsgType = False, passMsgArgs = True, extraArgs=None):
callback = GenericMsgCallback( callbackFunc, passMsgType=passMsgType, passMsgArgs=passMsgArgs, extraArgs=extraArgs)
self.inputMap[msgType] = callback
def processInput(self, msgType, argList):
try:
#print "processInput:", msgType, argList
if msgType in self.inputMap:
self.inputMap[msgType].call(msgType,argList)
# self.target.setPos( argList[0], argList[1] )
except:
traceback.print_exc()
| 41.267606
| 123
| 0.683276
|
acfed739159a8c1bef2742e60c5be889bec8e6a4
| 9,946
|
py
|
Python
|
tests/test_rl.py
|
Chia-Network/internal-custody
|
672cf33bb63cad960f5576f84a6606ce471e05cb
|
[
"Apache-2.0"
] | null | null | null |
tests/test_rl.py
|
Chia-Network/internal-custody
|
672cf33bb63cad960f5576f84a6606ce471e05cb
|
[
"Apache-2.0"
] | null | null | null |
tests/test_rl.py
|
Chia-Network/internal-custody
|
672cf33bb63cad960f5576f84a6606ce471e05cb
|
[
"Apache-2.0"
] | 1
|
2022-02-22T22:35:24.000Z
|
2022-02-22T22:35:24.000Z
|
import math
import pytest
from blspy import G2Element
from dataclasses import dataclass
from chia.clvm.spend_sim import SpendSim, SimClient
from chia.types.blockchain_format.coin import Coin
from chia.types.blockchain_format.program import Program
from chia.types.blockchain_format.sized_bytes import bytes32
from chia.types.mempool_inclusion_status import MempoolInclusionStatus
from chia.types.spend_bundle import SpendBundle
from chia.types.coin_spend import CoinSpend
from chia.util.errors import Err
from chia.util.ints import uint64
from chia.wallet.lineage_proof import LineageProof
from cic.drivers.rate_limiting import construct_rate_limiting_puzzle, solve_rate_limiting_puzzle
from cic.drivers.singleton import construct_singleton, generate_launch_conditions_and_coin_spend, solve_singleton
from tests.cost_logger import CostLogger
ACS = Program.to(1)
ACS_PH = ACS.get_tree_hash()
@pytest.fixture(scope="module")
def cost_logger():
return CostLogger()
@dataclass
class SetupInfo:
sim: SpendSim
sim_client: SimClient
singleton: Coin
launcher_id: bytes32
first_lineage_proof: LineageProof
start_date: uint64
drain_rate: uint64
@pytest.fixture(scope="function")
async def setup_info():
sim = await SpendSim.create()
sim_client = SimClient(sim)
await sim.farm_block(ACS_PH)
# Define constants
START_DATE = uint64(sim.timestamp)
DRAIN_RATE = 1 # 1 mojo per second
# Identify the coin
prefarm_coins = await sim_client.get_coin_records_by_puzzle_hashes([ACS_PH])
coin = next(cr.coin for cr in prefarm_coins if cr.coin.amount == 18375000000000000000)
# Launch it to the starting state
starting_amount = 18374999999999999999
conditions, launch_spend = generate_launch_conditions_and_coin_spend(
coin,
construct_rate_limiting_puzzle(START_DATE, starting_amount, DRAIN_RATE, uint64(1), ACS),
18374999999999999999,
)
creation_bundle = SpendBundle(
[
CoinSpend(
coin,
ACS,
Program.to(conditions),
),
launch_spend,
],
G2Element(),
)
# Process the state
await sim_client.push_tx(creation_bundle)
await sim.farm_block()
# Identify the coin again
coin = next(coin for coin in (await sim.all_non_reward_coins()) if coin.amount == 18374999999999999999)
return SetupInfo(
sim,
sim_client,
coin,
launch_spend.coin.name(),
LineageProof(parent_name=launch_spend.coin.parent_coin_info, amount=launch_spend.coin.amount),
START_DATE,
DRAIN_RATE,
)
@pytest.mark.asyncio
async def test_draining(setup_info, cost_logger):
try:
# Setup the conditions to drain
TO_DRAIN = uint64(10)
setup_info.sim.pass_time(uint64(math.ceil(TO_DRAIN / setup_info.drain_rate) + 1))
drain_time: uint64 = setup_info.sim.timestamp
await setup_info.sim.farm_block()
# Construct the spend
initial_rl_puzzle: Program = construct_rate_limiting_puzzle(
setup_info.start_date, setup_info.singleton.amount, setup_info.drain_rate, uint64(1), ACS
)
first_drain_spend = SpendBundle(
[
CoinSpend(
setup_info.singleton,
construct_singleton(
setup_info.launcher_id,
initial_rl_puzzle,
),
solve_singleton(
setup_info.first_lineage_proof,
setup_info.singleton.amount,
solve_rate_limiting_puzzle(
drain_time,
Program.to([[51, ACS_PH, setup_info.singleton.amount - TO_DRAIN]]),
),
),
),
],
G2Element(),
)
# Process the results
result = await setup_info.sim_client.push_tx(first_drain_spend)
assert result[0] == MempoolInclusionStatus.SUCCESS
await setup_info.sim.farm_block()
cost_logger.add_cost("Drain some", first_drain_spend)
# Find the new coin
new_coin: Coin = (await setup_info.sim_client.get_coin_records_by_parent_ids([setup_info.singleton.name()]))[
0
].coin
# Setup again
TO_DRAIN = uint64(20)
setup_info.sim.pass_time(uint64(math.ceil(TO_DRAIN / setup_info.drain_rate) + 1))
next_drain_time: uint64 = setup_info.sim.timestamp
await setup_info.sim.farm_block()
# Create the next spend
second_drain_spend = SpendBundle(
[
CoinSpend(
new_coin,
construct_singleton(
setup_info.launcher_id,
initial_rl_puzzle,
),
solve_singleton(
LineageProof(
setup_info.singleton.parent_coin_info,
initial_rl_puzzle.get_tree_hash(),
setup_info.singleton.amount,
),
new_coin.amount,
solve_rate_limiting_puzzle(
next_drain_time,
Program.to([[51, ACS_PH, new_coin.amount - TO_DRAIN]]),
),
),
),
],
G2Element(),
)
# Process the results
result = await setup_info.sim_client.push_tx(second_drain_spend)
assert result[0] == MempoolInclusionStatus.SUCCESS
await setup_info.sim.farm_block()
cost_logger.add_cost("Drain again", second_drain_spend)
# Check the child's puzzle hash
new_coin: Coin = (await setup_info.sim_client.get_coin_records_by_parent_ids([new_coin.name()]))[0].coin
assert (
new_coin.puzzle_hash
== construct_singleton(
setup_info.launcher_id,
initial_rl_puzzle,
).get_tree_hash()
)
finally:
await setup_info.sim.close()
@pytest.mark.asyncio
async def test_cant_drain_more(setup_info, cost_logger):
try:
# Setup the conditions to drain
TO_DRAIN = uint64(10)
setup_info.sim.pass_time(uint64(0)) # Oops forgot to pass the time
drain_time = uint64(math.ceil(TO_DRAIN / setup_info.drain_rate) + 1)
await setup_info.sim.farm_block()
# Construct the spend
initial_rl_puzzle: Program = construct_rate_limiting_puzzle(
setup_info.start_date, setup_info.singleton.amount, setup_info.drain_rate, uint64(1), ACS
)
drain_spend = SpendBundle(
[
CoinSpend(
setup_info.singleton,
construct_singleton(
setup_info.launcher_id,
initial_rl_puzzle,
),
solve_singleton(
setup_info.first_lineage_proof,
setup_info.singleton.amount,
solve_rate_limiting_puzzle(
drain_time,
Program.to([[51, ACS_PH, setup_info.singleton.amount - TO_DRAIN]]),
),
),
),
],
G2Element(),
)
# Make sure it fails
result = await setup_info.sim_client.push_tx(drain_spend)
assert result == (MempoolInclusionStatus.FAILED, Err.ASSERT_SECONDS_ABSOLUTE_FAILED)
finally:
await setup_info.sim.close()
@pytest.mark.asyncio
async def test_refill_is_ignored(setup_info, cost_logger):
try:
# First let's farm ourselves some funds
await setup_info.sim.farm_block(ACS_PH)
fund_coin: Coin = (
await setup_info.sim_client.get_coin_records_by_puzzle_hashes([ACS_PH], include_spent_coins=False)
)[0].coin
# Construct a spend without any time having passed
TO_REFILL = uint64(10)
initial_rl_puzzle: Program = construct_rate_limiting_puzzle(
setup_info.start_date, setup_info.singleton.amount, setup_info.drain_rate, uint64(1), ACS
)
refill_spend = SpendBundle(
[
CoinSpend(
setup_info.singleton,
construct_singleton(
setup_info.launcher_id,
initial_rl_puzzle,
),
solve_singleton(
setup_info.first_lineage_proof,
setup_info.singleton.amount,
solve_rate_limiting_puzzle(
setup_info.start_date,
Program.to([[51, ACS_PH, setup_info.singleton.amount + TO_REFILL]]),
),
),
),
CoinSpend(
fund_coin,
ACS,
Program.to([[51, ACS_PH, fund_coin.amount - TO_REFILL]]),
),
],
G2Element(),
)
# Process the results
result = await setup_info.sim_client.push_tx(refill_spend)
assert result[0] == MempoolInclusionStatus.SUCCESS
await setup_info.sim.farm_block()
cost_logger.add_cost("Refill", refill_spend)
# Check that the singleton is the same puzzle hash
new_coin: Coin = (await setup_info.sim_client.get_coin_records_by_parent_ids([setup_info.singleton.name()]))[
0
].coin
assert new_coin.puzzle_hash == setup_info.singleton.puzzle_hash
finally:
await setup_info.sim.close()
def test_cost(cost_logger):
cost_logger.log_cost_statistics()
| 34.534722
| 117
| 0.589785
|
acfed8389e768f0a0d0d268cf327e0397c643a11
| 17,818
|
py
|
Python
|
cwbot/modules/dread/DreadTimelineModule.py
|
zeryl/RUcwbot
|
734716506066da599fcbc96d0a815a5e30f6e077
|
[
"BSD-3-Clause"
] | null | null | null |
cwbot/modules/dread/DreadTimelineModule.py
|
zeryl/RUcwbot
|
734716506066da599fcbc96d0a815a5e30f6e077
|
[
"BSD-3-Clause"
] | 1
|
2019-04-15T02:48:19.000Z
|
2019-04-15T03:02:36.000Z
|
cwbot/modules/dread/DreadTimelineModule.py
|
zeryl/RUcwbot
|
734716506066da599fcbc96d0a815a5e30f6e077
|
[
"BSD-3-Clause"
] | null | null | null |
from cwbot.modules.BaseDungeonModule import BaseDungeonModule, eventDbMatch
from cwbot.common.exceptions import FatalError
from cwbot.common.kmailContainer import Kmail
from cwbot.kolextra.request.UserProfileRequest import UserProfileRequest
import pytz
from copy import deepcopy
import itertools
from collections import defaultdict
import datetime
import time
import re
import threading
from pastebin_python import PastebinPython
from pastebin_python.pastebin_exceptions \
import (PastebinBadRequestException,
PastebinNoPastesException, PastebinFileException)
from pastebin_python.pastebin_constants import PASTE_PUBLIC, EXPIRE_1_MONTH
from pastebin_python.pastebin_formats import FORMAT_NONE
def _nameKey(x):
return "".join(x.split()).strip().lower()
_maxLen = 33
_format = "{:33}{:33}{:33}"
_areas = {0: 'The Woods', 1: 'The Village', 2: 'The Castle'}
_shortestName = 4
_tz = pytz.timezone('America/Phoenix')
class DreadTimelineModule(BaseDungeonModule):
"""
creates a timeline of dreadsylvania.
"""
requiredCapabilities = ['chat', 'dread']
_name = "dread-timeline"
def __init__(self, manager, identity, config):
self._snapshots = None
self._lastComplete = None
self._lastRaidlog = None
self._apikey = None
self._pastes = None
self._initialized = False
self._readyForTimeline = threading.Event()
self._timelineLock = threading.Lock()
super(DreadTimelineModule, self).__init__(manager, identity, config)
def initialize(self, state, initData):
self._db = initData['event-db']
self._snapshots = state['snapshots']
self._lastComplete = state['last']
pastes = state.get('pastes', {})
self._pastes = {k: v for k,v in pastes.items()
if v.get('time', 0) > time.time() - 31 * 24 * 60 * 60}
self._processLog(initData)
self._initialized = True
def _configure(self, config):
self._apikey = config['pastebin_api_key']
@property
def initialState(self):
return {'snapshots': [],
'last': [0, 0, 0],
'pastes': {}}
@property
def state(self):
return {'snapshots': self._snapshots,
'last': self._lastComplete,
'pastes': self._pastes}
def _processLog(self, raidlog):
with self._timelineLock:
events = deepcopy(raidlog['events'])
self._lastRaidlog = deepcopy(raidlog)
dvid = raidlog.get('dvid')
if not self._dungeonActive():
if dvid is not None and str(dvid) not in self._pastes:
if self._initialized:
self._readyForTimeline.set()
d = self._raiseEvent("dread", "dread-overview",
data={'style': 'list',
'keys': ['killed']})
killed = [data['killed'] for data in d[0].data]
roundedKilled = map(lambda x: (x // 50) * 50, killed)
if roundedKilled > self._lastComplete:
self._lastComplete = roundedKilled
self._snapshots.append(self._getNewEvents(events))
return True
def _getNewEvents(self, events):
t1 = time.time()
newEvents = []
# first, get a list of all db entries and players
dbEntries = []
players = set()
for e in events:
if e['db-match'] not in dbEntries:
dbEntries.append(e['db-match'])
players.add(e['userId'])
# now, loop over all players and db entries
for dbm in dbEntries:
# skip unmatched events
if not dbm:
continue
matchingDoneEvents = list(eventDbMatch(
itertools.chain.from_iterable(
self._snapshots), dbm))
matchingNewEvents = list(eventDbMatch(events, dbm))
for uid in players:
matchesUser = lambda x: x['userId'] == uid
playerEvents = filter(matchesUser, matchingNewEvents)
doneEvents = filter(matchesUser, matchingDoneEvents)
playerTotalEvents = sum(pe['turns'] for pe in playerEvents)
doneTotalEvents = sum(de['turns'] for de in doneEvents)
eventDiff = playerTotalEvents - doneTotalEvents
if eventDiff < 0:
self._log.warn("Snapshot: {}\nevents: {}"
.format(self._snapshots, events))
raise RuntimeError("Error: detected {} events but "
"{} in snapshot for user {} and "
"db entry {}"
.format(playerTotalEvents,
doneTotalEvents,
uid,
dbm))
if eventDiff > 0:
newEvent = deepcopy(playerEvents[0])
newEvent['turns'] = eventDiff
newEvents.append(newEvent)
self.debugLog("Built new DB entries in {} seconds"
.format(time.time() - t1))
return newEvents
def _timelineHeader(self, events, nameShorthands):
r = UserProfileRequest(self.session, self.properties.userId)
d = self.tryRequest(r)
clanName = d.get('clanName')
kisses = self._lastRaidlog.get('dread', {}).get('kisses', "?")
users = {e['userId']: e['userName'] for e in events if e['db-match']}
timeString = (datetime.datetime.now()
.strftime("%A, %B %d %Y %I:%M%p UTC"))
timeHeader = ("Timeline for {}-kiss Dreadsylvania instance "
"in {}\nReport generated {}\n\n"
.format(kisses, clanName, timeString))
nameHeader = ("The following name abbreviations are used in this "
"report:\n\n{}\n\n"
.format("\n".join("{} = {} (#{})"
.format(shortName, users[uid], uid)
for uid, shortName
in nameShorthands.items())))
topHeader = _format.format(_areas[0], _areas[1], _areas[2]) + "\n"
return timeHeader + nameHeader + topHeader
# create a timeline.
# the timeline is a list of time entries.
# each timeentry looks like this:
# {'kills': [K1, K2, K3], # kills in 3 areas
# 'text': [[txt1, txt2], [txt1, txt2], [txt1, txt2]]} # text for 3 areas
def _eventTimeline(self, events, nameShorthands):
timeline = []
timelineKills = [0,0,0]
newEvents = self._getNewEvents(events)
t1 = time.time()
snapshots = deepcopy(self._snapshots)
snapshots.append(newEvents)
for snapshot in snapshots:
timelineText = []
for area in range(3):
txtList = []
areaName = _areas[area]
# first, let's find kills
kills = defaultdict(int)
killEvents = eventDbMatch(snapshot, {'category': areaName,
'zone': "(combat)",
'subzone': "normal"})
for e in killEvents:
timelineKills[area] += e['turns']
kills[e['userId']] += e['turns']
for uid, k in kills.items():
txtList.append(" {}: {} kills"
.format(nameShorthands[uid], k))
bossEvents = eventDbMatch(snapshot, {'category': areaName,
'zone': "(combat)",
'subzone': "boss"},
{'category': areaName,
'zone': "(combat)",
'subzone': "boss_defeat"})
for e in bossEvents:
txtList.append("*{} {}"
.format(nameShorthands[e['userId']],
e['event']))
allEvents = eventDbMatch(snapshot, {'category': areaName})
for e in allEvents:
dbm = e['db-match']
if dbm.get('zone') == "(combat)":
continue
if dbm.get('unique_text', "").strip() != "":
txtList.append("*{} got {} at {}"
.format(nameShorthands[e['userId']],
dbm['code'],
dbm['zone']))
elif dbm.get('zone') == "(unlock)":
txtList.append("-{} unlocked {}"
.format(nameShorthands[e['userId']],
dbm['subzone']))
else:
txtList.append("-{} did {} at {}"
.format(nameShorthands[e['userId']],
dbm['code'],
dbm['zone']))
txtList.sort()
timelineText.append(txtList)
timeline.append({'kills': deepcopy(timelineKills),
'text': timelineText})
self.debugLog("Built timeline in {} seconds"
.format(time.time() - t1))
return timeline
# convert a timeline to a multiline string to display.
def _timelineString(self, timeline):
def balanceLines(alines, extendString):
totalLines = map(len, alines)
maxLines = max(totalLines)
for lines in alines:
lines.extend([extendString] * (maxLines - len(lines)))
t1 = time.time()
areaLines = [["-+- 0% complete"],
["-+- 0% complete"],
["-+- 0% complete"]] * 3
lastKills = [0, 0, 0]
for t in timeline:
for area in range(3):
for txt in t['text'][area]:
areaLines[area].append(" | {}".format(txt))
balanceLines(areaLines, " |")
for area in range(3):
roundedKills = (t['kills'][area] // 50) * 50
if roundedKills > lastKills[area]:
lastKills[area] = roundedKills
areaLines[area].append("-+- {}% complete"
.format(int(roundedKills // 10)))
balanceLines(areaLines, "-+-")
# now format it correctly
for a in range(3):
areaLines[a] = map(lambda x: x[:_maxLen], areaLines[a])
lines = zip(*areaLines)
txtLines = [_format.format(*t) for t in lines]
self.debugLog("Built timeline string in {} seconds"
.format(time.time() - t1))
return "\n".join(line.rstrip() for line in txtLines)
def _getShortenedNames(self, events):
users = {e['userId']: e['userName'] for e in events if e['db-match']}
userNamesFixed = {uid: ''.join(name.split())
for uid,name in users.items()}
userNamesDone = {}
nameLength = _shortestName
while userNamesFixed:
counts = defaultdict(int)
# shorten names
newUserNames = {uid: name[:nameLength]
for uid, name in userNamesFixed.items()}
for name in newUserNames:
counts[name] += 1
userNamesDone.update({uid: name
for uid, name in newUserNames.items()
if counts[name] <= 1})
userNamesFixed = {uid: name
for uid, name in userNamesFixed.items()
if counts[newUserNames[uid]] > 1}
return userNamesDone
def _processDungeon(self, txt, raidlog):
self._processLog(raidlog)
return None
def _processCommand(self, message, cmd, args):
if cmd == "timeline":
dvid = self._lastRaidlog.get('dvid')
if (self._dungeonActive()
or dvid is None
or str(dvid) not in self._pastes):
return ("You can't get the timeline while the dungeon is "
"active.")
data = self._pastes[str(dvid)]
if data['error']:
return ("Error with timeline: {}".format(data['url']))
return "Timeline for current instance: {}".format(data['url'])
elif cmd == "timelines":
timelines = self._pastes.values()
timelines.sort(key=lambda x: x['time'], reverse=True)
strings = []
for item in timelines:
urlText = item['url'] if not item['error'] else "ERROR"
dvidText = item['dvid']
dt_utc = datetime.datetime.fromtimestamp(item['time'],
pytz.utc)
dt_az = dt_utc.astimezone(_tz)
timeText = dt_az.strftime("%a %d %b %y")
kisses = item['kisses']
strings.append("{} - {} [{} kisses]: {}"
.format(timeText, dvidText, kisses, urlText))
sendString = ""
for string in strings:
if len(string) + len(sendString) > 1500:
break
sendString += string + "\n"
if sendString == "":
return "No timelines in memory."
self.sendKmail(Kmail(message['userId'],
"Here are the most recent Dreadsylvania "
"instances:\n\n{}".format(sendString)))
return "Timelines sent."
def _heartbeat(self):
if self._readyForTimeline.is_set():
with self._timelineLock:
self._readyForTimeline.clear()
dvid = self._lastRaidlog.get('dvid')
if dvid is None or str(dvid) in self._pastes:
return
self._createTimeline()
def _createTimeline(self):
dvid = self._lastRaidlog.get('dvid')
kisses = self._lastRaidlog.get('dread', {}).get('kisses', "?")
if dvid is None:
return
shortNames = self._getShortenedNames(self._lastRaidlog['events'])
header = self._timelineHeader(self._lastRaidlog['events'], shortNames)
timeline = self._eventTimeline(self._lastRaidlog['events'], shortNames)
body = self._timelineString(timeline)
pbin = PastebinPython(api_dev_key=self._apikey)
try:
result = pbin.createPaste(header + body,
api_paste_format=FORMAT_NONE,
api_paste_private=PASTE_PUBLIC,
api_paste_expire_date=EXPIRE_1_MONTH)
resultError = re.search(r'https?://', result) is None
self._pastes[str(dvid)] = {'url': result,
'time': time.time(),
'dvid': dvid,
'error': resultError,
'kisses': kisses}
if resultError:
self.log("Error with timeline: {}".format(result))
except (PastebinBadRequestException,
PastebinFileException,
PastebinNoPastesException) as e:
self._pastes[str(dvid)] = {'url': e.message,
'time': time.time(),
'dvid': dvid,
'error': True,
'kisses': kisses}
self.log("Error with timeline: {}".format(e.message))
def reset(self, initData):
self._readyForTimeline.clear()
newState = self.initialState
newState['pastes'] = self._pastes
self.initialize(newState, initData)
def _eventCallback(self, eData):
s = eData.subject
if s == "state":
if eData.to is None:
self._eventReply({
'warning': '(omitted for general state inquiry)'})
else:
self._eventReply(self.state)
def _availableCommands(self):
return {'timeline': "!timeline: Show a timeline of the Dreadsylvania "
"instance."}
| 43.671569
| 88
| 0.465484
|
acfed8da7443acebf1c835b67c126a721d8b82d6
| 2,511
|
py
|
Python
|
backend/pyrogram/raw/functions/messages/update_dialog_filter.py
|
appheap/social-media-analyzer
|
0f9da098bfb0b4f9eb38e0244aa3a168cf97d51c
|
[
"Apache-2.0"
] | 5
|
2021-09-11T22:01:15.000Z
|
2022-03-16T21:33:42.000Z
|
backend/pyrogram/raw/functions/messages/update_dialog_filter.py
|
iamatlasss/social-media-analyzer
|
429d1d2bbd8bfce80c50c5f8edda58f87ace668d
|
[
"Apache-2.0"
] | null | null | null |
backend/pyrogram/raw/functions/messages/update_dialog_filter.py
|
iamatlasss/social-media-analyzer
|
429d1d2bbd8bfce80c50c5f8edda58f87ace668d
|
[
"Apache-2.0"
] | 3
|
2022-01-18T11:06:22.000Z
|
2022-02-26T13:39:28.000Z
|
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2021 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from io import BytesIO
from pyrogram.raw.core.primitives import Int, Long, Int128, Int256, Bool, Bytes, String, Double, Vector
from pyrogram.raw.core import TLObject
from pyrogram import raw
from typing import List, Union, Any
# # # # # # # # # # # # # # # # # # # # # # # #
# !!! WARNING !!! #
# This is a generated file! #
# All changes made in this file will be lost! #
# # # # # # # # # # # # # # # # # # # # # # # #
class UpdateDialogFilter(TLObject): # type: ignore
"""Telegram API method.
Details:
- Layer: ``123``
- ID: ``0x1ad4a04a``
Parameters:
id: ``int`` ``32-bit``
filter (optional): :obj:`DialogFilter <pyrogram.raw.base.DialogFilter>`
Returns:
``bool``
"""
__slots__: List[str] = ["id", "filter"]
ID = 0x1ad4a04a
QUALNAME = "functions.messages.UpdateDialogFilter"
def __init__(self, *, id: int, filter: "raw.base.DialogFilter" = None) -> None:
self.id = id # int
self.filter = filter # flags.0?DialogFilter
@staticmethod
def read(data: BytesIO, *args: Any) -> "UpdateDialogFilter":
flags = Int.read(data)
id = Int.read(data)
filter = TLObject.read(data) if flags & (1 << 0) else None
return UpdateDialogFilter(id=id, filter=filter)
def write(self) -> bytes:
data = BytesIO()
data.write(Int(self.ID, False))
flags = 0
flags |= (1 << 0) if self.filter is not None else 0
data.write(Int(flags))
data.write(Int(self.id))
if self.filter is not None:
data.write(self.filter.write())
return data.getvalue()
| 31
| 103
| 0.619275
|
acfed8e280803c0a956c8a00bb2c7964a8afdce1
| 4,004
|
py
|
Python
|
data_management/toolboxes/scripts/CalculateFieldDeltaTime.py
|
conklinbd/solutions-geoprocessing-toolbox
|
7afab793ea34b7e7cb7e32757e8a150b6637ffd2
|
[
"Apache-2.0"
] | null | null | null |
data_management/toolboxes/scripts/CalculateFieldDeltaTime.py
|
conklinbd/solutions-geoprocessing-toolbox
|
7afab793ea34b7e7cb7e32757e8a150b6637ffd2
|
[
"Apache-2.0"
] | null | null | null |
data_management/toolboxes/scripts/CalculateFieldDeltaTime.py
|
conklinbd/solutions-geoprocessing-toolbox
|
7afab793ea34b7e7cb7e32757e8a150b6637ffd2
|
[
"Apache-2.0"
] | 1
|
2018-10-25T15:52:41.000Z
|
2018-10-25T15:52:41.000Z
|
#--------ESRI 2010-------------------------------------
#-------------------------------------------------------------------------------
# Copyright 2010-2014 Esri
# 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.
#-------------------------------------------------------------------------------
# Calculate Field DeltaTime
# This script will calculate the time spent around a point
# in a GPS track series as half the timespan between the 2
# points either side and will add that time in seconds to
# a numeric field, the name of which is passed as a parameter.
# Each track (as identified in the Track ID Field) will be
# treated separately
# INPUTS:
# GPS Track Points (FEATURECLASS)
# DateTime Field (FIELD)
# Field in which to store time spent (FIELD)
# Track ID Field (FIELD)
# OUTPUTS:
# GPS Track Points - derived (FEATURECLASS)
#
# Date: June 30, 2010
#------------------------------------------------------
import arcpy
import datetime
import sys
import time
try:
#set features and cursors so that they are deletable in
#'finally' block should the script fail prior to their creation
nextfeat, srch_cursor = None, None
updatefeat, updt_cursor = None, None
inPoints = arcpy.GetParameterAsText(0)
inDateField = arcpy.GetParameterAsText(1)
inDeltaTimeField = arcpy.GetParameterAsText(2)
inTrackIDField = arcpy.GetParameterAsText(3)
fields = inDateField + ';' + inDeltaTimeField
if inTrackIDField :
fields += ';' + inTrackIDField
# WARNING: Workaround encountered using this script in Pro
# WARNING 2: SearchCursor now also requires fields at Arcpy Pro
if (sys.version_info.major < 3) :
srch_cursor = arcpy.SearchCursor(inPoints, "", None, fields, inDateField + " A")
else :
srch_cursor = arcpy.gp.SearchCursor(inPoints, "", None, fields, inDateField + " A")
nextfeat = next(srch_cursor)
nextfeat = next(srch_cursor) # this cursor looks at the point after the one being updated
# WARNING: Workaround encountered using this script in Pro
if (sys.version_info.major < 3) :
updt_cursor = arcpy.UpdateCursor(inPoints, "", None, fields, inDateField + " A")
else :
updt_cursor = arcpy.gp.UpdateCursor(inPoints, "", None, fields, inDateField + " A")
updatefeat = next(updt_cursor)
lastdt = None
lastid, thisid, nextid = None, None, None
try :
while updatefeat:
thisdt = updatefeat.getValue(inDateField)
if inTrackIDField:
thisid = updatefeat.getValue(inTrackIDField)
if thisid != lastid:
lastdt = None
if nextfeat:
if inTrackIDField:
nextid = nextfeat.getValue(inTrackIDField)
if thisid == nextid:
nextdt = nextfeat.getValue(inDateField)
else:
nextdt = None
else:
nextdt = None
if lastdt:
if nextdt:
span = (nextdt - lastdt)
else:
span = (thisdt - lastdt)
else:
if nextdt:
span = (nextdt - thisdt)
else:
span = None
if span:
span = float(span.seconds) / 2
updatefeat.setValue(inDeltaTimeField, span)
updt_cursor.updateRow(updatefeat)
lastid = thisid
lastdt = thisdt
updatefeat = next(updt_cursor)
if updatefeat:
nextfeat = next(srch_cursor)
except StopIteration:
pass # this is expected for iterators that use next()
arcpy.SetParameterAsText(4, inPoints)
except Exception as err:
import traceback
arcpy.AddError(
traceback.format_exception_only(type(err), err)[0].rstrip())
finally:
if nextfeat:
del nextfeat
if srch_cursor:
del srch_cursor
if updatefeat:
del updatefeat
if updt_cursor:
del updt_cursor
| 30.564885
| 90
| 0.676573
|
acfed94b780d849eabeb62d4bbcc3f172f58add8
| 7,340
|
py
|
Python
|
base/base_trainer.py
|
atch841/CCT
|
3a0b05d63fde9118ea369f2c2d512ae4c814c248
|
[
"MIT"
] | null | null | null |
base/base_trainer.py
|
atch841/CCT
|
3a0b05d63fde9118ea369f2c2d512ae4c814c248
|
[
"MIT"
] | null | null | null |
base/base_trainer.py
|
atch841/CCT
|
3a0b05d63fde9118ea369f2c2d512ae4c814c248
|
[
"MIT"
] | null | null | null |
import os, json, math, logging, sys, datetime
import torch
from torch.utils import tensorboard
from utils import helpers
from utils import logger
import utils.lr_scheduler
from utils.htmlwriter import HTML
def get_instance(module, name, config, *args):
return getattr(module, config[name]['type'])(*args, **config[name]['args'])
class BaseTrainer:
def __init__(self, model, resume, config, iters_per_epoch, train_logger=None):
self.model = model
self.config = config
self.train_logger = train_logger
self.logger = logging.getLogger(self.__class__.__name__)
self.do_validation = self.config['trainer']['val']
self.start_epoch = 1
self.improved = False
# SETTING THE DEVICE
self.device, availble_gpus = self._get_available_devices(self.config['n_gpu'])
self.model = torch.nn.DataParallel(self.model, device_ids=availble_gpus)
self.model.to(self.device)
# CONFIGS
cfg_trainer = self.config['trainer']
self.epochs = cfg_trainer['epochs']
self.save_period = cfg_trainer['save_period']
# OPTIMIZER
trainable_params = [{'params': filter(lambda p:p.requires_grad, self.model.module.get_other_params())},
{'params': filter(lambda p:p.requires_grad, self.model.module.get_backbone_params()),
'lr': config['optimizer']['args']['lr'] / 10}]
self.optimizer = get_instance(torch.optim, 'optimizer', config, trainable_params)
model_params = sum([i.shape.numel() for i in list(model.parameters())])
opt_params = sum([i.shape.numel() for j in self.optimizer.param_groups for i in j['params']])
assert opt_params == model_params, 'some params are missing in the opt'
self.lr_scheduler = getattr(utils.lr_scheduler, config['lr_scheduler'])(optimizer=self.optimizer, num_epochs=self.epochs,
iters_per_epoch=iters_per_epoch)
# MONITORING
self.monitor = cfg_trainer.get('monitor', 'off')
if self.monitor == 'off':
self.mnt_mode = 'off'
self.mnt_best = 0
else:
self.mnt_mode, self.mnt_metric = self.monitor.split()
assert self.mnt_mode in ['min', 'max']
self.mnt_best = -math.inf if self.mnt_mode == 'max' else math.inf
self.early_stoping = cfg_trainer.get('early_stop', math.inf)
# CHECKPOINTS & TENSOBOARD
date_time = datetime.datetime.now().strftime('%m-%d_%H-%M')
run_name = config['experim_name']
self.checkpoint_dir = os.path.join(cfg_trainer['save_dir'], run_name)
helpers.dir_exists(self.checkpoint_dir)
config_save_path = os.path.join(self.checkpoint_dir, 'config.json')
with open(config_save_path, 'w') as handle:
json.dump(self.config, handle, indent=4, sort_keys=True)
writer_dir = os.path.join(cfg_trainer['log_dir'], run_name)
self.writer = tensorboard.SummaryWriter(writer_dir)
self.html_results = HTML(web_dir=config['trainer']['save_dir'], exp_name=config['experim_name'],
save_name=config['experim_name'], config=config, resume=resume)
if resume: self._resume_checkpoint(resume)
def _get_available_devices(self, n_gpu):
sys_gpu = torch.cuda.device_count()
if sys_gpu == 0:
self.logger.warning('No GPUs detected, using the CPU')
n_gpu = 0
elif n_gpu > sys_gpu:
self.logger.warning(f'Nbr of GPU requested is {n_gpu} but only {sys_gpu} are available')
n_gpu = sys_gpu
device = torch.device('cuda:0' if n_gpu > 0 else 'cpu')
self.logger.info(f'Detected GPUs: {sys_gpu} Requested: {n_gpu}')
available_gpus = list(range(n_gpu))
return device, available_gpus
def train(self):
for epoch in range(self.start_epoch, self.epochs+1):
results = self._train_epoch(epoch)
if self.do_validation and epoch % self.config['trainer']['val_per_epochs'] == 0:
results = self._valid_epoch(epoch)
self.logger.info('\n\n')
for k, v in results.items():
self.logger.info(f' {str(k):15s}: {v}')
if self.train_logger is not None:
log = {'epoch' : epoch, **results}
self.train_logger.add_entry(log)
# CHECKING IF THIS IS THE BEST MODEL (ONLY FOR VAL)
if self.mnt_mode != 'off' and epoch % self.config['trainer']['val_per_epochs'] == 0:
try:
if self.mnt_mode == 'min': self.improved = (log[self.mnt_metric] < self.mnt_best)
else: self.improved = (log[self.mnt_metric] > self.mnt_best)
except KeyError:
self.logger.warning(f'The metrics being tracked ({self.mnt_metric}) has not been calculated. Training stops.')
break
if self.improved:
self.mnt_best = log[self.mnt_metric]
self.not_improved_count = 0
else:
self.not_improved_count += 1
if self.not_improved_count > self.early_stoping:
self.logger.info(f'\nPerformance didn\'t improve for {self.early_stoping} epochs')
self.logger.warning('Training Stoped')
break
# SAVE CHECKPOINT
if epoch % self.save_period == 0:
self._save_checkpoint(epoch, save_best=self.improved)
self.html_results.save()
def _save_checkpoint(self, epoch, save_best=False):
state = {
'arch': type(self.model).__name__,
'epoch': epoch,
'state_dict': self.model.state_dict(),
'monitor_best': self.mnt_best,
'config': self.config
}
filename = os.path.join(self.checkpoint_dir, f'checkpoint_epoch{epoch}.pth')
self.logger.info(f'\nSaving a checkpoint: {filename} ...')
torch.save(state, filename)
if save_best:
filename = os.path.join(self.checkpoint_dir, f'best_model.pth')
torch.save(state, filename)
self.logger.info("Saving current best: best_model.pth")
def _resume_checkpoint(self, resume_path):
self.logger.info(f'Loading checkpoint : {resume_path}')
checkpoint = torch.load(resume_path)
self.start_epoch = checkpoint['epoch'] + 1
self.mnt_best = checkpoint['monitor_best']
self.not_improved_count = 0
try:
self.model.load_state_dict(checkpoint['state_dict'])
except Exception as e:
print(f'Error when loading: {e}')
self.model.load_state_dict(checkpoint['state_dict'], strict=False)
if "logger" in checkpoint.keys():
self.train_logger = checkpoint['logger']
self.logger.info(f'Checkpoint <{resume_path}> (epoch {self.start_epoch}) was loaded')
def _train_epoch(self, epoch):
raise NotImplementedError
def _valid_epoch(self, epoch):
raise NotImplementedError
def _eval_metrics(self, output, target):
raise NotImplementedError
| 42.923977
| 130
| 0.606948
|
acfeda46c756ba2201cf28a37cca3cac247638c8
| 9,214
|
py
|
Python
|
pdil/core/factory.py
|
patcorwin/fossil
|
8e471c5233e4a2d81dc66bd8e2a3d6387e71ef61
|
[
"BSD-3-Clause"
] | 41
|
2017-04-24T09:43:24.000Z
|
2021-10-06T04:11:43.000Z
|
pdil/core/factory.py
|
patcorwin/fossil
|
8e471c5233e4a2d81dc66bd8e2a3d6387e71ef61
|
[
"BSD-3-Clause"
] | 22
|
2018-04-18T21:56:01.000Z
|
2021-08-05T20:57:45.000Z
|
pdil/core/factory.py
|
patcorwin/fossil
|
8e471c5233e4a2d81dc66bd8e2a3d6387e71ef61
|
[
"BSD-3-Clause"
] | 9
|
2017-04-24T09:43:27.000Z
|
2021-05-14T05:38:33.000Z
|
'''
A collection of helper functions to construct pymel node factories (i.e. custom pynodes).
The main appeal is providing direct access (via *Access) instead of get/set, so it only
makes sense if the attribute isn't animatable.
Additionally there is a helper that allows connecting a single object and another
for automatically deserializing json strings.
ex:
class MySpecialJoint(nt.Joint):
@classmethod
def _isVirtual(cls, obj, name):
fn = pymel.api.MFnDependencyNode(obj)
try:
if fn.hasAttribute('fossilMirror'):
return True
except: # .hasAttribute doesn't actually return False but errors, lame.
pass
return False
mirror = SingleConnectionAccess('fossilMirror')
data = JsonAccess('fossilData')
pymel.internal.factories.registerVirtualClass( MySpecialJoint )
j = joint()
j.addAttr('fossilMirror', at='message')
j.addAttr('fossilData', dt='string')
j = PyNode(j) # Must recast to get identified as a MySpecialJoint
someOtherJoint = joint()
print( j.mirror )
# Result: None
j.mirror = someOtherJoint
print( j.mirror )
# Result: joint2
j.mirror = None
print( j.mirror )
# Result: None
print( j.data )
# Result: {}
j.data = {'canned': 'goods' }
print( j.data, type(j.data) )
# Result: {'canned': 'goods' } <type 'dict'>
print( j.fossilData.get(), type(j.fossilData.get()) )
# Result: {"canned": "goods"} <type 'unicode'>
'''
import collections
import contextlib
import json
from pymel.core import hasAttr
from pymel.core.general import PyNode
try:
basestring
except NameError:
basestring = str
# Attribute access utilities --------------------------------------------------
# They all have to use .node() in case it's a sub attr, like sequence[0].data
def _getSingleConnection(obj, attrName):
'''
If connected, return the single entry, otherwise none.
'''
if not obj.node().hasAttr(attrName):
return None
connections = obj.attr(attrName).listConnections()
if connections:
return connections[0]
else:
return None
def _setSingleConnection(obj, attrName, value):
if value:
if isinstance(value, basestring):
PyNode(value).message >> messageAttr( obj, attrName )
else:
value.message >> messageAttr( obj, attrName )
else:
if hasAttr(obj.node(), attrName):
obj.attr(attrName).disconnect()
def _getSingleStringConnection(obj, attrName):
'''
If connected, return the single entry, otherwise checks if a string val is set, returning that.
'''
if not obj.node().hasAttr(attrName):
return ''
connections = obj.attr(attrName).listConnections()
if connections:
return connections[0]
else:
return obj.attr(attrName).get()
def _setSingleStringConnection(obj, attrName, value):
if value:
if isinstance(value, basestring):
if obj.node().hasAttr(attrName) and obj.attr(attrName).listConnections():
obj.attr(attrName).disconnect()
_setStringAttr(obj, attrName, value)
else:
_setStringAttr(obj, attrName, None)
value.message >> obj.attr( attrName )
else:
if hasAttr(obj.node(), attrName):
obj.attr(attrName).disconnect()
obj.attr(attrName).set('')
def _getStringAttr(obj, attrName):
if obj.node().hasAttr(attrName):
return obj.attr(attrName).get()
return ''
def _setStringAttr(obj, attrName, val):
if not obj.node().hasAttr(attrName):
obj.addAttr( attrName, dt='string' )
if val is not None:
obj.attr(attrName).set(val)
def setJsonAttr(obj, attrName, val):
_setStringAttr(obj, attrName, json.dumps(val))
def getJsonAttr(obj, attrName, ):
return json.loads( _getStringAttr(obj, attrName), object_pairs_hook=collections.OrderedDict)
def _getIntAttr(obj, attrName):
if obj.node().hasAttr(attrName):
return obj.attr(attrName).get()
return -666
def _setIntAttr(obj, attrName, val):
if not obj.node().hasAttr(attrName):
obj.addAttr( attrName, dt='long' )
if val is not None:
obj.attr(attrName).set(val)
def _getFloatAttr(obj, attrName):
if obj.node().hasAttr(attrName):
return obj.attr(attrName).get()
return -666.666
def _setFloatAttr(obj, attrName, val):
if not obj.node().hasAttr(attrName):
obj.addAttr( attrName, dt='double' )
if val is not None:
obj.attr(attrName).set(val)
def messageAttr( obj, name ):
'''
Make the attribute if it doesn't exist and return it.
'''
if not obj.hasAttr( name ):
obj.addAttr( name, at='message' )
return obj.attr(name)
class FakeAttribute(object):
def __init__(self, obj, getter, setter):
self.obj = obj
self.getter = getter
self.setter = setter
def get(self):
return self.getter(self.obj)
def set(self, val):
self.setter(self.obj, val)
# Descriptors -----------------------------------------------------------------
class DeprecatedAttr(object):
'''
When a regular attribute has been replaced by something, allow for not
fixing every code reference but route to the new data location.
'''
def __init__(self, getter, setter, mayaAttr=True):
self.getter = getter
self.setter = setter
self.mayaAttr = mayaAttr
def __get__(self, instance, owner):
if self.mayaAttr:
return FakeAttribute(instance, self.getter, self.setter)
else:
return self.getter(instance)
def __set__(self, instance, value):
# This is never legitimately called for maya attrs
if not self.mayaAttr:
self.setter(instance, value)
class StringAccess(object):
'''
Provides access to the attribute of the given name, defaulting to an
empty string if the attribute doesn't exist.
'''
def __init__(self, attrname):
self.attr = attrname
def __get__(self, instance, owner):
return _getStringAttr(instance, self.attr)
def __set__(self, instance, value):
_setStringAttr(instance, self.attr, value)
class SingleConnectionAccess(object):
'''
Returns the object connected to the given attribute, or None if the attr
doesn't exist or isn't connected.
'''
def __init__(self, attrname):
self.attr = attrname
def __get__(self, instance, owner):
return _getSingleConnection(instance, self.attr)
def __set__(self, instance, value):
_setSingleConnection(instance, self.attr, value)
class SingleStringConnectionAccess(object):
'''
Just like SingleConnection but is also a string for alternate values
'''
def __init__(self, attrname):
self.attr = attrname
def __get__(self, instance, owner):
return _getSingleStringConnection(instance, self.attr)
def __set__(self, instance, value):
_setSingleStringConnection(instance, self.attr, value)
class Json(collections.OrderedDict):
def __init__(self, data, node, attr):
collections.OrderedDict.__init__(self, data)
self._node = node
self._attr = attr
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self._node.attr(self._attr).set( json.dumps(self) )
class JsonAccess(object):
'''
Auto tranform json data to/from a string. Call in `with` statement and edit
the result to automatically assign the changes.
'''
def __init__(self, attrname, defaults={}):
self.attr = attrname
self.defaults = defaults
def __get__(self, instance, owner):
res = _getStringAttr(instance, self.attr)
if not res:
return self.defaults.copy()
return Json(json.loads(res, object_pairs_hook=collections.OrderedDict), instance, self.attr )
def __set__(self, instance, value):
setJsonAttr(instance, self.attr, value)
class IntAccess(object):
'''
Provides access to the attribute of the given name, defaulting to an
empty string if the attribute doesn't exist.
'''
def __init__(self, attrname):
self.attr = attrname
def __get__(self, instance, owner):
return _getIntAttr(instance, self.attr)
def __set__(self, instance, value):
_setIntAttr(instance, self.attr, value)
class FloatAccess(object):
'''
Provides access to the attribute of the given name, defaulting to an
empty string if the attribute doesn't exist.
'''
def __init__(self, attrname):
self.attr = attrname
def __get__(self, instance, owner):
return _getFloatAttr(instance, self.attr)
def __set__(self, instance, value):
_setFloatAttr(instance, self.attr, value)
| 27.504478
| 101
| 0.62188
|
acfeda7f5888ef8d43ca9c73d99b840bed7aa2d4
| 158
|
py
|
Python
|
apps/__init__.py
|
pythonyhd/django_blog
|
285800df723ede53bc8b827bd9d3c6ee11bba07a
|
[
"Apache-2.0"
] | 2
|
2019-12-04T05:36:40.000Z
|
2020-01-20T06:52:20.000Z
|
apps/__init__.py
|
pythonyhd/django_blog
|
285800df723ede53bc8b827bd9d3c6ee11bba07a
|
[
"Apache-2.0"
] | 9
|
2021-04-08T21:59:16.000Z
|
2022-03-12T00:48:24.000Z
|
apps/__init__.py
|
pythonyhd/django_blog
|
285800df723ede53bc8b827bd9d3c6ee11bba07a
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
# @Time : 2019/11/28 17:40
# @Author : King life
# @Email : 18353626676@163.com
# @File : __init__.py.py
# @Software: PyCharm
| 26.333333
| 32
| 0.588608
|
acfedb3b4397c9a9763c2b98c1b1e398bb3572c5
| 938
|
py
|
Python
|
src/python/grapl_analyzerlib/grapl_analyzerlib/prelude.py
|
0xflotus/grapl
|
574902a176ccc4d0cd6fc34549e9dbc95e8044fb
|
[
"Apache-2.0"
] | 1
|
2021-12-12T14:27:49.000Z
|
2021-12-12T14:27:49.000Z
|
src/python/grapl_analyzerlib/grapl_analyzerlib/prelude.py
|
0xflotus/grapl
|
574902a176ccc4d0cd6fc34549e9dbc95e8044fb
|
[
"Apache-2.0"
] | 449
|
2020-09-11T07:07:18.000Z
|
2021-08-03T06:09:36.000Z
|
src/python/grapl_analyzerlib/grapl_analyzerlib/prelude.py
|
0xflotus/grapl
|
574902a176ccc4d0cd6fc34549e9dbc95e8044fb
|
[
"Apache-2.0"
] | null | null | null |
from grapl_analyzerlib.nodes.dynamic_node import DynamicNodeView, DynamicNodeQuery
from grapl_analyzerlib.nodes.process_node import (
ProcessView,
ProcessQuery,
IProcessView,
IProcessQuery,
)
from grapl_analyzerlib.nodes.file_node import FileView, FileQuery, IFileView, IFileQuery
from grapl_analyzerlib.nodes.risk_node import RiskView, RiskQuery, IRiskView, IRiskQuery
from grapl_analyzerlib.nodes.any_node import NodeQuery, NodeView
from grapl_analyzerlib.nodes.lens_node import LensView, LensQuery
from grapl_analyzerlib.nodes.queryable import Queryable, NQ
from grapl_analyzerlib.nodes.viewable import Viewable, NV
from grapl_analyzerlib.nodes.comparators import Not
from grapl_analyzerlib.execution import ExecutionHit
from grapl_analyzerlib.grapl_client import (
GraphClient,
MasterGraphClient,
LocalMasterGraphClient,
)
from grapl_analyzerlib.plugin_retriever import load_plugins, load_plugins_local
| 37.52
| 88
| 0.846482
|
acfedccf4741744ad37f5d313bb1fa9e08732b81
| 8,403
|
py
|
Python
|
wemake_python_styleguide/constants.py
|
serkanozer/wemake-python-styleguide
|
6032a1bde628d6052869b1da60786c7fc84f5e47
|
[
"MIT"
] | null | null | null |
wemake_python_styleguide/constants.py
|
serkanozer/wemake-python-styleguide
|
6032a1bde628d6052869b1da60786c7fc84f5e47
|
[
"MIT"
] | null | null | null |
wemake_python_styleguide/constants.py
|
serkanozer/wemake-python-styleguide
|
6032a1bde628d6052869b1da60786c7fc84f5e47
|
[
"MIT"
] | null | null | null |
"""
This module contains list of white- and black-listed ``python`` members.
We add values here when we want to make them public.
Or when a value is reused in several places.
Then, we automatically have to add it here and document it.
Other constants that are not used across modules
and does not require to be documented can be defined where they are used.
All values here must be documented with ``#:`` comments.
"""
import math
import re
from typing_extensions import Final
#: List of functions we forbid to use.
FUNCTIONS_BLACKLIST: Final = frozenset((
# Code generation:
'eval',
'exec',
'compile',
# Termination:
'exit',
'quit',
# Magic:
'globals',
'locals',
'vars',
'dir',
# IO:
'print',
'pprint',
'input',
'breakpoint',
# Attribute access:
'hasattr',
'delattr',
# Gratis:
'copyright',
'help',
'credits',
# Dynamic imports:
'__import__',
# OOP:
'staticmethod',
# Mypy:
'reveal_type',
))
#: List of module metadata we forbid to use.
MODULE_METADATA_VARIABLES_BLACKLIST: Final = frozenset((
'__author__',
'__all__',
'__version__',
'__about__',
))
#: List of variable names we forbid to use.
VARIABLE_NAMES_BLACKLIST: Final = frozenset((
# Meaningless words:
'data',
'result',
'results',
'item',
'items',
'value',
'values',
'val',
'vals',
'var',
'vars',
'variable',
'content',
'contents',
'info',
'handle',
'handler',
'file',
'obj',
'objects',
'objs',
'some',
'do',
'param',
'params',
'parameters',
# Confuseables:
'no',
'true',
'false',
# Names from examples:
'foo',
'bar',
'baz',
))
#: List of characters sequences that are hard to read.
UNREADABLE_CHARACTER_COMBINATIONS: Final = frozenset((
'1l',
'1I',
'0O',
'O0',
# Not included: 'lI', 'l1', 'Il'
# Because these names are quite common in real words.
))
#: List of special names that are used only as first argument in methods.
SPECIAL_ARGUMENT_NAMES_WHITELIST: Final = frozenset((
'self',
'cls',
'mcs',
))
#: List of all magic methods from the python docs.
ALL_MAGIC_METHODS: Final = frozenset((
'__new__',
'__init__',
'__del__',
'__repr__',
'__str__',
'__bytes__',
'__format__',
'__lt__',
'__le__',
'__eq__',
'__ne__',
'__gt__',
'__ge__',
'__hash__',
'__bool__',
'__getattr__',
'__getattribute__',
'__setattr__',
'__delattr__',
'__dir__',
'__get__',
'__set__',
'__delete__',
'__set_name__',
'__init_subclass__',
'__instancecheck__',
'__subclasscheck__',
'__class_getitem__',
'__call__',
'__len__',
'__length_hint__',
'__getitem__',
'__setitem__',
'__delitem__',
'__missing__',
'__iter__',
'__reversed__',
'__contains__',
'__add__',
'__sub__',
'__mul__',
'__matmul__',
'__truediv__',
'__floordiv__',
'__mod__',
'__divmod__',
'__pow__',
'__lshift__',
'__rshift__',
'__and__',
'__xor__',
'__or__',
'__radd__',
'__rsub__',
'__rmul__',
'__rmatmul__',
'__rtruediv__',
'__rfloordiv__',
'__rmod__',
'__rdivmod__',
'__rpow__',
'__rlshift__',
'__rrshift__',
'__rand__',
'__rxor__',
'__ror__',
'__iadd__',
'__isub__',
'__imul__',
'__imatmul__',
'__itruediv__',
'__ifloordiv__',
'__imod__',
'__ipow__',
'__ilshift__',
'__irshift__',
'__iand__',
'__ixor__',
'__ior__',
'__neg__',
'__pos__',
'__abs__',
'__invert__',
'__complex__',
'__int__',
'__float__',
'__index__',
'__round__',
'__trunc__',
'__floor__',
'__ceil__',
'__enter__',
'__exit__',
'__await__',
'__aiter__',
'__anext__',
'__aenter__',
'__aexit__',
))
#: List of magic methods that are forbidden to use.
MAGIC_METHODS_BLACKLIST: Final = frozenset((
# Since we don't use `del`:
'__del__',
'__delitem__',
'__delete__',
# Since we don't use `pickle`:
'__reduce__',
'__reduce_ex__',
'__dir__', # since we don't use `dir()`
'__delattr__', # since we don't use `delattr()`
))
#: List of magic methods that are not allowed to be generators.
YIELD_MAGIC_METHODS_BLACKLIST: Final = ALL_MAGIC_METHODS.difference({
# Allowed to be used with ``yield`` keyword:
'__call__', # Fixes Issue:146
'__iter__',
})
#: List of magic methods that are not allowed to be async.
ASYNC_MAGIC_METHODS_BLACKLIST: Final = ALL_MAGIC_METHODS.difference({
# In order of appearance on
# https://docs.python.org/3/reference/datamodel.html#basic-customization
# Allowed magic methods are:
'__anext__',
'__aenter__',
'__aexit__',
'__call__',
})
#: List of builtin classes that are allowed to subclass.
ALLOWED_BUILTIN_CLASSES: Final = frozenset((
'type',
'object',
))
#: List of nested functions' names we allow to use.
NESTED_FUNCTIONS_WHITELIST: Final = frozenset((
'decorator',
'factory',
'wrapper',
))
#: List of allowed ``__future__`` imports.
FUTURE_IMPORTS_WHITELIST: Final = frozenset((
'annotations',
'generator_stop',
))
#: List of blacklisted module names.
MODULE_NAMES_BLACKLIST: Final = frozenset((
'util',
'utils',
'utilities',
'helpers',
))
#: List of allowed module magic names.
MAGIC_MODULE_NAMES_WHITELIST: Final = frozenset((
'__init__',
'__main__',
))
#: List of bad magic module functions.
MAGIC_MODULE_NAMES_BLACKLIST: Final = frozenset((
'__getattr__',
'__dir__',
))
#: Regex pattern to name modules.
MODULE_NAME_PATTERN: Final = re.compile(r'^_?_?[a-z][a-z\d_]*[a-z\d](__)?$')
#: Common numbers that are allowed to be used without being called "magic".
MAGIC_NUMBERS_WHITELIST: Final = frozenset((
0, # both int and float
0.1,
0.5,
1.0,
100,
1000,
1024, # bytes
24, # hours
60, # seconds, minutes
1j, # imaginary part of a complex number
))
#: Maximum amount of ``pragma`` no-cover comments per module.
MAX_NO_COVER_COMMENTS: Final = 5
#: Maximum length of ``yield`` ``tuple`` expressions.
MAX_LEN_YIELD_TUPLE: Final = 5
#: Maximum number of compare nodes in a single expression.
MAX_COMPARES: Final = 2
#: Maximum number of conditions in a single ``if`` or ``while`` statement.
MAX_CONDITIONS: Final = 4
#: Maximum number of `elif` blocks in a single `if` condition:
MAX_ELIFS: Final = 3
#: Maximum number of ``except`` cases in a single ``try`` clause.
MAX_EXCEPT_CASES: Final = 3
#: Approximate constants which real values should be imported from math module.
MATH_APPROXIMATE_CONSTANTS: Final = frozenset((
math.pi,
math.e,
math.tau,
))
#: List of vague method names that may cause confusion if imported as is:
VAGUE_IMPORTS_BLACKLIST: Final = frozenset((
'read',
'write',
'load',
'loads',
'dump',
'dumps',
'parse',
'safe_load',
'safe_dump',
'load_all',
'dump_all',
'safe_load_all',
'safe_dump_all',
))
#: List of literals without arguments we forbid to use.
LITERALS_BLACKLIST: Final = frozenset((
'int',
'float',
'str',
'bytes',
'bool',
'complex',
))
#: List of functions in which arguments must be tuples.
TUPLE_ARGUMENTS_METHODS: Final = frozenset((
'frozenset',
))
#: Conditions that can appear in the ``if`` statement to allow nested imports.
ALLOWED_NESTED_IMPORTS_CONDITIONS: Final = frozenset((
'TYPE_CHECKING',
))
#: List of commonly used aliases
ALIAS_NAMES_WHITELIST: Final = frozenset((
'np',
'pd',
'df',
'plt',
'sns',
'tf',
'cv',
))
# Internal variables
# ==================
# Please, do not touch values beyond this line!
# ---------------------------------------------
# They are not publicly documented since they are not used by the end user.
# But, we still need them to be defined here.
# Used as a default filename, when it is not passed by flake8:
STDIN: Final = 'stdin'
# Used to specify as a placeholder for `__init__`:
INIT: Final = '__init__'
# Used to determine when we are running on Windows:
WINDOWS_OS: Final = 'nt'
# Used as a placeholder for special `_` variable:
UNUSED_PLACEHOLDER: Final = '_'
| 19.912322
| 79
| 0.617756
|
acfede504fd745b36cb09e180bae5338e837098b
| 3,260
|
py
|
Python
|
src/secondaires/botanique/masques/element_recoltable/__init__.py
|
stormi/tsunami
|
bdc853229834b52b2ee8ed54a3161a1a3133d926
|
[
"BSD-3-Clause"
] | null | null | null |
src/secondaires/botanique/masques/element_recoltable/__init__.py
|
stormi/tsunami
|
bdc853229834b52b2ee8ed54a3161a1a3133d926
|
[
"BSD-3-Clause"
] | null | null | null |
src/secondaires/botanique/masques/element_recoltable/__init__.py
|
stormi/tsunami
|
bdc853229834b52b2ee8ed54a3161a1a3133d926
|
[
"BSD-3-Clause"
] | null | null | null |
# -*-coding:Utf-8 -*
# Copyright (c) 2012 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Fichier contenant le masque <element_recoltable>."""
from primaires.interpreteur.masque.masque import Masque
from primaires.interpreteur.masque.fonctions import *
from primaires.interpreteur.masque.exceptions.erreur_validation \
import ErreurValidation
class ElementRecoltable(Masque):
"""Masque <element_recoltable>.
On attend un élément récoltable en paramètre, comme feuilles, fruits...
"""
nom = "element_recoltable"
nom_complet = "élément récoltable"
def init(self):
"""Initialisation des attributs"""
self.element = None
self.vegetal = None
def repartir(self, personnage, masques, commande):
"""Répartition du masque."""
lstrip(commande)
nom = liste_vers_chaine(commande)
if not nom:
raise ErreurValidation(
"Précisez un élément récoltable.")
self.a_interpreter = nom
commande[:] = []
masques.append(self)
return True
def valider(self, personnage, dic_masques):
"""Validation du masque"""
Masque.valider(self, personnage, dic_masques)
nom = self.a_interpreter
salle = personnage.salle
vegetal = self.vegetal
if vegetal is None:
raise ErreurValidation(
"|err|Aucun végétal n'est précisé.|ff|")
try:
element = vegetal.periode.get_element(nom)
except ValueError:
raise ErreurValidation(
"|err|L'élément récoltable {} est introuvable.|ff|".format(
nom))
self.element = element
return True
| 37.471264
| 79
| 0.68589
|
acfedef27a2a95fa23e2012c42bf2ac03be150af
| 9,532
|
py
|
Python
|
images/gao.py
|
iruletheworld/Visualisaion-for-Symmetrical-Components-Fortescue-Clarke-Parke
|
732b3bd935e0cbbf722853f1e6e125aa2034a61b
|
[
"Apache-2.0"
] | 3
|
2017-12-13T19:21:01.000Z
|
2020-04-11T14:13:01.000Z
|
images/gao.py
|
iruletheworld/Visualisaion-for-Symmetrical-Components-Fortescue-Clarke-Parke
|
732b3bd935e0cbbf722853f1e6e125aa2034a61b
|
[
"Apache-2.0"
] | null | null | null |
images/gao.py
|
iruletheworld/Visualisaion-for-Symmetrical-Components-Fortescue-Clarke-Parke
|
732b3bd935e0cbbf722853f1e6e125aa2034a61b
|
[
"Apache-2.0"
] | 1
|
2017-12-13T19:21:21.000Z
|
2017-12-13T19:21:21.000Z
|
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.6.2)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x08\x34\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\xa6\x00\x00\x00\xd9\x08\x06\x00\x00\x00\xaa\xfc\x4b\x63\
\x00\x00\x00\x01\x73\x52\x47\x42\x02\x40\xc0\x7d\xc5\x00\x00\x00\
\x09\x70\x48\x59\x73\x00\x00\x12\x74\x00\x00\x12\x74\x01\xde\x66\
\x1f\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\x74\x77\x61\
\x72\x65\x00\x4d\x69\x63\x72\x6f\x73\x6f\x66\x74\x20\x4f\x66\x66\
\x69\x63\x65\x7f\xed\x35\x71\x00\x00\x07\xb4\x49\x44\x41\x54\x78\
\xda\xed\x9d\xcd\x6d\x55\x31\x10\x46\x6f\x01\x69\x00\x89\x14\x01\
\xaf\x07\x14\x21\x2a\x20\x62\xcb\x2a\xca\x86\x02\x1e\xd9\xa5\x8d\
\xd4\x01\xad\xa4\x03\x7a\x00\x21\x40\xfc\x25\x79\x77\xec\xf1\xf8\
\x9b\xf1\x59\x9c\x2d\xe4\xf9\x1e\x8f\x67\xc6\xf6\xbd\xdb\xcd\xcd\
\xcd\x06\xa0\x06\x83\x00\x88\x09\x80\x98\x80\x98\x00\x88\x09\x88\
\x09\x80\x98\x00\x88\x09\x88\x09\x80\x98\x80\x98\x00\x88\x09\x88\
\x09\x80\x98\x00\x88\x09\x88\x09\x80\x98\x80\x98\x00\x88\x09\x88\
\x09\x80\x98\x00\x88\x09\x88\x09\x80\x98\x80\x98\x00\x88\x09\x80\
\x98\x80\x98\x00\x88\x09\x88\x09\x80\x98\x80\x98\x00\x88\x09\x80\
\x98\x80\x98\x00\x88\x09\x88\x09\x80\x98\x9a\x1c\x8f\xef\x9e\x1d\
\xb6\xed\x7e\xdb\xb6\xaf\xff\x73\xb8\x7f\x77\x3c\x3e\x63\x9c\x10\
\x33\x9c\xb7\x87\xed\xee\x61\x29\x7f\x72\x78\x7b\xc7\x38\x21\xa6\
\x50\xb4\x24\x6a\x22\xe6\x24\x3e\x5e\x1e\xde\x3c\x2d\xe5\x0f\x0e\
\x97\x1f\xdf\x30\x5e\x88\x19\xc6\xd5\xab\xf3\x0f\x7b\xc4\x3c\x7f\
\x75\xf5\x81\xf1\x42\x4c\xc4\x44\x4c\xc4\x44\x4c\xc4\xcc\x57\x91\
\xff\xe2\xf9\xc5\xe7\xf7\xb7\xb7\x67\x8c\x19\x62\x0e\xe7\xf6\xf6\
\xfd\xd9\xc5\xf3\xed\xf3\x2e\x31\xb7\xf3\x2f\x17\xd7\xc7\x17\x8c\
\x1b\x62\x0e\xe7\x78\x7d\xf1\xe2\x7c\xdb\xbe\x20\x26\x62\x22\x26\
\x62\x02\x62\x22\x26\x62\x02\x62\xce\x11\x93\xdd\x1f\xc4\x0c\x62\
\xef\x76\x24\x62\x22\x26\x62\x22\x66\xfd\xa5\xb7\x3e\x39\xf2\x5e\
\x64\x83\xaf\x8a\xdb\xab\x92\xe2\xed\xde\xf2\x83\xe9\x8c\x4a\x55\
\x10\x10\x24\xa3\x6a\xdc\xf2\xbb\xeb\xd4\x37\x10\x45\x03\xc4\xb4\
\x56\xb0\x50\x04\x87\xfb\x4e\x2c\xd1\x50\x5f\x4c\x22\x24\xc8\x89\
\x89\x94\x20\x27\x26\x85\x0d\x78\x57\xe6\x34\xbc\xbb\x18\x7f\x77\
\x7c\xef\xfd\xa2\x6a\xbd\xcc\x05\xc5\xe4\x28\xda\x32\x7b\xe5\xf3\
\xc5\xe4\xad\x17\x88\x39\x43\x4c\xde\x03\x84\x98\xf1\xd5\x39\xd1\
\x0e\x8a\x9c\x2e\x02\xc4\x2c\x8b\x76\xdf\x95\x02\xad\xec\x0f\xab\
\xda\xc2\x5a\xe5\x44\x7c\x1d\x11\x57\x6c\xf2\x17\x2e\x0a\xd3\xff\
\x80\x0c\x0d\x68\x96\xfe\x85\xc4\x64\x6f\xbe\x76\x04\x4d\xf9\x47\
\x73\xac\xae\x7e\xfb\x0d\x29\x91\x13\x31\xc9\x27\x03\x49\xfe\x6e\
\x4e\xda\x3f\xce\x91\x49\x69\xf2\x64\x6e\x2d\xb1\x84\x0b\x54\xb8\
\xc3\x7e\x5b\xe2\xa8\xb9\x78\xb4\xd4\xcc\xc5\xfc\x3a\x0e\x79\xdb\
\x48\xeb\xe5\x96\x89\x5a\x2a\x1e\x13\x32\xeb\x72\xbe\x8c\x98\x59\
\x1f\x90\xed\x9d\xef\x88\x99\x44\xcc\x1a\x3b\x22\x3d\x72\x22\xa6\
\x5a\x71\x50\x6c\x1f\xb9\xf5\x2c\x40\xd6\x6f\x0d\x95\xcc\xb3\xaa\
\x7e\xf8\xa9\xa5\x28\x42\x4c\x15\x31\x0b\x9f\xb8\x69\x89\x9a\x88\
\x29\x21\x66\xfd\x6b\x1a\xd6\xb4\x06\x31\x15\xc4\x5c\xe0\xd2\x9a\
\xb5\x10\xa4\xf8\x11\x10\x73\x85\xd3\xdd\x36\x31\x69\xb0\x23\xa6\
\x64\xf1\x93\x37\xb5\x29\xf6\x30\xea\x5e\xe2\x6a\x6a\x17\xb1\x57\
\x2e\x14\x25\x0a\x7e\x8a\x79\xb5\x1e\x66\x4d\x31\x8b\xc9\xd9\xbe\
\x5f\x9e\x7b\xf5\x28\xfc\x60\x72\xe7\x9c\xdd\x07\x38\x38\x28\xac\
\xb9\x8c\x65\x5c\xd2\x3c\x4f\x51\x65\xdf\xfd\x4a\xf1\x47\xba\x1e\
\xa4\x15\x89\x24\x63\x0f\x3e\x73\xe7\x27\xc7\xb2\x36\x29\xc2\xcc\
\xba\x38\x57\xa1\x6d\x96\xe6\x0f\xe5\x22\xda\x5a\x85\x5f\x9a\x3f\
\xb4\xf7\xc0\x2c\xd7\x76\x11\x53\xba\x10\xaa\x4b\xad\xcd\x85\xf5\
\xda\x28\x48\x89\x98\xc8\x49\x4e\xb9\x94\x98\xb3\xab\x5e\x5e\x68\
\x80\x98\xbb\x58\xed\xcd\x6f\x55\xaf\x8e\x94\x13\x73\x89\x02\x69\
\xb1\x2f\x77\x2c\xf3\x43\x53\x45\xd5\xa2\x79\x23\x62\x66\x28\xb0\
\xf8\x76\x11\x62\x02\x62\x12\x21\xe9\x47\x22\xe6\x72\xc5\xd1\x42\
\xb9\x67\xf9\x1f\x58\xbe\xd7\x49\x83\x3d\x07\x9c\x42\xe2\xe3\x00\
\x2c\xcd\xec\x0e\x21\x26\x32\xae\x15\x49\xa9\x9c\x17\x24\xc3\x96\
\x66\x0a\x21\x39\x24\xbc\x9e\xa0\xf2\x52\xf2\x69\xbe\x35\x7b\xa7\
\x54\xd8\xc1\x6d\x19\xd9\xf6\x95\xd8\x16\x29\xfd\x47\xa1\xc8\x31\
\x3f\x65\xd1\x89\x9e\xcb\x4a\x99\xa5\x8d\x32\x43\x56\x85\xb1\x59\
\x67\xf9\x2e\x72\x9a\x27\xaa\x33\x31\x5b\xce\xda\x83\xce\xcb\xb5\
\xd2\x2e\xeb\x25\x97\xac\x4a\x57\x0f\xf6\x6d\x26\x1c\xee\x5f\xbe\
\xdc\x3e\x55\x6a\xca\x97\x5a\xc2\xff\x14\x72\x57\x9e\x2a\x1e\x51\
\xf7\x4f\xd6\xdf\x02\xb9\xe7\xe7\x93\x52\xa0\x44\x51\x61\xbf\x60\
\xb6\xe8\xab\x7b\x06\x72\xff\x64\xfd\xfb\x37\x78\x17\x4c\x33\xf2\
\xcd\xf4\xd1\xf2\xa1\x65\xdb\xfe\x60\xf4\xf6\x91\x6d\x93\xf5\xe1\
\xc9\xe5\xb6\x39\x31\x61\x65\x49\x9d\x5b\x3e\x36\x93\x9b\xfe\x4d\
\xb1\xaa\xdd\x56\xec\x3c\x1e\xf5\xbd\x0e\xbc\x44\x47\xcd\xe9\x0f\
\xa0\x75\x56\x3f\x35\x50\xad\xb2\x2b\xf5\x36\x3d\x3f\x8a\xe0\x22\
\x67\xf0\xc4\x4d\xd9\x4c\xdf\x53\x75\x37\x15\x01\x27\x96\x2c\xcf\
\xc2\xe2\xd4\x6f\xb0\x89\x79\x3a\x15\xe9\x96\x13\x31\x7d\xf2\x9d\
\xd6\xbe\xdf\xaf\xa8\x19\xbd\xe3\xf2\x6f\xb4\xf6\x16\xb3\xbf\x17\
\x1a\x5b\x24\x26\x6b\x1a\xdb\x06\x27\xe7\x35\x8b\xef\xbf\xf1\xf2\
\xb5\x29\xba\x19\xa2\x59\x4f\x41\x14\x99\xea\xe4\xca\x2f\x8d\xcb\
\xc9\x2a\xe7\x38\xad\xc2\xb4\xa6\x24\x88\xe9\xb8\x94\xd4\xbf\x9c\
\x66\x1f\x97\xde\x34\x07\x31\x1d\x7a\x8d\xf5\xef\x07\xb5\x8d\xcb\
\xa8\xa2\xb3\x84\x98\xa6\xc1\xe9\xa8\x0a\x4b\xdf\x2d\x6f\x6c\x7e\
\xb7\xe4\x9a\x4b\x88\x69\xcd\xff\x7a\x06\xa5\xf4\x72\xde\x28\x66\
\xd3\x4a\x12\xd8\x32\x4a\x53\x91\xf7\xe4\x37\xa5\xef\x0d\x45\xae\
\x24\x81\x5b\x93\x69\x2a\xf2\x1e\x31\x4b\x5f\xfb\xed\x10\xd3\x3e\
\x61\xe3\x7a\x99\x6b\x88\x59\xb9\x00\xea\x10\xb3\x65\x5c\xa2\x2a\
\xf3\x25\xc4\xf4\xee\x67\x5a\xf3\xdd\xa1\x11\xbb\x33\xef\xb3\x2e\
\xe7\x88\xe9\xbc\x84\x34\x57\xe6\xce\x79\xd5\xec\x49\x32\x33\xd7\
\x47\xcc\x24\x91\xc1\xfb\xd4\x7e\xc8\x44\x09\xaa\xcc\xa7\x89\x69\
\x7b\x28\xd1\x62\xc6\x1e\x58\xe8\xe9\xb3\x7a\x4c\xa0\xe8\x67\x51\
\x48\xcc\xfe\x13\xe6\xb6\x87\x1f\x7f\xa2\xbd\xb5\x40\xf3\x10\xd3\
\xba\x9c\x47\x34\xda\x73\xec\xfa\x38\x88\x62\x9a\x08\x13\x2f\xa9\
\xcd\x88\x5e\x91\x9b\x1d\xb5\xc4\x74\x10\x25\x8b\x98\x11\xe7\x07\
\x7a\xc7\xa7\xac\x98\xe6\x84\xdb\x41\x94\xa8\x7d\xf9\xc8\x25\xd5\
\x53\x4c\xb5\xea\x3c\x87\x98\x0e\xa2\x64\x10\xd3\x5c\xa5\x3b\x46\
\x76\xb5\xea\x7c\x4b\x11\x19\x10\x33\xe4\xef\x34\xfd\xff\x15\xc5\
\xb4\xee\xfa\x78\xe4\x34\xea\x62\x2a\x1c\x43\x53\x5a\xce\x53\x88\
\xd9\x3b\x00\x33\x72\xda\x88\x5e\xa6\xb7\x18\x4a\xe3\x84\x98\x02\
\xd7\x08\xda\xf6\xd2\xc7\xf4\x5a\x55\x9a\xed\x09\x9a\xeb\xfd\x3f\
\xbe\xa5\x79\x1d\x79\x5a\x7b\xc4\x1d\xf8\xa8\x49\x32\x6a\x9c\x12\
\x88\xd9\x1f\x19\x94\xc5\x6c\x3e\x79\x34\x28\x0f\x56\x69\xb6\x2f\
\xd1\x5c\x57\x16\x53\xf1\x2a\xad\xb5\x3b\x30\x62\xac\xf4\x5b\x45\
\x93\xc4\x8c\x90\xb3\xfd\x9c\xe6\xd8\xbd\xfc\x19\xcf\x68\xba\x98\
\xa3\x5f\x72\xe0\x55\xfc\x8c\x16\xa0\xeb\x5c\xe6\xe0\x76\x96\xc2\
\xc9\xf6\x25\x7a\x98\x8a\x12\xf4\x9c\xc5\x8c\xe8\x18\xd8\x53\x0c\
\xdf\x49\x5c\xbe\x55\xd4\x9b\xcb\x8d\x90\xb3\xef\xaa\x45\xcc\x91\
\xbc\xd9\x0d\xff\xf2\xad\xa2\x9e\x81\x1e\x91\x47\xf5\xde\xff\x09\
\xeb\x16\x34\xe5\xe5\x7e\x93\x46\xbb\xf0\xf1\x3c\x3d\x23\xf0\x66\
\xdd\xfe\xfb\xed\x09\x4e\xd6\x3b\xad\x2e\xc2\xd1\xd2\xbf\xda\xf3\
\x7c\x55\x8c\x45\x50\xb7\x0b\x68\xc1\x7b\xf8\x6d\x13\xc9\x67\xf2\
\x68\x8b\x29\x95\xdb\xd9\xa3\xba\xef\x7d\xf6\x3c\xd7\x3d\x3c\x02\
\x8a\xb4\x98\x23\xf2\xa9\xac\xef\x31\x9a\xf5\x7e\xf8\xd6\x55\xa6\
\xf7\xd9\x09\x2f\x0b\x63\xf2\xa9\x94\x2f\x73\x9d\xf8\x45\x8d\xf6\
\xbc\xb8\xef\xf9\xe9\x2e\xe3\x03\x97\xae\x54\xaf\x8c\x99\xfc\xf5\
\xb6\xae\xb1\xea\xf8\xdb\x97\x29\x7c\x52\x46\x4e\x91\x4f\x0a\xf6\
\x14\x8d\xad\x4b\xba\xec\x72\xa0\x7e\x88\xa2\xf2\xf2\xed\xdd\xe6\
\x6a\xc9\x8f\x65\x67\x9c\xfe\x41\xdd\x51\xe8\x7d\xdb\xb2\x3f\xf5\
\xb1\xa7\x65\xa2\x0f\x7d\xce\xc3\x99\xfb\x82\x57\xbd\xef\x59\xba\
\xae\x2c\xc6\xb4\x44\xf3\x07\x4d\xce\xad\x42\xf3\x4f\xb1\x6f\x58\
\x0e\x6d\xb3\x19\x7e\xab\xe6\x12\x29\xf4\xb0\xc6\x48\xaa\x1d\x1d\
\x47\xa6\x3b\x7b\x6b\x07\xc9\x07\xaa\xf4\xb1\x51\xaf\x25\x5f\xfd\
\x37\x45\x4e\xd0\x3d\x72\xea\x85\x7e\x91\x16\x09\x8c\x2c\x12\x4f\
\xd7\x10\x62\xf9\x88\x5e\x45\x0a\x83\x0a\xc4\x13\xe9\x9a\x54\x92\
\x1c\x79\x65\x16\x26\x17\x42\x27\xd2\x1b\x9d\x99\x94\xa4\x3a\x05\
\xa7\xf6\xd1\x89\x67\xae\x11\xda\xc9\x2b\x17\x2d\x86\x1e\x4f\xdd\
\x04\x12\xe1\x7c\xad\x13\xf0\x93\xf3\xb1\xe5\x7c\x5e\x18\x47\x4a\
\xe4\xf4\x12\x33\xfb\x89\x6c\xd0\xcb\x39\xbb\xc5\x44\x4a\x18\x51\
\x6f\x74\x8b\xe9\x76\x25\x81\xea\x9b\xa5\xdd\xab\xf8\xf1\xda\x8e\
\xca\xbe\x2d\x07\x9e\x11\xf4\xe9\x55\x33\x44\x4c\x1a\xe7\x60\x65\
\xa0\x98\xe4\x91\xa0\x22\x26\xf9\x23\x44\x8a\x09\x80\x98\x00\x88\
\x09\x88\x09\x80\x98\x80\x98\x00\x88\x09\x88\x09\x80\x98\x00\x88\
\x09\x88\x09\x80\x98\x80\x98\x00\x88\x09\x88\x09\x80\x98\x00\x88\
\x09\x88\x09\x80\x98\x80\x98\x00\x88\x09\x88\x09\x80\x98\x00\x88\
\x09\x88\x09\x80\x98\x80\x98\x00\x88\x09\x80\x98\xa0\xcc\x37\x3d\
\x80\x55\x52\xf6\xbe\x19\x3a\x00\x00\x00\x00\x49\x45\x4e\x44\xae\
\x42\x60\x82\
"
qt_resource_name = b"\
\x00\x03\
\x00\x00\x6d\x7f\
\x00\x67\
\x00\x61\x00\x6f\
\x00\x07\
\x0d\x82\x57\x87\
\x00\x67\
\x00\x61\x00\x6f\x00\x2e\x00\x70\x00\x6e\x00\x67\
"
qt_resource_struct = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\
\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
"
def qInitResources():
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()
| 55.418605
| 96
| 0.727444
|
acfedff9e41e527ab48dffb8e68e60f9e7e7443b
| 7,395
|
py
|
Python
|
bindings/python/cntk/ops/tests/ops_test_utils.py
|
KeDengMS/CNTK
|
fce86cd9581e7ba746d1ec75bbd67dd35d35d11c
|
[
"RSA-MD"
] | 1
|
2021-05-09T01:37:49.000Z
|
2021-05-09T01:37:49.000Z
|
bindings/python/cntk/ops/tests/ops_test_utils.py
|
KeDengMS/CNTK
|
fce86cd9581e7ba746d1ec75bbd67dd35d35d11c
|
[
"RSA-MD"
] | null | null | null |
bindings/python/cntk/ops/tests/ops_test_utils.py
|
KeDengMS/CNTK
|
fce86cd9581e7ba746d1ec75bbd67dd35d35d11c
|
[
"RSA-MD"
] | null | null | null |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
"""
Utils for operations unit tests
"""
import numpy as np
import pytest
from cntk.tests.test_utils import *
from ...ops.functions import Function
from ...utils import sanitize_dtype_cntk
from ...utils import eval as cntk_eval, cntk_device
from .. import constant, input_variable
I = input_variable
@pytest.fixture(params=["dense", "sparse"])
def left_matrix_type(request):
return request.param
@pytest.fixture(params=["dense", "sparse"])
def right_matrix_type(request):
return request.param
def _test_unary_op(precision, device_id, op_func,
value, expected_forward, expected_backward_all, op_param_dict=None):
value = AA(value, dtype=PRECISION_TO_TYPE[precision])
a = I(shape=value.shape,
data_type=sanitize_dtype_cntk(PRECISION_TO_TYPE[precision]),
needs_gradient=True,
name='a')
# create batch
value.shape = (1, 1) + value.shape
if (type(op_func) == str):
input_op = eval('%s a' % op_func)
elif op_param_dict:
input_op = op_func(a, **op_param_dict)
else:
input_op = op_func(a)
forward_input = {a: value}
expected_backward = {a: expected_backward_all['arg'], }
unittest_helper(input_op,
forward_input, expected_forward, expected_backward,
device_id=device_id, precision=precision)
def _test_binary_op(precision, device_id, op_func, left_operand, right_operand,
expected_forward, expected_backward_all,
only_input_variables=False, wrap_batch_seq=True):
left_value = AA(left_operand, dtype=PRECISION_TO_TYPE[precision])
right_value = AA(right_operand, dtype=PRECISION_TO_TYPE[precision])
a = I(shape=left_value.shape,
data_type=sanitize_dtype_cntk(precision),
needs_gradient=True,
name='a')
b = I(shape=right_value.shape,
data_type=sanitize_dtype_cntk(precision),
needs_gradient=True,
name='b')
if (type(op_func) == str):
input_op_constant = eval('a %s right_operand' % op_func)
constant_op_input = eval('left_operand %s b' % op_func)
input_op_input = eval('a %s b' % op_func)
else:
input_op_constant = op_func(a, right_value)
constant_op_input = op_func(left_value, b)
input_op_input = op_func(a, b)
# create batch by wrapping the data point into a sequence of length one and
# putting it into a batch of one sample
if wrap_batch_seq:
left_value.shape = (1, 1) + left_value.shape
right_value.shape = (1, 1) + right_value.shape
forward_input = {a: left_value, b: right_value}
expected_backward = {a: expected_backward_all[
'left_arg'], b: expected_backward_all['right_arg'], }
unittest_helper(input_op_input,
forward_input, expected_forward, expected_backward,
device_id=device_id, precision=precision)
if not only_input_variables:
forward_input = {a: left_value}
expected_backward = {a: expected_backward_all['left_arg'], }
unittest_helper(input_op_constant,
forward_input, expected_forward, expected_backward,
device_id=device_id, precision=precision)
forward_input = {b: right_value}
expected_backward = {b: expected_backward_all['right_arg'], }
unittest_helper(constant_op_input,
forward_input, expected_forward, expected_backward,
device_id=device_id, precision=precision)
def unittest_helper(root_node,
forward_input, expected_forward, expected_backward,
device_id=-1, precision="float"):
assert isinstance(root_node, Function)
backward_pass = expected_backward is not None
forward, backward = cntk_eval(root_node, forward_input, precision,
cntk_device(device_id), backward_pass)
# for forward we always expect only one result
assert len(forward) == 1
forward = list(forward.values())[0]
forward = np.atleast_1d(forward)
for res, exp in zip(forward, expected_forward):
assert res.shape == AA(exp).shape
assert np.allclose(res, exp, atol=TOLERANCE_ABSOLUTE)
if expected_backward:
for key in expected_backward:
res, exp = backward[key], expected_backward[key]
if isinstance(res, list):
assert len(res) == len(exp)
for res_seq, exp_seq in zip(res, exp):
assert res_seq.shape == AA(exp_seq).shape
assert np.allclose(
res_seq, exp_seq, atol=TOLERANCE_ABSOLUTE)
elif isinstance(res, np.ndarray):
assert res.shape == AA(exp).shape
assert np.allclose(res, exp, atol=TOLERANCE_ABSOLUTE)
def batch_dense_to_sparse(batch, dynamic_axis=''):
'''
Helper test function that converts a batch of dense tensors into sparse
representation that can be consumed by :func:`cntk.ops.sparse_input_numpy`.
Args:
batch (list): list of samples. If ``dynamic_axis`` is given, samples are sequences
of tensors. Otherwise, they are simple tensors.
dynamic_axis (str or :func:`cntk.ops.dynamic_axis` instance): the dynamic axis
Returns:
(indices, values, shape)
'''
batch_indices = []
batch_values = []
tensor_shape = []
shapes_in_tensor = set()
for tensor in batch:
if isinstance(tensor, list):
tensor = np.asarray(tensor)
if dynamic_axis:
# collecting the shapes ignoring the dynamic axis
shapes_in_tensor.add(tensor.shape[1:])
else:
shapes_in_tensor.add(tensor.shape)
if len(shapes_in_tensor) != 1:
raise ValueError('except for the sequence dimensions all shapes ' +
'should be the same - instead we %s' %
(", ".join(str(s) for s in shapes_in_tensor)))
t_indices = range(tensor.size)
t_values = tensor.ravel(order='F')
mask = t_values != 0
batch_indices.append(list(np.asarray(t_indices)[mask]))
batch_values.append(list(np.asarray(t_values)[mask]))
return batch_indices, batch_values, shapes_in_tensor.pop()
def test_batch_dense_to_sparse_full():
i, v, s = batch_dense_to_sparse(
[
[[1, 2, 3], [4, 5, 6]],
[[10, 20, 30], [40, 50, 60]],
])
assert i == [
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
]
assert v == [
[1, 4, 2, 5, 3, 6],
[10, 40, 20, 50, 30, 60]
]
assert s == (2, 3)
i, v, s = batch_dense_to_sparse([[1]])
assert i == [[0]]
assert v == [[1]]
assert s == (1,)
def test_batch_dense_to_sparse_zeros():
i, v, s = batch_dense_to_sparse(
[
[[1, 2, 3], [4, 0, 6]],
[[0, 0, 0], [40, 50, 60]],
])
assert i == [
[0, 1, 2, 4, 5],
[1, 3, 5],
]
assert v == [
[1, 4, 2, 3, 6],
[40, 50, 60]
]
assert s == (2, 3)
| 32.152174
| 90
| 0.607708
|
acfee089ad6d2cc5ff85500b5591b2da726dce46
| 916
|
py
|
Python
|
notify/by_multiple.py
|
bttg/UoM-WAM-Spam
|
8083cbac003397e9c022c02bc427454638dd235f
|
[
"MIT"
] | 54
|
2019-06-20T00:50:38.000Z
|
2021-12-01T06:59:38.000Z
|
notify/by_multiple.py
|
bttg/UoM-WAM-Spam
|
8083cbac003397e9c022c02bc427454638dd235f
|
[
"MIT"
] | 18
|
2019-06-21T00:20:54.000Z
|
2020-12-03T22:04:15.000Z
|
notify/by_multiple.py
|
bttg/UoM-WAM-Spam
|
8083cbac003397e9c022c02bc427454638dd235f
|
[
"MIT"
] | 24
|
2019-06-20T02:49:18.000Z
|
2021-12-02T08:22:09.000Z
|
"""
Multiple-method notifier
:author: Matthew Farrugia-Roberts
"""
class MultiNotifier:
def __init__(self, notifiers=None):
if notifiers is not None:
self.notifiers = notifiers
else:
self.notifiers = []
def add_notifier(self, notifier):
self.notifiers.append(notifier)
def notify(self, subject: str, text: str) -> None:
print("Triggering all notification methods...")
problems = []
nsuccess, nfail = 0, 0
for notifier in self.notifiers:
try:
notifier.notify(subject, text)
nsuccess += 1
except Exception as e:
problems.append((notifier, e))
nfail += 1
print(f"{nsuccess} notification methods triggered, {nfail} failed.")
if problems != []:
raise Exception("Some notification methods failed.", *problems)
| 29.548387
| 76
| 0.575328
|
acfee098d5e002410f88314b31391a5803f56d47
| 10,926
|
py
|
Python
|
sympy/physics/quantum/tensorproduct.py
|
sn6uv/sympy
|
5b149c2f72847e4785c65358b09d99b29f101dd5
|
[
"BSD-3-Clause"
] | null | null | null |
sympy/physics/quantum/tensorproduct.py
|
sn6uv/sympy
|
5b149c2f72847e4785c65358b09d99b29f101dd5
|
[
"BSD-3-Clause"
] | null | null | null |
sympy/physics/quantum/tensorproduct.py
|
sn6uv/sympy
|
5b149c2f72847e4785c65358b09d99b29f101dd5
|
[
"BSD-3-Clause"
] | null | null | null |
"""Abstract tensor product."""
from sympy import Expr, Add, Mul, Matrix, Pow, sympify
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.qexpr import QuantumError
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.matrixutils import (
numpy_ndarray,
scipy_sparse_matrix,
matrix_tensor_product
)
from sympy.core.trace import Tr
__all__ = [
'TensorProduct',
'tensor_product_simp'
]
#-----------------------------------------------------------------------------
# Tensor product
#-----------------------------------------------------------------------------
class TensorProduct(Expr):
"""The tensor product of two or more arguments.
For matrices, this uses ``matrix_tensor_product`` to compute the Kronecker
or tensor product matrix. For other objects a symbolic ``TensorProduct``
instance is returned. The tensor product is a non-commutative
multiplication that is used primarily with operators and states in quantum
mechanics.
Currently, the tensor product distinguishes between commutative and non-
commutative arguments. Commutative arguments are assumed to be scalars and
are pulled out in front of the ``TensorProduct``. Non-commutative arguments
remain in the resulting ``TensorProduct``.
Parameters
==========
args : tuple
A sequence of the objects to take the tensor product of.
Examples
========
Start with a simple tensor product of sympy matrices::
>>> from sympy import I, Matrix, symbols
>>> from sympy.physics.quantum import TensorProduct
>>> m1 = Matrix([[1,2],[3,4]])
>>> m2 = Matrix([[1,0],[0,1]])
>>> TensorProduct(m1, m2)
[1, 0, 2, 0]
[0, 1, 0, 2]
[3, 0, 4, 0]
[0, 3, 0, 4]
>>> TensorProduct(m2, m1)
[1, 2, 0, 0]
[3, 4, 0, 0]
[0, 0, 1, 2]
[0, 0, 3, 4]
We can also construct tensor products of non-commutative symbols:
>>> from sympy import Symbol
>>> A = Symbol('A',commutative=False)
>>> B = Symbol('B',commutative=False)
>>> tp = TensorProduct(A, B)
>>> tp
AxB
We can take the dagger of a tensor product (note the order does NOT reverse
like the dagger of a normal product):
>>> from sympy.physics.quantum import Dagger
>>> Dagger(tp)
Dagger(A)xDagger(B)
Expand can be used to distribute a tensor product across addition:
>>> C = Symbol('C',commutative=False)
>>> tp = TensorProduct(A+B,C)
>>> tp
(A + B)xC
>>> tp.expand(tensorproduct=True)
AxC + BxC
"""
is_commutative = False
def __new__(cls, *args):
if isinstance(args[0], (Matrix, numpy_ndarray, scipy_sparse_matrix)):
return matrix_tensor_product(*args)
c_part, new_args = cls.flatten(sympify(args))
c_part = Mul(*c_part)
if len(new_args) == 0:
return c_part
elif len(new_args) == 1:
return c_part*new_args[0]
else:
tp = Expr.__new__(cls, *new_args)
return c_part*tp
@classmethod
def flatten(cls, args):
# TODO: disallow nested TensorProducts.
c_part = []
nc_parts = []
for arg in args:
cp, ncp = arg.args_cnc()
c_part.extend(list(cp))
nc_parts.append(Mul._from_args(ncp))
return c_part, nc_parts
def _eval_adjoint(self):
return TensorProduct(*[Dagger(i) for i in self.args])
def _eval_rewrite(self, pattern, rule, **hints):
sargs = self.args
terms = [ t._eval_rewrite(pattern, rule, **hints) for t in sargs]
return TensorProduct(*terms).expand(tensorproduct=True)
def _sympystr(self, printer, *args):
from sympy.printing.str import sstr
length = len(self.args)
s = ''
for i in range(length):
if isinstance(self.args[i], (Add, Pow, Mul)):
s = s + '('
s = s + sstr(self.args[i])
if isinstance(self.args[i], (Add, Pow, Mul)):
s = s + ')'
if i != length-1:
s = s + 'x'
return s
def _pretty(self, printer, *args):
length = len(self.args)
pform = printer._print('', *args)
for i in range(length):
next_pform = printer._print(self.args[i], *args)
if isinstance(self.args[i], (Add, Mul)):
next_pform = prettyForm(
*next_pform.parens(left='(', right=')')
)
pform = prettyForm(*pform.right(next_pform))
if i != length-1:
if printer._use_unicode:
pform = prettyForm(*pform.right(u'\u2a02' + u' '))
else:
pform = prettyForm(*pform.right('x' + ' '))
return pform
def _latex(self, printer, *args):
length = len(self.args)
s = ''
for i in range(length):
if isinstance(self.args[i], (Add, Mul)):
s = s + '\\left('
# The extra {} brackets are needed to get matplotlib's latex
# rendered to render this properly.
s = s + '{' + printer._print(self.args[i], *args) + '}'
if isinstance(self.args[i], (Add, Mul)):
s = s + '\\right)'
if i != length-1:
s = s + '\\otimes '
return s
def doit(self, **hints):
return TensorProduct(*[item.doit(**hints) for item in self.args])
def _eval_expand_tensorproduct(self, **hints):
"""Distribute TensorProducts across addition."""
args = self.args
add_args = []
stop = False
for i in range(len(args)):
if isinstance(args[i], Add):
for aa in args[i].args:
tp = TensorProduct(*args[:i]+(aa,)+args[i+1:])
if isinstance(tp, TensorProduct):
tp = tp._eval_expand_tensorproduct()
add_args.append(tp)
break
if add_args:
return Add(*add_args)
else:
return self
def _eval_trace(self, **kwargs):
indices = kwargs.get('indices', None)
exp = tensor_product_simp(self)
if indices is None or len(indices) == 0:
return Mul(*[Tr(arg).doit() for arg in exp.args])
else:
return Mul(*[Tr(value).doit() if idx in indices else value
for idx, value in enumerate(exp.args)])
def tensor_product_simp_Mul(e):
"""Simplify a Mul with TensorProducts.
Current the main use of this is to simplify a ``Mul`` of ``TensorProduct``s
to a ``TensorProduct`` of ``Muls``. It currently only works for relatively
simple cases where the initial ``Mul`` only has scalars and raw
``TensorProduct``s, not ``Add``, ``Pow``, ``Commutator``s of
``TensorProduct``s.
Parameters
==========
e : Expr
A ``Mul`` of ``TensorProduct``s to be simplified.
Returns
=======
e : Expr
A ``TensorProduct`` of ``Mul``s.
Examples
========
This is an example of the type of simplification that this function
performs::
>>> from sympy.physics.quantum.tensorproduct import tensor_product_simp_Mul, TensorProduct
>>> from sympy import Symbol
>>> A = Symbol('A',commutative=False)
>>> B = Symbol('B',commutative=False)
>>> C = Symbol('C',commutative=False)
>>> D = Symbol('D',commutative=False)
>>> e = TensorProduct(A,B)*TensorProduct(C,D)
>>> e
AxB*CxD
>>> tensor_product_simp_Mul(e)
(A*C)x(B*D)
"""
# TODO: This won't work with Muls that have other composites of
# TensorProducts, like an Add, Pow, Commutator, etc.
# TODO: This only works for the equivalent of single Qbit gates.
if not isinstance(e, Mul):
return e
c_part, nc_part = e.args_cnc()
n_nc = len(nc_part)
if n_nc == 0 or n_nc == 1:
return e
elif e.has(TensorProduct):
current = nc_part[0]
if not isinstance(current, TensorProduct):
raise TypeError('TensorProduct expected, got: %r' % current)
n_terms = len(current.args)
new_args = list(current.args)
for next in nc_part[1:]:
# TODO: check the hilbert spaces of next and current here.
if isinstance(next, TensorProduct):
if n_terms != len(next.args):
raise QuantumError(
'TensorProducts of different lengths: %r and %r' % \
(current, next)
)
for i in range(len(new_args)):
new_args[i] = new_args[i]*next.args[i]
else:
# this won't quite work as we don't want next in the TensorProduct
for i in range(len(new_args)):
new_args[i] = new_args[i]*next
current = next
return Mul(*c_part)*TensorProduct(*new_args)
else:
return e
def tensor_product_simp(e, **hints):
"""Try to simplify and combine TensorProducts.
In general this will try to pull expressions inside of ``TensorProducts``.
It currently only works for relatively simple cases where the products have
only scalars, raw ``TensorProducts``, not ``Add``, ``Pow``, ``Commutators``
of ``TensorProducts``. It is best to see what it does by showing examples.
Examples
========
>>> from sympy.physics.quantum import tensor_product_simp
>>> from sympy.physics.quantum import TensorProduct
>>> from sympy import Symbol
>>> A = Symbol('A',commutative=False)
>>> B = Symbol('B',commutative=False)
>>> C = Symbol('C',commutative=False)
>>> D = Symbol('D',commutative=False)
First see what happens to products of tensor products:
>>> e = TensorProduct(A,B)*TensorProduct(C,D)
>>> e
AxB*CxD
>>> tensor_product_simp(e)
(A*C)x(B*D)
This is the core logic of this function, and it works inside, powers, sums,
commutators and anticommutators as well:
>>> tensor_product_simp(e**2)
(A*C)x(B*D)**2
"""
if isinstance(e, Add):
return Add(*[tensor_product_simp(arg) for arg in e.args])
elif isinstance(e, Pow):
return tensor_product_simp(e.base)**e.exp
elif isinstance(e, Mul):
return tensor_product_simp_Mul(e)
elif isinstance(e, Commutator):
return Commutator(*[tensor_product_simp(arg) for arg in e.args])
elif isinstance(e, AntiCommutator):
return AntiCommutator(*[tensor_product_simp(arg) for arg in e.args])
else:
return e
| 33.515337
| 98
| 0.568918
|
acfee0d6f8b25d500499c1d3bde1875357abcdbd
| 2,196
|
py
|
Python
|
tests/benchmarks/scenarios/test_rl_scenario.py
|
lipovsek/avalanche
|
1f06502b12140b39f48adf5a5f3b5de8ec2a930b
|
[
"MIT"
] | null | null | null |
tests/benchmarks/scenarios/test_rl_scenario.py
|
lipovsek/avalanche
|
1f06502b12140b39f48adf5a5f3b5de8ec2a930b
|
[
"MIT"
] | null | null | null |
tests/benchmarks/scenarios/test_rl_scenario.py
|
lipovsek/avalanche
|
1f06502b12140b39f48adf5a5f3b5de8ec2a930b
|
[
"MIT"
] | null | null | null |
from avalanche.benchmarks.scenarios.rl_scenario import RLScenario, RLExperience
import unittest
import numpy as np
try:
import gym
skip = False
except ImportError:
skip = True
@unittest.skipIf(skip, reason="Need gym to run these tests")
def test_simple_scenario():
n_envs = 3
envs = [gym.make('CartPole-v1')]*n_envs
rl_scenario = RLScenario(envs, n_parallel_envs=1,
task_labels=True, eval_envs=[])
tr_stream = rl_scenario.train_stream
assert len(tr_stream) == n_envs
assert not len(rl_scenario.eval_stream)
for i, exp in enumerate(tr_stream):
assert exp.current_experience == i
env = exp.environment
# same envs
assert exp.task_label == 0
assert isinstance(env, gym.Env)
obs = env.reset()
assert isinstance(obs, np.ndarray)
@unittest.skipIf(skip, reason="Need gym to run these tests")
def test_multiple_envs():
envs = [gym.make('CartPole-v0'), gym.make('CartPole-v1'),
gym.make('Acrobot-v1')]
rl_scenario = RLScenario(envs, n_parallel_envs=1,
task_labels=True, eval_envs=envs[:2])
tr_stream = rl_scenario.train_stream
assert len(tr_stream) == 3
for i, exp in enumerate(tr_stream):
assert exp.current_experience == i == exp.task_label
assert len(rl_scenario.eval_stream) == 2
for i, exp in enumerate(rl_scenario.eval_stream):
assert exp.task_label == i
assert exp.environment.spec.id == envs[i].spec.id
# deep copies of the same env are considered as different tasks
envs = [gym.make('CartPole-v1') for _ in range(3)]
eval_envs = [gym.make('CartPole-v1')] * 2
rl_scenario = RLScenario(envs, n_parallel_envs=1,
task_labels=True, eval_envs=eval_envs)
for i, exp in enumerate(rl_scenario.train_stream):
assert exp.task_label == i
# while shallow copies in eval behave like the ones in train
assert len(rl_scenario.eval_stream) == 2
for i, exp in enumerate(rl_scenario.eval_stream):
assert exp.task_label == 0
assert exp.environment.spec.id == envs[0].spec.id
| 36.6
| 79
| 0.651184
|
acfee1295baf024a321069e60cc27f6d570ba705
| 3,504
|
py
|
Python
|
helpers/UrIII_mono.py
|
cdli-gh/Unsupervised-NMT-for-Sumerian-English-
|
40025185529e91a3af2db130445dc694d9a0ef16
|
[
"MIT"
] | 17
|
2020-08-12T08:58:27.000Z
|
2022-03-14T21:50:38.000Z
|
helpers/UrIII_mono.py
|
cdli-gh/Unsupervised-NMT-for-Sumerian-English-
|
40025185529e91a3af2db130445dc694d9a0ef16
|
[
"MIT"
] | 5
|
2020-02-26T11:58:42.000Z
|
2020-08-07T20:06:16.000Z
|
helpers/UrIII_mono.py
|
cdli-gh/Unsupervised-NMT-for-Sumerian-English-
|
40025185529e91a3af2db130445dc694d9a0ef16
|
[
"MIT"
] | 8
|
2020-02-26T16:02:25.000Z
|
2020-06-12T21:51:55.000Z
|
import pandas as pd
import re
stop_chars=["@", "&", "$", "#", ">"]
with open('../dataset/dataToUse/UrIIICompSents/test.sum', 'r') as f:
test = f.read().split('\n')
with open('../dataset/dataToUse/allCompSents/train.sum', 'r') as f:
train = f.read().split('\n')
df1 = pd.read_csv('../all_sum.csv')
lines = list(df1.values[:, 0])
def savefile(filename,LIST):
with open(filename, 'w') as f:
for line in LIST:
f.write("%s\n" % line)
def processing_1(text_line):
#x = re.sub(r"\[\.+\]","unk",text_line)
#x = re.sub(r"...","unk",x)
x = re.sub(r'\#', '', text_line)
x = re.sub(r"\_", "", x)
x = re.sub(r"\[", "", x)
x = re.sub(r"\]", "", x)
x = re.sub(r"\<", "", x)
x = re.sub(r"\>", "", x)
x = re.sub(r"\!", "", x)
x = re.sub(r"@c", "", x)
x = re.sub(r"@t", "", x)
#x=re.sub(r"(x)+","x",x)
x = re.sub(r"\?", "", x)
x = x.split()
x = " ".join(x)
k = re.search(r"[a-wyzA-Z]+",x)
if k:
return x
else:
return ""
def pretty_line_sum(text_line):
#x = re.sub(r"\[\.+\]","unk",text_line)
#x = re.sub(r"...","unk",x)
x = re.sub(r'\#', '', text_line)
x = re.sub(r"\_", "", x)
x = re.sub(r"\[", "", x)
x = re.sub(r"\]", "", x)
x = re.sub(r"\<", "", x)
x = re.sub(r"\>", "", x)
x = re.sub(r"\!", "", x)
x = re.sub(r"@c", "", x)
x = re.sub(r"@t", "", x)
#x=re.sub(r"(x)+","x",x)
x = re.sub(r"\?", "", x)
x = x.split()
x = " ".join(x)
k = re.search(r"[a-wyzA-Z]+",x)
if k:
return x
else:
return ""
def parallel(lines_r):
# pll_org = open("../sumerian_translated.atf", "r")
sum_org = open("../dataset/original/supp_sum_mono3.txt", "w")
# eng_org = open("../dataset/original/supp_eng_pll2.txt", "w")
sumerian_pll = open("../dataset/cleaned/allCompSents/mono.sum", "w")
# english_pll = open("../dataset/cleaned/allCompSents/pll.eng", "a")
# lines = pll_org.readlines()
# print(len(lines_r))
for lines in lines_r:
if(lines.find('#atf: lang sux') == -1):
continue
try:
lines = lines.split('\n')
except:
continue
# print(len(lines))
sum_lines = []
# eng_lines = []
org_sum_lines = []
# org_eng_lines = []
count_words = 0
for i in range(len(lines)):
if lines[i] != "" and lines[i] != " " and lines[i][0] not in stop_chars:
index=lines[i].find(".")
sum_line = pretty_line_sum(lines[i][index+1:])
count_words += len(sum_line.split())
if(sum_line not in sum_lines):
sum_lines.append(sum_line)
org_sum_lines.append(lines[i][index+1:])
if count_words>5 or len(sum_lines) >= 3 or i == len(lines)-1 and count_words:
sum_org.write(' '.join(org_sum_lines))
# eng_org.write(' '.join(org_eng_lines))
if(' '.join(sum_lines) not in test and ' '.join(sum_lines) not in train):
sumerian_pll.write(' '.join(sum_lines))
# english_pll.write(' '.join(eng_lines))
sumerian_pll.write('\n')
# english_pll.write('\n')
sum_lines = []
# eng_lines = []
org_sum_lines = []
# org_eng_lines = []
count_words = 0
parallel(lines)
| 32.146789
| 89
| 0.470605
|
acfee1e3fd888b55d947a83f38b539a250b89152
| 434
|
py
|
Python
|
WebGarageSale/env/lib/python3.9/site-packages/djongo/features.py
|
dayojohn19/Garage_Sale
|
a32a89392911e9ce57cd1441edcbb3781f3ee67d
|
[
"Apache-2.0"
] | 1
|
2021-09-15T01:36:55.000Z
|
2021-09-15T01:36:55.000Z
|
onboarding/Lib/site-packages/djongo/features.py
|
USPCodeLabSanca/on.boarding-2021.2---Filtro-de-Receitas
|
273c0f852c66ecec840dc8db4bd3894ef727beb0
|
[
"MIT"
] | null | null | null |
onboarding/Lib/site-packages/djongo/features.py
|
USPCodeLabSanca/on.boarding-2021.2---Filtro-de-Receitas
|
273c0f852c66ecec840dc8db4bd3894ef727beb0
|
[
"MIT"
] | 1
|
2022-03-12T01:09:35.000Z
|
2022-03-12T01:09:35.000Z
|
from django.db.backends.base.features import BaseDatabaseFeatures
class DatabaseFeatures(BaseDatabaseFeatures):
supports_transactions = False
# djongo doesn't seem to support this currently
has_bulk_insert = True
has_native_uuid_field = True
supports_timezones = False
uses_savepoints = False
can_clone_databases = True
test_db_allows_multiple_connections = False
supports_unspecified_pk = True
| 28.933333
| 65
| 0.78341
|
acfee2f4ce5fc6d7fc32cf8ec26f44ddd79b2df9
| 4,205
|
py
|
Python
|
tests/test_trs.py
|
rupertnash/cwltool
|
9ffdfe50aa5c8006d35a2a6f0ba22b772567a57f
|
[
"Apache-2.0"
] | null | null | null |
tests/test_trs.py
|
rupertnash/cwltool
|
9ffdfe50aa5c8006d35a2a6f0ba22b772567a57f
|
[
"Apache-2.0"
] | 15
|
2021-08-09T15:24:53.000Z
|
2022-03-30T20:17:42.000Z
|
tests/test_trs.py
|
rupertnash/cwltool
|
9ffdfe50aa5c8006d35a2a6f0ba22b772567a57f
|
[
"Apache-2.0"
] | 2
|
2021-10-01T10:08:32.000Z
|
2021-10-01T11:53:48.000Z
|
from typing import Any, Optional
from unittest import mock
from unittest.mock import MagicMock
from cwltool.main import main
from .util import get_data
class MockResponse1:
def __init__(
self, json_data: Any, status_code: int, raise_for_status: Optional[bool] = None
) -> None:
"""Create a fake return object for requests.Session.head."""
self.json_data = json_data
self.status_code = status_code
self.raise_for_status = mock.Mock()
self.raise_for_status.side_effect = raise_for_status
def json(self) -> Any:
return self.json_data
def mocked_requests_head(*args: Any) -> MockResponse1:
return MockResponse1(None, 200)
class MockResponse2:
def __init__(
self, json_data: Any, status_code: int, raise_for_status: Optional[bool] = None
) -> None:
"""Create a fake return object for requests.Session.get."""
self.json_data = json_data
self.text = json_data
self.status_code = status_code
self.raise_for_status = mock.Mock()
self.raise_for_status.side_effect = raise_for_status
def json(self) -> Any:
return self.json_data
headers = {"content-type": "text/plain"}
def mocked_requests_get(*args: Any, **kwargs: Any) -> MockResponse2:
if (
args[0]
== "https://dockstore.org/api/api/ga4gh/v2/tools/quay.io%2Fbriandoconnor%2Fdockstore-tool-md5sum/versions/1.0.4/CWL/files"
):
return MockResponse2(
[
{"file_type": "CONTAINERFILE", "path": "Dockerfile"},
{"file_type": "PRIMARY_DESCRIPTOR", "path": "Dockstore.cwl"},
{"file_type": "TEST_FILE", "path": "test.json"},
],
200,
)
elif (
args[0]
== "https://dockstore.org/api/api/ga4gh/v2/tools/quay.io%2Fbriandoconnor%2Fdockstore-tool-md5sum/versions/1.0.4/plain-CWL/descriptor/Dockstore.cwl"
):
string = open(get_data("tests/trs/Dockstore.cwl")).read()
return MockResponse2(string, 200)
elif (
args[0]
== "https://dockstore.org/api/api/ga4gh/v2/tools/%23workflow%2Fgithub.com%2Fdockstore-testing%2Fmd5sum-checker/versions/develop/plain-CWL/descriptor/md5sum-tool.cwl"
):
string = open(get_data("tests/trs/md5sum-tool.cwl")).read()
return MockResponse2(string, 200)
elif (
args[0]
== "https://dockstore.org/api/api/ga4gh/v2/tools/%23workflow%2Fgithub.com%2Fdockstore-testing%2Fmd5sum-checker/versions/develop/plain-CWL/descriptor/md5sum-workflow.cwl"
):
string = open(get_data("tests/trs/md5sum-workflow.cwl")).read()
return MockResponse2(string, 200)
elif (
args[0]
== "https://dockstore.org/api/api/ga4gh/v2/tools/%23workflow%2Fgithub.com%2Fdockstore-testing%2Fmd5sum-checker/versions/develop/CWL/files"
):
return MockResponse2(
[
{"file_type": "TEST_FILE", "path": "md5sum-input-cwl.json"},
{"file_type": "SECONDARY_DESCRIPTOR", "path": "md5sum-tool.cwl"},
{"file_type": "PRIMARY_DESCRIPTOR", "path": "md5sum-workflow.cwl"},
],
200,
)
print("A mocked call to TRS missed, target was %s", args[0])
return MockResponse2(None, 404)
@mock.patch("requests.Session.head", side_effect=mocked_requests_head)
@mock.patch("requests.Session.get", side_effect=mocked_requests_get)
def test_tool_trs_template(mock_head: MagicMock, mock_get: MagicMock) -> None:
params = ["--make-template", r"quay.io/briandoconnor/dockstore-tool-md5sum:1.0.4"]
return_value = main(params)
mock_head.assert_called()
mock_get.assert_called()
assert return_value == 0
@mock.patch("requests.Session.head", side_effect=mocked_requests_head)
@mock.patch("requests.Session.get", side_effect=mocked_requests_get)
def test_workflow_trs_template(mock_head: MagicMock, mock_get: MagicMock) -> None:
params = [
"--make-template",
r"#workflow/github.com/dockstore-testing/md5sum-checker:develop",
]
return_value = main(params)
mock_head.assert_called()
mock_get.assert_called()
assert return_value == 0
| 36.565217
| 177
| 0.656361
|
acfee3c1fd520d66b260a93f6c58f154fe5c1f80
| 1,573
|
py
|
Python
|
source/week5/homework_answer/3DReconstruction/stereoconfig.py
|
chargerKong/3D_detection
|
d3fb7926413f86be9f8aceac169285ee03c8db00
|
[
"Apache-2.0"
] | null | null | null |
source/week5/homework_answer/3DReconstruction/stereoconfig.py
|
chargerKong/3D_detection
|
d3fb7926413f86be9f8aceac169285ee03c8db00
|
[
"Apache-2.0"
] | null | null | null |
source/week5/homework_answer/3DReconstruction/stereoconfig.py
|
chargerKong/3D_detection
|
d3fb7926413f86be9f8aceac169285ee03c8db00
|
[
"Apache-2.0"
] | null | null | null |
#coding:utf-8
import numpy as np
####################仅仅是一个示例###################################
# 双目相机参数
class stereoCamera1(object):
#class stereoCameral(object):
def __init__(self):
# 左相机内参
self.cam_matrix_left = np.array([[1499.64168081943, 0, 1097.61651199043],
[0., 1497.98941910377, 772.371510027325],
[0., 0., 1.]])
# 右相机内参
self.cam_matrix_right = np.array([[1494.85561041115, 0, 1067.32184876563],
[0., 1491.89013795616, 777.983913223449],
[0., 0., 1.]])
# 左右相机畸变系数:[k1, k2, p1, p2, k3]
self.distortion_l = np.array([[-0.110331619900584, 0.0789239541458329, -0.000417147132750895, 0.00171210128855920, -0.00959533143245654]])
self.distortion_r = np.array([[-0.106539730103100, 0.0793246026401067, -0.000288067586478778, -8.92638488356863e-06, -0.0161669384831612]])
# 旋转矩阵
self.R = np.array([[0.993995723217419, 0.0165647819554691, 0.108157802419652],
[-0.0157381345263306, 0.999840084288358, -0.00849217121126161],
[-0.108281177252152, 0.00673897982027135, 0.994097466450785]])
# 平移矩阵
self.T = np.array([[-423.716923177417], [2.56178287450396], [21.9734621041330]])
# 焦距
self.focal_length = 1602.46406 # 默认值,一般取立体校正后的重投影矩阵Q中的 Q[2,3]
# 基线距离
self.baseline = 423.716923177417 # 单位:mm, 为平移向量的第一个参数(取绝对值)
| 41.394737
| 147
| 0.546726
|
acfee45ee17163a01bbcd9311175f74a0c8e4c93
| 96
|
py
|
Python
|
app_kitchen/apps.py
|
CBaut/kitchen
|
1efb0fb5c1e32ea704ce5678cb781b1e41e73441
|
[
"MIT"
] | null | null | null |
app_kitchen/apps.py
|
CBaut/kitchen
|
1efb0fb5c1e32ea704ce5678cb781b1e41e73441
|
[
"MIT"
] | 10
|
2020-01-09T02:34:04.000Z
|
2020-02-28T00:02:26.000Z
|
app_kitchen/apps.py
|
CBaut/kitchen
|
1efb0fb5c1e32ea704ce5678cb781b1e41e73441
|
[
"MIT"
] | 1
|
2020-06-23T17:33:24.000Z
|
2020-06-23T17:33:24.000Z
|
from django.apps import AppConfig
class AppKitchenConfig(AppConfig):
name = 'app_kitchen'
| 16
| 34
| 0.770833
|
acfee5801fdb2d45cc863f6ca55c7f9ca953f100
| 8,657
|
py
|
Python
|
protocall/interpreter/parser_converter.py
|
google/protocall
|
0b02cdaa696c883ce3ececb41341e6648d325fec
|
[
"Apache-2.0"
] | 16
|
2016-07-17T14:47:03.000Z
|
2021-10-12T03:35:44.000Z
|
protocall/interpreter/parser_converter.py
|
google/protocall
|
0b02cdaa696c883ce3ececb41341e6648d325fec
|
[
"Apache-2.0"
] | null | null | null |
protocall/interpreter/parser_converter.py
|
google/protocall
|
0b02cdaa696c883ce3ececb41341e6648d325fec
|
[
"Apache-2.0"
] | 11
|
2016-09-17T14:32:21.000Z
|
2021-10-12T03:35:39.000Z
|
# Copyright 2016 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pyparsing import ParseResults
from protocall.proto import protocall_pb2
from grammar import expression, statement, assignment, call, return_, block, scope, define, while_expression, while_scope, if_expression, if_scope, elif_expression, elif_scope, elif_scopes, else_scope, conditional
from AST import Call, Assignment, ArrayAssignment, Integer, String, Boolean, Proto, Array, Identifier, Field, ArrayRef, While, ArithmeticOperator, ComparisonOperator, Conditional, Return, Define
def convert_field(field):
f = protocall_pb2.Field()
for component in field.components:
c = f.component.add()
c.name = component.identifier
return f
def convert_statement(statement):
s = protocall_pb2.Statement()
if isinstance(statement.statement, Call):
call = statement.statement
field, args = call.field, call.args
c = protocall_pb2.Call()
c.field.CopyFrom(convert_field(field))
for arg in args:
a = c.argument.add()
a.identifier.name = arg.identifier.identifier
a.expression.CopyFrom(convert_expression(arg.expression.expression))
s.call.CopyFrom(c)
elif isinstance(statement.statement, Assignment):
assignment = statement.statement
field, expression = assignment.field, assignment.expression
a = protocall_pb2.Assignment()
a.field.CopyFrom(convert_field(field))
a.expression.CopyFrom(convert_expression(expression.expression))
s.assignment.CopyFrom(a)
elif isinstance(statement.statement, ArrayAssignment):
array_assignment = statement.statement
array_ref, expression = array_assignment.array_ref, array_assignment.expression
a = protocall_pb2.ArrayAssignment()
a.array_ref.field.CopyFrom(convert_field(array_ref.field))
a.array_ref.index.value = array_ref.index
a.expression.CopyFrom(convert_expression(expression.expression))
s.array_assignment.CopyFrom(a)
elif isinstance(statement.statement, While):
while_expression = statement.statement
expression, scope = while_expression.expression, while_expression.scope
w = protocall_pb2.While()
w.expression_scope.expression.CopyFrom(convert_expression(expression.expression))
w.expression_scope.scope.CopyFrom(convert_scope(scope.scope))
s.while_.CopyFrom(w)
elif isinstance(statement.statement, Conditional):
conditional = statement.statement
if_scope = conditional.if_scope
elif_scopes = conditional.elif_scopes
c = protocall_pb2.Conditional()
c.if_scope.expression.CopyFrom(convert_expression(if_scope.expression.expression))
c.if_scope.scope.CopyFrom(convert_scope(if_scope.scope.scope))
for elif_scope in elif_scopes:
es = c.elif_scope.add()
es.expression.CopyFrom(convert_expression(elif_scope.expression.expression))
es.scope.CopyFrom(convert_scope(elif_scope.scope.scope))
else_scope = conditional.else_scope
if else_scope:
c.else_scope.CopyFrom(convert_scope(else_scope.scope.scope))
s.conditional.CopyFrom(c)
elif isinstance(statement.statement, Return):
return_ = statement.statement
expression = return_.expression
r = protocall_pb2.Return()
r.expression.CopyFrom(convert_expression(expression.expression))
s.return_.CopyFrom(r)
elif isinstance(statement.statement, Define):
define = statement.statement
field = define.field
scope = define.scope
d = protocall_pb2.Define()
d.field.CopyFrom(convert_field(field))
d.scope.CopyFrom(convert_scope(scope.scope))
s.define.CopyFrom(d)
else:
print statement.statement
raise RuntimeError
return s
def convert_block(block):
bl = protocall_pb2.Block()
for statement in block.block:
s = convert_statement(statement)
bl.statement.add().CopyFrom(s)
return bl
def convert_argument(argument):
ar = protocall_pb2.Argument()
ar.identifier.name = argument.identifier.identifier
e = convert_expression(argument.expression.expression)
ar.expression.CopyFrom(e)
return ar
def convert_scope(scope):
s_pb = protocall_pb2.Scope()
block = scope.block
for statement in block:
s_pb.block.statement.add().CopyFrom(convert_statement(statement))
return s_pb
def convert_arithmetic_operator(arithmetic_operator, e):
if arithmetic_operator.operator == '*':
op = protocall_pb2.ArithmeticOperator.Op.Value("MULTIPLY")
elif arithmetic_operator.operator == '/':
op = protocall_pb2.ArithmeticOperator.Op.Value("DIVIDE")
elif arithmetic_operator.operator == '+':
op = protocall_pb2.ArithmeticOperator.Op.Value("PLUS")
elif arithmetic_operator.operator == '-':
op = protocall_pb2.ArithmeticOperator.Op.Value("MINUS")
else:
print arithmetic_operator.operator
raise RuntimeError
e.arithmetic_operator.operator = op
left = convert_expression(arithmetic_operator.left)
if isinstance(left, protocall_pb2.Expression):
e.arithmetic_operator.left.CopyFrom(left)
elif isinstance(left, protocall_pb2.Identifier):
e.atom.identifier.CopyFrom(left)
else:
raise RuntimeError
e.arithmetic_operator.left.CopyFrom(left)
right = convert_expression(arithmetic_operator.right)
if isinstance(right, protocall_pb2.Expression):
e.arithmetic_operator.right.CopyFrom(right)
elif isinstance(right, protocall_pb2.Identifier):
e.atom.identifier.CopyFrom(right)
else:
raise RuntimeError
e.arithmetic_operator.right.CopyFrom(right)
def convert_comparison_operator(comparison_operator, e):
if comparison_operator.operator == '>':
op = protocall_pb2.ComparisonOperator.Op.Value("GREATER_THAN")
elif comparison_operator.operator == '<':
op = protocall_pb2.ComparisonOperator.Op.Value("LESS_THAN")
elif comparison_operator.operator == '==':
op = protocall_pb2.ComparisonOperator.Op.Value("EQUALS")
else:
print comparison_operator.operator
raise RuntimeError
e.comparison_operator.operator = op
left = convert_expression(comparison_operator.left)
if isinstance(left, protocall_pb2.Expression):
e.comparison_operator.left.CopyFrom(left)
elif isinstance(left, protocall_pb2.Identifier):
e.atom.identifier.CopyFrom(left)
else:
raise RuntimeError
e.comparison_operator.left.CopyFrom(left)
right = convert_expression(comparison_operator.right)
if isinstance(right, protocall_pb2.Expression):
e.comparison_operator.right.CopyFrom(right)
elif isinstance(right, protocall_pb2.Identifier):
e.atom.identifier.CopyFrom(right)
else:
raise RuntimeError
e.comparison_operator.right.CopyFrom(right)
def convert_expression(expression):
e = protocall_pb2.Expression()
if isinstance(expression, Integer):
e.atom.literal.integer.value = expression.value
elif isinstance(expression, String):
e.atom.literal.string.value = expression.value
elif isinstance(expression, Boolean):
e.atom.literal.boolean.value = expression.value
elif isinstance(expression, Proto):
e.atom.literal.proto.field.CopyFrom(convert_expression(expression.field).atom.field)
e.atom.literal.proto.value = str(expression.proto)
elif isinstance(expression, Field):
e.atom.field.CopyFrom(convert_field(expression))
elif isinstance(expression, Array):
array = e.atom.literal.array
for item in expression.elements:
element = array.element.add()
element.CopyFrom(convert_expression(item.expression))
elif isinstance(expression, ArrayRef):
e.atom.array_ref.field.CopyFrom(convert_field(expression.field))
e.atom.array_ref.index.value = expression.index
elif isinstance(expression, ArithmeticOperator):
convert_arithmetic_operator(expression, e)
elif isinstance(expression, ComparisonOperator):
convert_comparison_operator(expression, e)
elif isinstance(expression, Call):
e.call.field.CopyFrom(convert_field(expression.field))
for arg in expression.args:
a = e.call.argument.add()
a.CopyFrom(convert_argument(arg))
else:
print expression.__class__
raise RuntimeError
return e
| 40.834906
| 213
| 0.753148
|
acfee5f389dbe8a9df1885000c7fc6bac770a59b
| 1,260
|
py
|
Python
|
chpt6/chessboard.py
|
GDG-Buea/learn-python
|
9dfe8caa4b57489cf4249bf7e64856062a0b93c2
|
[
"Apache-2.0"
] | null | null | null |
chpt6/chessboard.py
|
GDG-Buea/learn-python
|
9dfe8caa4b57489cf4249bf7e64856062a0b93c2
|
[
"Apache-2.0"
] | 2
|
2018-05-21T09:39:00.000Z
|
2018-05-27T15:59:15.000Z
|
chpt6/chessboard.py
|
GDG-Buea/learn-python
|
9dfe8caa4b57489cf4249bf7e64856062a0b93c2
|
[
"Apache-2.0"
] | 2
|
2018-05-19T14:59:56.000Z
|
2018-05-19T15:25:48.000Z
|
# This program displays two chessboards side by side
# # Draw one chessboard whose upper-left corner is at
# # (startx, starty) and bottom-right corner is at (endx, endy)
# def drawChessboard(startx, endx, starty, endy):
import turtle
def draw_chessboard(x, y):
# Draw chess board borders
turtle.speed(50)
turtle.pensize(3)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.color("green")
for i in range(4):
turtle.forward(240)
turtle.left(90)
# Draw chess board inside
turtle.color("black")
for j in range(-120, 90, 60):
for i in range(-120, 120, 60):
turtle.penup()
turtle.goto(i, j)
turtle.pendown()
# Draw a small rectangle
turtle.begin_fill()
for k in range(4):
turtle.forward(30)
turtle.left(90)
for j in range(-90, 120, 60):
for i in range(-90, 120, 60):
turtle.penup()
turtle.goto(i, j)
turtle.pendown()
# Draw a small rectangle
turtle.begin_fill()
for k in range(4):
turtle.forward(30)
turtle.left(90)
turtle.end_fill()
draw_chessboard(-120, -120)
| 24.230769
| 63
| 0.556349
|
acfee6620e5db44d158757e1a512e70f89e62c55
| 29,236
|
py
|
Python
|
plugins/modules/oci_compute_image.py
|
slmjy/oci-ansible-collection
|
349c91e2868bf4706a6e3d6fb3b47fc622bfe11b
|
[
"Apache-2.0"
] | 108
|
2020-05-19T20:46:10.000Z
|
2022-03-25T14:10:01.000Z
|
plugins/modules/oci_compute_image.py
|
slmjy/oci-ansible-collection
|
349c91e2868bf4706a6e3d6fb3b47fc622bfe11b
|
[
"Apache-2.0"
] | 90
|
2020-06-14T22:07:11.000Z
|
2022-03-07T05:40:29.000Z
|
plugins/modules/oci_compute_image.py
|
slmjy/oci-ansible-collection
|
349c91e2868bf4706a6e3d6fb3b47fc622bfe11b
|
[
"Apache-2.0"
] | 42
|
2020-08-30T23:09:12.000Z
|
2022-03-25T16:58:01.000Z
|
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for details.
# GENERATED FILE - DO NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: oci_compute_image
short_description: Manage an Image resource in Oracle Cloud Infrastructure
description:
- This module allows the user to create, update and delete an Image resource in Oracle Cloud Infrastructure
- For I(state=present), creates a boot disk image for the specified instance or imports an exported image from the Oracle Cloud Infrastructure Object
Storage service.
- When creating a new image, you must provide the OCID of the instance you want to use as the basis for the image, and
the OCID of the compartment containing that instance. For more information about images,
see L(Managing Custom Images,https://docs.cloud.oracle.com/iaas/Content/Compute/Tasks/managingcustomimages.htm).
- When importing an exported image from Object Storage, you specify the source information
in L(ImageSourceDetails,https://docs.cloud.oracle.com/en-us/iaas/api/#/en/iaas/latest/requests/ImageSourceDetails).
- When importing an image based on the namespace, bucket name, and object name,
use L(ImageSourceViaObjectStorageTupleDetails,https://docs.cloud.oracle.com/en-
us/iaas/api/#/en/iaas/latest/requests/ImageSourceViaObjectStorageTupleDetails).
- When importing an image based on the Object Storage URL, use
L(ImageSourceViaObjectStorageUriDetails,https://docs.cloud.oracle.com/en-us/iaas/api/#/en/iaas/latest/requests/ImageSourceViaObjectStorageUriDetails).
See L(Object Storage URLs,https://docs.cloud.oracle.com/iaas/Content/Compute/Tasks/imageimportexport.htm#URLs) and L(Using Pre-Authenticated
Requests,https://docs.cloud.oracle.com/iaas/Content/Object/Tasks/usingpreauthenticatedrequests.htm)
for constructing URLs for image import/export.
- For more information about importing exported images, see
L(Image Import/Export,https://docs.cloud.oracle.com/iaas/Content/Compute/Tasks/imageimportexport.htm).
- "You may optionally specify a *display name* for the image, which is simply a friendly name or description.
It does not have to be unique, and you can change it. See L(UpdateImage,https://docs.cloud.oracle.com/en-us/iaas/api/#/en/iaas/latest/Image/UpdateImage).
Avoid entering confidential information."
- "This resource has the following action operations in the M(oracle.oci.oci_compute_image_actions) module: change_compartment, export."
version_added: "2.9.0"
author: Oracle (@oracle)
options:
compartment_id:
description:
- The OCID of the compartment you want the image to be created in.
- Required for create using I(state=present).
- Required for update when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is set.
- Required for delete when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is set.
type: str
defined_tags:
description:
- Defined tags for this resource. Each key is predefined and scoped to a
namespace. For more information, see L(Resource Tags,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
- "Example: `{\\"Operations\\": {\\"CostCenter\\": \\"42\\"}}`"
- This parameter is updatable.
type: dict
display_name:
description:
- A user-friendly name for the image. It does not have to be unique, and it's changeable.
Avoid entering confidential information.
- You cannot use a platform image name as a custom image name.
- "Example: `My Oracle Linux image`"
- Required for create, update, delete when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is set.
- This parameter is updatable when C(OCI_USE_NAME_AS_IDENTIFIER) is not set.
type: str
aliases: ["name"]
freeform_tags:
description:
- Free-form tags for this resource. Each tag is a simple key-value pair with no
predefined name, type, or namespace. For more information, see L(Resource
Tags,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
- "Example: `{\\"Department\\": \\"Finance\\"}`"
- This parameter is updatable.
type: dict
image_source_details:
description:
- ""
type: dict
suboptions:
operating_system:
description:
- ""
type: str
operating_system_version:
description:
- ""
type: str
source_image_type:
description:
- The format of the image to be imported. Only monolithic
images are supported. This attribute is not used for exported Oracle images with the OCI image format.
type: str
choices:
- "QCOW2"
- "VMDK"
source_type:
description:
- The source type for the image. Use `objectStorageTuple` when specifying the namespace,
bucket name, and object name. Use `objectStorageUri` when specifying the Object Storage URL.
type: str
choices:
- "objectStorageTuple"
- "objectStorageUri"
required: true
bucket_name:
description:
- The Object Storage bucket for the image.
- Required when source_type is 'objectStorageTuple'
type: str
namespace_name:
description:
- The Object Storage namespace for the image.
- Required when source_type is 'objectStorageTuple'
type: str
object_name:
description:
- The Object Storage name for the image.
- Required when source_type is 'objectStorageTuple'
type: str
source_uri:
description:
- The Object Storage URL for the image.
- Required when source_type is 'objectStorageUri'
type: str
instance_id:
description:
- The OCID of the instance you want to use as the basis for the image.
type: str
launch_mode:
description:
- "Specifies the configuration mode for launching virtual machine (VM) instances. The configuration modes are:
* `NATIVE` - VM instances launch with paravirtualized boot and VFIO devices. The default value for platform images.
* `EMULATED` - VM instances launch with emulated devices, such as the E1000 network driver and emulated SCSI disk controller.
* `PARAVIRTUALIZED` - VM instances launch with paravirtualized devices using VirtIO drivers.
* `CUSTOM` - VM instances launch with custom configuration settings specified in the `LaunchOptions` parameter."
type: str
choices:
- "NATIVE"
- "EMULATED"
- "PARAVIRTUALIZED"
- "CUSTOM"
image_id:
description:
- The L(OCID,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the image.
- Required for update using I(state=present) when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is not set.
- Required for delete using I(state=absent) when environment variable C(OCI_USE_NAME_AS_IDENTIFIER) is not set.
type: str
aliases: ["id"]
operating_system:
description:
- Operating system
- "Example: `Oracle Linux`"
- This parameter is updatable.
type: str
operating_system_version:
description:
- Operating system version
- "Example: `7.4`"
- This parameter is updatable.
type: str
state:
description:
- The state of the Image.
- Use I(state=present) to create or update an Image.
- Use I(state=absent) to delete an Image.
type: str
required: false
default: 'present'
choices: ["present", "absent"]
extends_documentation_fragment: [ oracle.oci.oracle, oracle.oci.oracle_creatable_resource, oracle.oci.oracle_wait_options ]
"""
EXAMPLES = """
- name: Create image
oci_compute_image:
# required
compartment_id: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx"
# optional
defined_tags: {'Operations': {'CostCenter': 'US'}}
display_name: display_name_example
freeform_tags: {'Department': 'Finance'}
image_source_details:
# required
source_type: objectStorageTuple
bucket_name: bucket_name_example
namespace_name: namespace_name_example
object_name: object_name_example
# optional
operating_system: operating_system_example
operating_system_version: operating_system_version_example
source_image_type: QCOW2
instance_id: "ocid1.instance.oc1..xxxxxxEXAMPLExxxxxx"
launch_mode: NATIVE
- name: Update image
oci_compute_image:
# required
image_id: "ocid1.image.oc1..xxxxxxEXAMPLExxxxxx"
# optional
defined_tags: {'Operations': {'CostCenter': 'US'}}
display_name: display_name_example
freeform_tags: {'Department': 'Finance'}
operating_system: operating_system_example
operating_system_version: operating_system_version_example
- name: Update image using name (when environment variable OCI_USE_NAME_AS_IDENTIFIER is set)
oci_compute_image:
# required
compartment_id: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx"
display_name: display_name_example
# optional
defined_tags: {'Operations': {'CostCenter': 'US'}}
freeform_tags: {'Department': 'Finance'}
operating_system: operating_system_example
operating_system_version: operating_system_version_example
- name: Delete image
oci_compute_image:
# required
image_id: "ocid1.image.oc1..xxxxxxEXAMPLExxxxxx"
state: absent
- name: Delete image using name (when environment variable OCI_USE_NAME_AS_IDENTIFIER is set)
oci_compute_image:
# required
compartment_id: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx"
display_name: display_name_example
state: absent
"""
RETURN = """
image:
description:
- Details of the Image resource acted upon by the current operation
returned: on success
type: complex
contains:
base_image_id:
description:
- The OCID of the image originally used to launch the instance.
returned: on success
type: str
sample: "ocid1.baseimage.oc1..xxxxxxEXAMPLExxxxxx"
compartment_id:
description:
- The OCID of the compartment containing the instance you want to use as the basis for the image.
returned: on success
type: str
sample: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx"
create_image_allowed:
description:
- Whether instances launched with this image can be used to create new images.
For example, you cannot create an image of an Oracle Database instance.
- "Example: `true`"
returned: on success
type: bool
sample: true
defined_tags:
description:
- Defined tags for this resource. Each key is predefined and scoped to a
namespace. For more information, see L(Resource Tags,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
- "Example: `{\\"Operations\\": {\\"CostCenter\\": \\"42\\"}}`"
returned: on success
type: dict
sample: {'Operations': {'CostCenter': 'US'}}
display_name:
description:
- A user-friendly name for the image. It does not have to be unique, and it's changeable.
Avoid entering confidential information.
- You cannot use a platform image name as a custom image name.
- "Example: `My custom Oracle Linux image`"
returned: on success
type: str
sample: display_name_example
freeform_tags:
description:
- Free-form tags for this resource. Each tag is a simple key-value pair with no
predefined name, type, or namespace. For more information, see L(Resource
Tags,https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
- "Example: `{\\"Department\\": \\"Finance\\"}`"
returned: on success
type: dict
sample: {'Department': 'Finance'}
id:
description:
- The OCID of the image.
returned: on success
type: str
sample: "ocid1.resource.oc1..xxxxxxEXAMPLExxxxxx"
launch_mode:
description:
- "Specifies the configuration mode for launching virtual machine (VM) instances. The configuration modes are:
* `NATIVE` - VM instances launch with iSCSI boot and VFIO devices. The default value for platform images.
* `EMULATED` - VM instances launch with emulated devices, such as the E1000 network driver and emulated SCSI disk controller.
* `PARAVIRTUALIZED` - VM instances launch with paravirtualized devices using VirtIO drivers.
* `CUSTOM` - VM instances launch with custom configuration settings specified in the `LaunchOptions` parameter."
returned: on success
type: str
sample: NATIVE
launch_options:
description:
- ""
returned: on success
type: complex
contains:
boot_volume_type:
description:
- "Emulation type for the boot volume.
* `ISCSI` - ISCSI attached block storage device.
* `SCSI` - Emulated SCSI disk.
* `IDE` - Emulated IDE disk.
* `VFIO` - Direct attached Virtual Function storage. This is the default option for local data
volumes on platform images.
* `PARAVIRTUALIZED` - Paravirtualized disk. This is the default for boot volumes and remote block
storage volumes on platform images."
returned: on success
type: str
sample: ISCSI
firmware:
description:
- "Firmware used to boot VM. Select the option that matches your operating system.
* `BIOS` - Boot VM using BIOS style firmware. This is compatible with both 32 bit and 64 bit operating
systems that boot using MBR style bootloaders.
* `UEFI_64` - Boot VM using UEFI style firmware compatible with 64 bit operating systems. This is the
default for platform images."
returned: on success
type: str
sample: BIOS
network_type:
description:
- "Emulation type for the physical network interface card (NIC).
* `E1000` - Emulated Gigabit ethernet controller. Compatible with Linux e1000 network driver.
* `VFIO` - Direct attached Virtual Function network controller. This is the networking type
when you launch an instance using hardware-assisted (SR-IOV) networking.
* `PARAVIRTUALIZED` - VM instances launch with paravirtualized devices using VirtIO drivers."
returned: on success
type: str
sample: E1000
remote_data_volume_type:
description:
- "Emulation type for volume.
* `ISCSI` - ISCSI attached block storage device.
* `SCSI` - Emulated SCSI disk.
* `IDE` - Emulated IDE disk.
* `VFIO` - Direct attached Virtual Function storage. This is the default option for local data
volumes on platform images.
* `PARAVIRTUALIZED` - Paravirtualized disk. This is the default for boot volumes and remote block
storage volumes on platform images."
returned: on success
type: str
sample: ISCSI
is_pv_encryption_in_transit_enabled:
description:
- Deprecated. Instead use `isPvEncryptionInTransitEnabled` in
L(LaunchInstanceDetails,https://docs.cloud.oracle.com/en-us/iaas/api/#/en/iaas/latest/datatypes/LaunchInstanceDetails).
returned: on success
type: bool
sample: true
is_consistent_volume_naming_enabled:
description:
- Whether to enable consistent volume naming feature. Defaults to false.
returned: on success
type: bool
sample: true
lifecycle_state:
description:
- ""
returned: on success
type: str
sample: PROVISIONING
operating_system:
description:
- The image's operating system.
- "Example: `Oracle Linux`"
returned: on success
type: str
sample: operating_system_example
operating_system_version:
description:
- The image's operating system version.
- "Example: `7.2`"
returned: on success
type: str
sample: operating_system_version_example
agent_features:
description:
- ""
returned: on success
type: complex
contains:
is_monitoring_supported:
description:
- This attribute is not used.
returned: on success
type: bool
sample: true
is_management_supported:
description:
- This attribute is not used.
returned: on success
type: bool
sample: true
listing_type:
description:
- "The listing type of the image. The default value is \\"NONE\\"."
returned: on success
type: str
sample: COMMUNITY
size_in_mbs:
description:
- The boot volume size for an instance launched from this image (1 MB = 1,048,576 bytes).
Note this is not the same as the size of the image when it was exported or the actual size of the image.
- "Example: `47694`"
returned: on success
type: int
sample: 56
billable_size_in_gbs:
description:
- The size of the internal storage for this image that is subject to billing (1 GB = 1,073,741,824 bytes).
- "Example: `100`"
returned: on success
type: int
sample: 56
time_created:
description:
- The date and time the image was created, in the format defined by L(RFC3339,https://tools.ietf.org/html/rfc3339).
- "Example: `2016-08-25T21:10:29.600Z`"
returned: on success
type: str
sample: "2013-10-20T19:20:30+01:00"
sample: {
"base_image_id": "ocid1.baseimage.oc1..xxxxxxEXAMPLExxxxxx",
"compartment_id": "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx",
"create_image_allowed": true,
"defined_tags": {'Operations': {'CostCenter': 'US'}},
"display_name": "display_name_example",
"freeform_tags": {'Department': 'Finance'},
"id": "ocid1.resource.oc1..xxxxxxEXAMPLExxxxxx",
"launch_mode": "NATIVE",
"launch_options": {
"boot_volume_type": "ISCSI",
"firmware": "BIOS",
"network_type": "E1000",
"remote_data_volume_type": "ISCSI",
"is_pv_encryption_in_transit_enabled": true,
"is_consistent_volume_naming_enabled": true
},
"lifecycle_state": "PROVISIONING",
"operating_system": "operating_system_example",
"operating_system_version": "operating_system_version_example",
"agent_features": {
"is_monitoring_supported": true,
"is_management_supported": true
},
"listing_type": "COMMUNITY",
"size_in_mbs": 56,
"billable_size_in_gbs": 56,
"time_created": "2013-10-20T19:20:30+01:00"
}
"""
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.oracle.oci.plugins.module_utils import (
oci_common_utils,
oci_wait_utils,
)
from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import (
OCIResourceHelperBase,
get_custom_class,
)
try:
from oci.work_requests import WorkRequestClient
from oci.core import ComputeClient
from oci.core.models import CreateImageDetails
from oci.core.models import UpdateImageDetails
HAS_OCI_PY_SDK = True
except ImportError:
HAS_OCI_PY_SDK = False
class ImageHelperGen(OCIResourceHelperBase):
"""Supported operations: create, update, get, list and delete"""
def __init__(self, *args, **kwargs):
super(ImageHelperGen, self).__init__(*args, **kwargs)
self.work_request_client = WorkRequestClient(
self.client._config, **self.client._kwargs
)
def get_module_resource_id_param(self):
return "image_id"
def get_module_resource_id(self):
return self.module.params.get("image_id")
def get_get_fn(self):
return self.client.get_image
def get_resource(self):
return oci_common_utils.call_with_backoff(
self.client.get_image, image_id=self.module.params.get("image_id"),
)
def get_required_kwargs_for_list(self):
required_list_method_params = [
"compartment_id",
]
return dict(
(param, self.module.params[param]) for param in required_list_method_params
)
def get_optional_kwargs_for_list(self):
optional_list_method_params = (
["display_name"]
if self._use_name_as_identifier()
else ["display_name", "operating_system", "operating_system_version"]
)
return dict(
(param, self.module.params[param])
for param in optional_list_method_params
if self.module.params.get(param) is not None
and (
self._use_name_as_identifier()
or (
not self.module.params.get("key_by")
or param in self.module.params.get("key_by")
)
)
)
def list_resources(self):
required_kwargs = self.get_required_kwargs_for_list()
optional_kwargs = self.get_optional_kwargs_for_list()
kwargs = oci_common_utils.merge_dicts(required_kwargs, optional_kwargs)
return oci_common_utils.list_all_resources(self.client.list_images, **kwargs)
def get_create_model_class(self):
return CreateImageDetails
def get_exclude_attributes(self):
return ["image_source_details", "instance_id"]
def create_resource(self):
create_details = self.get_create_model()
return oci_wait_utils.call_and_wait(
call_fn=self.client.create_image,
call_fn_args=(),
call_fn_kwargs=dict(create_image_details=create_details,),
waiter_type=oci_wait_utils.WORK_REQUEST_WAITER_KEY,
operation=oci_common_utils.CREATE_OPERATION_KEY,
waiter_client=self.work_request_client,
resource_helper=self,
wait_for_states=oci_common_utils.get_work_request_completed_states(),
)
def get_update_model_class(self):
return UpdateImageDetails
def update_resource(self):
update_details = self.get_update_model()
return oci_wait_utils.call_and_wait(
call_fn=self.client.update_image,
call_fn_args=(),
call_fn_kwargs=dict(
image_id=self.module.params.get("image_id"),
update_image_details=update_details,
),
waiter_type=oci_wait_utils.LIFECYCLE_STATE_WAITER_KEY,
operation=oci_common_utils.UPDATE_OPERATION_KEY,
waiter_client=self.get_waiter_client(),
resource_helper=self,
wait_for_states=self.get_wait_for_states_for_operation(
oci_common_utils.UPDATE_OPERATION_KEY,
),
)
def delete_resource(self):
return oci_wait_utils.call_and_wait(
call_fn=self.client.delete_image,
call_fn_args=(),
call_fn_kwargs=dict(image_id=self.module.params.get("image_id"),),
waiter_type=oci_wait_utils.LIFECYCLE_STATE_WAITER_KEY,
operation=oci_common_utils.DELETE_OPERATION_KEY,
waiter_client=self.get_waiter_client(),
resource_helper=self,
wait_for_states=self.get_wait_for_states_for_operation(
oci_common_utils.DELETE_OPERATION_KEY,
),
)
ImageHelperCustom = get_custom_class("ImageHelperCustom")
class ResourceHelper(ImageHelperCustom, ImageHelperGen):
pass
def main():
module_args = oci_common_utils.get_common_arg_spec(
supports_create=True, supports_wait=True
)
module_args.update(
dict(
compartment_id=dict(type="str"),
defined_tags=dict(type="dict"),
display_name=dict(aliases=["name"], type="str"),
freeform_tags=dict(type="dict"),
image_source_details=dict(
type="dict",
options=dict(
operating_system=dict(type="str"),
operating_system_version=dict(type="str"),
source_image_type=dict(type="str", choices=["QCOW2", "VMDK"]),
source_type=dict(
type="str",
required=True,
choices=["objectStorageTuple", "objectStorageUri"],
),
bucket_name=dict(type="str"),
namespace_name=dict(type="str"),
object_name=dict(type="str"),
source_uri=dict(type="str"),
),
),
instance_id=dict(type="str"),
launch_mode=dict(
type="str", choices=["NATIVE", "EMULATED", "PARAVIRTUALIZED", "CUSTOM"]
),
image_id=dict(aliases=["id"], type="str"),
operating_system=dict(type="str"),
operating_system_version=dict(type="str"),
state=dict(type="str", default="present", choices=["present", "absent"]),
)
)
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
if not HAS_OCI_PY_SDK:
module.fail_json(msg="oci python sdk required for this module.")
resource_helper = ResourceHelper(
module=module,
resource_type="image",
service_client_class=ComputeClient,
namespace="core",
)
result = dict(changed=False)
if resource_helper.is_delete_using_name():
result = resource_helper.delete_using_name()
elif resource_helper.is_delete():
result = resource_helper.delete()
elif resource_helper.is_update_using_name():
result = resource_helper.update_using_name()
elif resource_helper.is_update():
result = resource_helper.update()
elif resource_helper.is_create():
result = resource_helper.create()
module.exit_json(**result)
if __name__ == "__main__":
main()
| 42.74269
| 159
| 0.606513
|
acfee7f71274fd5cc93bd63bf09f0d892f9fafff
| 680
|
py
|
Python
|
blumycelium/the_exceptions.py
|
bluwr-tech/blumycelium
|
8f6b24b42244869682d3bd2e5b31428a48c98872
|
[
"Apache-2.0"
] | 2
|
2022-03-15T10:36:22.000Z
|
2022-03-23T10:36:35.000Z
|
blumycelium/the_exceptions.py
|
bluwr-tech/blumycelium
|
8f6b24b42244869682d3bd2e5b31428a48c98872
|
[
"Apache-2.0"
] | null | null | null |
blumycelium/the_exceptions.py
|
bluwr-tech/blumycelium
|
8f6b24b42244869682d3bd2e5b31428a48c98872
|
[
"Apache-2.0"
] | null | null | null |
class EmptyParameter(Exception):
"""Represents an empty parameter"""
pass
class EmptyAnnotationError(Exception):
""""""
pass
class PlaceHolerKeyError(Exception):
""""""
pass
class RedundantParameterError(Exception):
""""""
pass
class ParameterTypeError(Exception):
""""""
pass
class DatabaseNotFoundError(Exception):
""""""
pass
class ResultTypeError(Exception):
""""""
pass
class ValueDerivationError(Exception):
""""""
pass
class MultipleDerivationError(Exception):
""""""
pass
class DependencyTypeError(Exception):
""""""
pass
class ResultNotFound(Exception):
""""""
pass
| 13.333333
| 41
| 0.630882
|
acfee8304d9809c3dc701bec067c7c1f889882ec
| 499
|
py
|
Python
|
data/scripts/templates/object/tangible/ship/crafted/booster/shared_base_booster_subcomponent_mk3.py
|
obi-two/GameServer
|
7d37024e2291a97d49522610cd8f1dbe5666afc2
|
[
"MIT"
] | 20
|
2015-02-23T15:11:56.000Z
|
2022-03-18T20:56:48.000Z
|
data/scripts/templates/object/tangible/ship/crafted/booster/shared_base_booster_subcomponent_mk3.py
|
apathyboy/swganh
|
665128efe9154611dec4cb5efc61d246dd095984
|
[
"MIT"
] | null | null | null |
data/scripts/templates/object/tangible/ship/crafted/booster/shared_base_booster_subcomponent_mk3.py
|
apathyboy/swganh
|
665128efe9154611dec4cb5efc61d246dd095984
|
[
"MIT"
] | 20
|
2015-04-04T16:35:59.000Z
|
2022-03-24T14:54:37.000Z
|
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/booster/shared_base_booster_subcomponent_mk3.iff"
result.attribute_template_id = 8
result.stfName("space_crafting_n","base_booster_subcomponent_mk3")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result
| 29.352941
| 98
| 0.753507
|
acfeea519e7fca9b20bc10ea3184d0733d65386c
| 66,995
|
py
|
Python
|
scripts/dpdk_setup_ports.py
|
mcallaghan-sandvine/trex-core
|
55fc1ed6d2e3d066e7895321eae233bb0339b722
|
[
"Apache-2.0"
] | null | null | null |
scripts/dpdk_setup_ports.py
|
mcallaghan-sandvine/trex-core
|
55fc1ed6d2e3d066e7895321eae233bb0339b722
|
[
"Apache-2.0"
] | 3
|
2018-04-25T20:28:49.000Z
|
2018-07-16T13:45:40.000Z
|
scripts/dpdk_setup_ports.py
|
mcallaghan-sandvine/trex-core
|
55fc1ed6d2e3d066e7895321eae233bb0339b722
|
[
"Apache-2.0"
] | null | null | null |
#! /bin/bash
"source" "find_python.sh" "--local"
"exec" "$PYTHON" "$0" "$@"
# hhaim
import sys
import os
python_ver = 'python%s' % sys.version_info[0]
yaml_path = os.path.join('external_libs', 'pyyaml-3.11', python_ver)
if yaml_path not in sys.path:
sys.path.append(yaml_path)
import yaml
import dpdk_nic_bind
import re
import argparse
import copy
import shlex
import traceback
from collections import defaultdict, OrderedDict
from distutils.util import strtobool
import subprocess
import platform
import stat
import time
# exit code is Important should be
# -1 : don't continue
# 0 : no errors - no need to load mlx share object
# 32 : no errors - mlx share object should be loaded
# 64 : no errors - napatech 3GD should be running
MLX_EXIT_CODE = 32
NTACC_EXIT_CODE = 64
class VFIOBindErr(Exception): pass
PATH_ARR = os.getenv('PATH', '').split(':')
for path in ['/usr/local/sbin', '/usr/sbin', '/sbin']:
if path not in PATH_ARR:
PATH_ARR.append(path)
os.environ['PATH'] = ':'.join(PATH_ARR)
def if_list_remove_sub_if(if_list):
return if_list
class ConfigCreator(object):
mandatory_interface_fields = ['Slot_str', 'Device_str', 'NUMA']
_2hex_re = '[\da-fA-F]{2}'
mac_re = re.compile('^({0}:){{5}}{0}$'.format(_2hex_re))
MAC_LCORE_NUM = 63 # current bitmask is 64 bit
# cpu_topology - dict: physical processor -> physical core -> logical processing unit (thread)
# interfaces - array of dicts per interface, should include "mandatory_interface_fields" values
def __init__(self, cpu_topology, interfaces, include_lcores = [], exclude_lcores = [], only_first_thread = False, zmq_rpc_port = None, zmq_pub_port = None, prefix = None, ignore_numa = False):
self.cpu_topology = copy.deepcopy(cpu_topology)
self.interfaces = copy.deepcopy(interfaces)
del cpu_topology
del interfaces
assert isinstance(self.cpu_topology, dict), 'Type of cpu_topology should be dict, got: %s' % type(self.cpu_topology)
assert len(self.cpu_topology.keys()) > 0, 'cpu_topology should contain at least one processor'
assert isinstance(self.interfaces, list), 'Type of interfaces should be list, got: %s' % type(list)
assert len(self.interfaces) % 2 == 0, 'Should be even number of interfaces, got: %s' % len(self.interfaces)
assert len(self.interfaces) >= 2, 'Should be at least two interfaces, got: %s' % len(self.interfaces)
assert isinstance(include_lcores, list), 'include_lcores should be list, got: %s' % type(include_lcores)
assert isinstance(exclude_lcores, list), 'exclude_lcores should be list, got: %s' % type(exclude_lcores)
assert len(self.interfaces) >= 2, 'Should be at least two interfaces, got: %s' % len(self.interfaces)
if only_first_thread:
for cores in self.cpu_topology.values():
for core in cores.keys():
cores[core] = cores[core][:1]
include_lcores = [int(x) for x in include_lcores]
exclude_lcores = [int(x) for x in exclude_lcores]
self.has_zero_lcore = False
self.lcores_per_numa = {}
total_lcores = 0
for numa, cores in self.cpu_topology.items():
self.lcores_per_numa[numa] = {'main': [], 'siblings': [], 'all': []}
for core, lcores in cores.items():
total_lcores += len(lcores)
for lcore in list(lcores):
if include_lcores and lcore not in include_lcores:
cores[core].remove(lcore)
if exclude_lcores and lcore in exclude_lcores:
cores[core].remove(lcore)
if lcore > self.MAC_LCORE_NUM:
cores[core].remove(lcore)
if 0 in lcores:
self.has_zero_lcore = True
lcores.remove(0)
self.lcores_per_numa[numa]['siblings'].extend(lcores)
else:
self.lcores_per_numa[numa]['main'].extend(lcores[:1])
self.lcores_per_numa[numa]['siblings'].extend(lcores[1:])
self.lcores_per_numa[numa]['all'].extend(lcores)
for interface in self.interfaces:
for mandatory_interface_field in ConfigCreator.mandatory_interface_fields:
if mandatory_interface_field not in interface:
raise DpdkSetup("Expected '%s' field in interface dictionary, got: %s" % (mandatory_interface_field, interface))
Device_str = self._verify_devices_same_type(self.interfaces)
if '40Gb' in Device_str:
self.speed = 40
else:
self.speed = 10
minimum_required_lcores = len(self.interfaces) // 2 + 2
if total_lcores < minimum_required_lcores:
raise DpdkSetup('Your system should have at least %s cores for %s interfaces, and it has: %s.' %
(minimum_required_lcores, len(self.interfaces), total_lcores))
interfaces_per_numa = defaultdict(int)
for i in range(0, len(self.interfaces), 2):
if self.interfaces[i]['Slot_str'] == 'dummy':
numa = self.interfaces[i+1]['NUMA']
other_if_numa = self.interfaces[i]['NUMA']
else:
numa = self.interfaces[i]['NUMA']
other_if_numa = self.interfaces[i+1]['NUMA']
if numa != other_if_numa and not ignore_numa and self.interfaces[i]['Slot_str'] != 'dummy' and self.interfaces[i+1]['Slot_str'] != 'dummy':
raise DpdkSetup('NUMA of each pair of interfaces should be the same. Got NUMA %s for client interface %s, NUMA %s for server interface %s' %
(numa, self.interfaces[i]['Slot_str'], self.interfaces[i+1]['NUMA'], self.interfaces[i+1]['Slot_str']))
interfaces_per_numa[numa] += 2
self.interfaces_per_numa = interfaces_per_numa
self.prefix = prefix
self.zmq_pub_port = zmq_pub_port
self.zmq_rpc_port = zmq_rpc_port
self.ignore_numa = ignore_numa
@staticmethod
def verify_mac(mac_string):
if not ConfigCreator.mac_re.match(mac_string):
raise DpdkSetup('MAC address should be in format of 12:34:56:78:9a:bc, got: %s' % mac_string)
return mac_string.lower()
@staticmethod
def _exit_if_bad_ip(ip):
if not ConfigCreator._verify_ip(ip):
raise DpdkSetup("Got bad IP %s" % ip)
@staticmethod
def _verify_ip(ip):
a = ip.split('.')
if len(a) != 4:
return False
for x in a:
if not x.isdigit():
return False
i = int(x)
if i < 0 or i > 255:
return False
return True
@staticmethod
def _verify_devices_same_type(interfaces_list):
Device_str = interfaces_list[0]['Device_str']
if Device_str == 'dummy':
return Device_str
for interface in interfaces_list:
if interface['Device_str'] == 'dummy':
continue
if Device_str != interface['Device_str']:
raise DpdkSetup('Interfaces should be of same type, got:\n\t* %s\n\t* %s' % (Device_str, interface['Device_str']))
return Device_str
def create_config(self, filename = None, print_config = False):
config_str = '### Config file generated by dpdk_setup_ports.py ###\n\n'
config_str += '- port_limit: %s\n' % len(self.interfaces)
config_str += ' version: 2\n'
config_str += " interfaces: ['%s']\n" % "', '".join([interface['Slot_str'] + interface.get("sub_interface", "") for interface in self.interfaces])
if self.speed > 10:
config_str += ' port_bandwidth_gb: %s\n' % self.speed
if self.prefix:
config_str += ' prefix: %s\n' % self.prefix
if self.zmq_pub_port:
config_str += ' zmq_pub_port: %s\n' % self.zmq_pub_port
if self.zmq_rpc_port:
config_str += ' zmq_rpc_port: %s\n' % self.zmq_rpc_port
config_str += ' port_info:\n'
for index, interface in enumerate(self.interfaces):
if 'ip' in interface:
self._exit_if_bad_ip(interface['ip'])
self._exit_if_bad_ip(interface['def_gw'])
config_str += ' '*6 + '- ip: %s\n' % interface['ip']
config_str += ' '*8 + 'default_gw: %s\n' % interface['def_gw']
else:
config_str += ' '*6 + '- dest_mac: %s' % self.verify_mac(interface['dest_mac'])
if interface.get('loopback_dest'):
config_str += " # MAC OF LOOPBACK TO IT'S DUAL INTERFACE\n"
else:
config_str += '\n'
config_str += ' '*8 + 'src_mac: %s\n' % self.verify_mac(interface['src_mac'])
if index % 2:
config_str += '\n' # dual if barrier
if not self.ignore_numa:
config_str += ' platform:\n'
if len(self.interfaces_per_numa.keys()) == 1 and -1 in self.interfaces_per_numa: # VM, use any cores
lcores_pool = sorted([lcore for lcores in self.lcores_per_numa.values() for lcore in lcores['all']])
config_str += ' '*6 + 'master_thread_id: %s\n' % (0 if self.has_zero_lcore else lcores_pool.pop(0))
config_str += ' '*6 + 'latency_thread_id: %s\n' % lcores_pool.pop(0)
lcores_per_dual_if = int(len(lcores_pool) * 2 / len(self.interfaces))
config_str += ' '*6 + 'dual_if:\n'
for i in range(0, len(self.interfaces), 2):
lcores_for_this_dual_if = list(map(str, sorted(lcores_pool[:lcores_per_dual_if])))
lcores_pool = lcores_pool[lcores_per_dual_if:]
if not lcores_for_this_dual_if:
raise DpdkSetup('lcores_for_this_dual_if is empty (internal bug, please report with details of setup)')
config_str += ' '*8 + '- socket: 0\n'
config_str += ' '*10 + 'threads: [%s]\n\n' % ','.join(lcores_for_this_dual_if)
else:
# we will take common minimum among all NUMAs, to satisfy all
lcores_per_dual_if = 99
extra_lcores = 1 if self.has_zero_lcore else 2
# worst case 3 iterations, to ensure master and "rx" have cores left
while (lcores_per_dual_if * sum(self.interfaces_per_numa.values()) / 2) + extra_lcores > sum([len(lcores['all']) for lcores in self.lcores_per_numa.values()]):
lcores_per_dual_if -= 1
for numa, lcores_dict in self.lcores_per_numa.items():
if not self.interfaces_per_numa[numa]:
continue
lcores_per_dual_if = min(lcores_per_dual_if, int(2 * len(lcores_dict['all']) / self.interfaces_per_numa[numa]))
lcores_pool = copy.deepcopy(self.lcores_per_numa)
# first, allocate lcores for dual_if section
dual_if_section = ' '*6 + 'dual_if:\n'
for i in range(0, len(self.interfaces), 2):
if self.interfaces[i]['Device_str'] == 'dummy':
numa = self.interfaces[i+1]['NUMA']
else:
numa = self.interfaces[i]['NUMA']
dual_if_section += ' '*8 + '- socket: %s\n' % numa
lcores_for_this_dual_if = lcores_pool[numa]['all'][:lcores_per_dual_if]
lcores_pool[numa]['all'] = lcores_pool[numa]['all'][lcores_per_dual_if:]
for lcore in lcores_for_this_dual_if:
if lcore in lcores_pool[numa]['main']:
lcores_pool[numa]['main'].remove(lcore)
elif lcore in lcores_pool[numa]['siblings']:
lcores_pool[numa]['siblings'].remove(lcore)
else:
raise DpdkSetup('lcore not in main nor in siblings list (internal bug, please report with details of setup)')
if not lcores_for_this_dual_if:
raise DpdkSetup('Not enough cores at NUMA %s. This NUMA has %s processing units and %s interfaces.' % (numa, len(self.lcores_per_numa[numa]), self.interfaces_per_numa[numa]))
dual_if_section += ' '*10 + 'threads: [%s]\n\n' % ','.join(list(map(str, sorted(lcores_for_this_dual_if))))
# take the cores left to master and rx
mains_left = [lcore for lcores in lcores_pool.values() for lcore in lcores['main']]
siblings_left = [lcore for lcores in lcores_pool.values() for lcore in lcores['siblings']]
if mains_left:
rx_core = mains_left.pop(0)
else:
rx_core = siblings_left.pop(0)
if self.has_zero_lcore:
master_core = 0
elif mains_left:
master_core = mains_left.pop(0)
else:
master_core = siblings_left.pop(0)
config_str += ' '*6 + 'master_thread_id: %s\n' % master_core
config_str += ' '*6 + 'latency_thread_id: %s\n' % rx_core
# add the dual_if section
config_str += dual_if_section
# verify config is correct YAML format
try:
yaml.safe_load(config_str)
except Exception as e:
raise DpdkSetup('Could not create correct yaml config.\nGenerated YAML:\n%s\nEncountered error:\n%s' % (config_str, e))
if print_config:
print(config_str)
if filename:
if os.path.exists(filename):
if not dpdk_nic_bind.confirm('File %s already exist, overwrite? (y/N)' % filename):
print('Skipping.')
return config_str
with open(filename, 'w') as f:
f.write(config_str)
print('Saved to %s.' % filename)
return config_str
# only load igb_uio if it's available
def load_igb_uio():
loaded_mods = dpdk_nic_bind.get_loaded_modules()
if 'igb_uio' in loaded_mods:
return True
if 'uio' not in loaded_mods:
ret = os.system('modprobe uio')
if ret:
return False
km = './ko/%s/igb_uio.ko' % dpdk_nic_bind.kernel_ver
if os.path.exists(km):
return os.system('insmod %s' % km) == 0
# try to compile igb_uio if it's missing
def compile_and_load_igb_uio():
loaded_mods = dpdk_nic_bind.get_loaded_modules()
if 'igb_uio' in loaded_mods:
return
if 'uio' not in loaded_mods:
ret = os.system('modprobe uio')
if ret:
print('Failed inserting uio module, please check if it is installed')
sys.exit(-1)
km = './ko/%s/igb_uio.ko' % dpdk_nic_bind.kernel_ver
if not os.path.exists(km):
print("ERROR: We don't have precompiled igb_uio.ko module for your kernel version")
print('Will try compiling automatically - make sure you have file-system read/write permission')
try:
subprocess.check_output('make', cwd = './ko/src', stderr = subprocess.STDOUT)
subprocess.check_output(['make', 'install'], cwd = './ko/src', stderr = subprocess.STDOUT)
print('\nSuccess.')
except Exception as e:
print('\n ERROR: Automatic compilation failed: (%s)' % e)
print('Make sure you have file-system read/write permission')
print('You can try compiling yourself, using the following commands:')
print(' $cd ko/src')
print(' $make')
print(' $make install')
print(' $cd -')
print('Then, try to run TRex again.')
print('Note: you might need additional Linux packages for that:')
print(' * yum based (Fedora, CentOS, RedHat):')
print(' sudo yum install kernel-devel-`uname -r`')
print(' sudo yum group install "Development tools"')
print(' * apt based (Ubuntu):')
print(' sudo apt install linux-headers-`uname -r`')
print(' sudo apt install build-essential')
sys.exit(-1)
ret = os.system('insmod %s' % km)
if ret:
print('Failed inserting igb_uio module')
sys.exit(-1)
class map_driver(object):
args=None;
cfg_file='/etc/trex_cfg.yaml'
parent_args = None
class DpdkSetup(Exception):
pass
class CIfMap:
def __init__(self, cfg_file):
self.m_cfg_file =cfg_file;
self.m_cfg_dict={};
self.m_devices={};
self.m_is_mellanox_mode=False;
def dump_error (self,err):
s="""%s
From this TRex version a configuration file must exist in /etc/ folder "
The name of the configuration file should be /etc/trex_cfg.yaml "
The minimum configuration file should include something like this
- version : 2 # version 2 of the configuration file
interfaces : ["03:00.0","03:00.1","13:00.1","13:00.0"] # list of the interfaces to bind run ./dpdk_nic_bind.py --status to see the list
port_limit : 2 # number of ports to use valid is 2,4,6,8,10,12
example of already bind devices
$ ./dpdk_nic_bind.py --status
Network devices using DPDK-compatible driver
============================================
0000:03:00.0 '82599ES 10-Gigabit SFI/SFP+ Network Connection' drv=igb_uio unused=
0000:03:00.1 '82599ES 10-Gigabit SFI/SFP+ Network Connection' drv=igb_uio unused=
0000:13:00.0 '82599ES 10-Gigabit SFI/SFP+ Network Connection' drv=igb_uio unused=
0000:13:00.1 '82599ES 10-Gigabit SFI/SFP+ Network Connection' drv=igb_uio unused=
Network devices using kernel driver
===================================
0000:02:00.0 '82545EM Gigabit Ethernet Controller (Copper)' if=eth2 drv=e1000 unused=igb_uio *Active*
Other network devices
=====================
""" % (err);
return s;
def raise_error (self,err):
s= self.dump_error (err)
raise DpdkSetup(s)
def set_only_mellanox_nics(self):
self.m_is_mellanox_mode=True;
def get_only_mellanox_nics(self):
return self.m_is_mellanox_mode
def read_pci (self,pci_id,reg_id):
out=subprocess.check_output(['setpci', '-s',pci_id, '%s.w' %(reg_id)])
out=out.decode(errors='replace');
return (out.strip());
def write_pci (self,pci_id,reg_id,val):
out=subprocess.check_output(['setpci','-s',pci_id, '%s.w=%s' %(reg_id,val)])
out=out.decode(errors='replace');
return (out.strip());
def tune_mlx_device (self,pci_id):
# set PCIe Read to 4K and not 512 ... need to add it to startup s
val=self.read_pci (pci_id,68)
if val[0]=='0':
#hypervisor does not give the right to write to this register
return;
if val[0]!='5':
val='5'+val[1:]
self.write_pci (pci_id,68,val)
assert(self.read_pci (pci_id,68)==val);
def get_mtu_mlx (self,dev_id):
if len(dev_id)>0:
try:
out=subprocess.check_output(['ifconfig', dev_id])
except Exception as e:
raise DpdkSetup(' "ifconfig %s" utility does not works, try to install it using "$yum install net-tools -y" on CentOS system' %(dev_id) )
out=out.decode(errors='replace');
obj=re.search(r'MTU:(\d+)',out,flags=re.MULTILINE|re.DOTALL);
if obj:
return int(obj.group(1));
else:
obj=re.search(r'mtu (\d+)',out,flags=re.MULTILINE|re.DOTALL);
if obj:
return int(obj.group(1));
else:
return -1
def set_mtu_mlx (self,dev_id,new_mtu):
if len(dev_id)>0:
out=subprocess.check_output(['ifconfig', dev_id,'mtu',str(new_mtu)])
out=out.decode(errors='replace');
def set_max_mtu_mlx_device(self,dev_id):
mtu=9*1024+22
dev_mtu=self.get_mtu_mlx (dev_id);
if (dev_mtu>0) and (dev_mtu!=mtu):
self.set_mtu_mlx(dev_id,mtu);
if self.get_mtu_mlx(dev_id) != mtu:
print("Could not set MTU to %d" % mtu)
sys.exit(-1);
def disable_flow_control_mlx_device (self,dev_id):
if len(dev_id)>0:
my_stderr = open("/dev/null","wb")
cmd ='ethtool -A '+dev_id + ' rx off tx off '
subprocess.call(cmd, stdout=my_stderr,stderr=my_stderr, shell=True)
my_stderr.close();
def check_ofed_version (self):
ofed_info='/usr/bin/ofed_info'
ofed_ver_re = re.compile('.*[-](\d)[.](\d)[-].*')
ofed_ver= 42
ofed_ver_show= '4.2'
if not os.path.isfile(ofed_info):
print("OFED %s is not installed on this setup" % ofed_info)
sys.exit(-1);
try:
out = subprocess.check_output([ofed_info])
except Exception as e:
print("OFED %s can't run " % (ofed_info))
sys.exit(-1);
lines=out.splitlines();
if len(lines)>1:
m= ofed_ver_re.match(str(lines[0]))
if m:
ver=int(m.group(1))*10+int(m.group(2))
if ver < ofed_ver:
print("installed OFED version is '%s' should be at least '%s' and up" % (lines[0],ofed_ver_show))
sys.exit(-1);
else:
print("not found valid OFED version '%s' " % (lines[0]))
sys.exit(-1);
def verify_ofed_os(self):
err_msg = 'Warning: Mellanox NICs where tested only with RedHat/CentOS 7.4\n'
err_msg += 'Correct usage with other Linux distributions is not guaranteed.'
try:
dist = platform.dist()
if dist[0] not in ('redhat', 'centos') or not dist[1].startswith('7.4'):
print(err_msg)
except Exception as e:
print('Error while determining OS type: %s' % e)
def load_config_file (self):
fcfg=self.m_cfg_file
if not os.path.isfile(fcfg) :
self.raise_error ("There is no valid configuration file %s\n" % fcfg)
try:
stream = open(fcfg, 'r')
self.m_cfg_dict= yaml.safe_load(stream)
except Exception as e:
print(e);
raise e
stream.close();
cfg_dict = self.m_cfg_dict[0]
if 'version' not in cfg_dict:
raise DpdkSetup("Configuration file %s is old, it should include version field\n" % fcfg )
if int(cfg_dict['version'])<2 :
raise DpdkSetup("Configuration file %s is old, expected version 2, got: %s\n" % (fcfg, cfg_dict['version']))
if 'interfaces' not in self.m_cfg_dict[0]:
raise DpdkSetup("Configuration file %s is old, it should include interfaces field with even number of elements" % fcfg)
if_list= if_list_remove_sub_if(self.m_cfg_dict[0]['interfaces']);
l=len(if_list);
if l > 16:
raise DpdkSetup("Configuration file %s should include interfaces field with maximum 16 elements, got: %s." % (fcfg,l))
if l % 2:
raise DpdkSetup("Configuration file %s should include even number of interfaces, got: %s" % (fcfg,l))
if 'port_limit' in cfg_dict:
if cfg_dict['port_limit'] > len(if_list):
raise DpdkSetup('Error: port_limit should not be higher than number of interfaces in config file: %s\n' % fcfg)
if cfg_dict['port_limit'] % 2:
raise DpdkSetup('Error: port_limit in config file must be even number, got: %s\n' % cfg_dict['port_limit'])
if cfg_dict['port_limit'] <= 0:
raise DpdkSetup('Error: port_limit in config file must be positive number, got: %s\n' % cfg_dict['port_limit'])
if map_driver.parent_args and map_driver.parent_args.limit_ports is not None:
if map_driver.parent_args.limit_ports > len(if_list):
raise DpdkSetup('Error: --limit-ports CLI argument (%s) must not be higher than number of interfaces (%s) in config file: %s\n' % (map_driver.parent_args.limit_ports, len(if_list), fcfg))
def do_bind_all(self, drv, pci, force = False):
assert type(pci) is list
cmd = '{ptn} dpdk_nic_bind.py --bind={drv} {pci} {frc}'.format(
ptn = sys.executable,
drv = drv,
pci = ' '.join(pci),
frc = '--force' if force else '')
print(cmd)
return os.system(cmd)
# pros: no need to compile .ko per Kernel version
# cons: need special config/hw (not always works)
def try_bind_to_vfio_pci(self, to_bind_list):
krnl_params_file = '/proc/cmdline'
if not os.path.exists(krnl_params_file):
raise VFIOBindErr('Could not find file with Kernel boot parameters: %s' % krnl_params_file)
with open(krnl_params_file) as f:
krnl_params = f.read()
if 'iommu=' not in krnl_params:
raise VFIOBindErr('vfio-pci is not an option here')
if 'vfio_pci' not in dpdk_nic_bind.get_loaded_modules():
ret = os.system('modprobe vfio_pci')
if ret:
raise VFIOBindErr('Could not load vfio_pci')
ret = self.do_bind_all('vfio-pci', to_bind_list)
if ret:
raise VFIOBindErr('Binding to vfio_pci failed')
def pci_name_to_full_name (self,pci_name):
if pci_name == 'dummy':
return pci_name
c='[0-9A-Fa-f]';
sp='[:]'
s_short=c+c+sp+c+c+'[.]'+c;
s_full=c+c+c+c+sp+s_short
re_full = re.compile(s_full)
re_short = re.compile(s_short)
if re_short.match(pci_name):
return '0000:'+pci_name
if re_full.match(pci_name):
return pci_name
err=" %s is not a valid pci address \n" %pci_name;
raise DpdkSetup(err)
def run_dpdk_lspci (self):
dpdk_nic_bind.get_nic_details()
self.m_devices= dpdk_nic_bind.devices
def get_prefix(self):
if map_driver.parent_args.prefix:
return map_driver.parent_args.prefix
return self.m_cfg_dict[0].get('prefix', '')
def preprocess_astf_file_is_needed(self):
""" check if we are in astf mode, in case we are convert the profile to json in tmp"""
is_astf_mode = map_driver.parent_args and map_driver.parent_args.astf
if is_astf_mode:
input_file = map_driver.parent_args.file
if not input_file:
return
just_copy=False
extension = os.path.splitext(input_file)[1]
if extension == '.json':
just_copy = True;
else:
if extension != '.py':
raise DpdkSetup('ERROR when running with --astf mode, you need to have a new Python profile format (.py) and not YAML')
instance_name = ""
prefix = self.get_prefix()
if prefix:
instance_name = '-' + prefix
json_file = "/tmp/astf{instance}.json".format(instance=instance_name)
msg="converting astf profile {file} to json {out}".format(file = input_file, out=json_file)
print(msg);
tunable='';
if map_driver.parent_args.tunable:
tunable="-t "+map_driver.parent_args.tunable+" "
if just_copy:
cmd = 'cp {file} {json_file}'.format(file=input_file, json_file=json_file)
else:
cmd = './astf-sim -f {file} {tun} --json > {json_file}'.format(file=input_file, tun=tunable, json_file=json_file)
print(cmd)
ret = os.system(cmd)
os.chmod(json_file, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
if ret:
with open(json_file) as f:
out = ' ' + '\n '.join(f.read().splitlines())
raise DpdkSetup('ERROR could not convert astf profile to JSON try to debug it using the command above.\nProduced output:\n%s' % out)
def verify_stf_file(self):
""" check the input file of STF """
is_stf_mode = map_driver.parent_args and (not map_driver.parent_args.astf) and map_driver.parent_args.file
if is_stf_mode:
extension = os.path.splitext(map_driver.parent_args.file)[1]
if extension == '.py':
raise DpdkSetup('ERROR: Python files can not be used with STF mode, did you forget "--astf" flag?')
elif extension != '.yaml':
pass # should we fail here?
def config_hugepages(self, wanted_count = None):
huge_mnt_dir = '/mnt/huge'
if not os.path.isdir(huge_mnt_dir):
print("Creating huge node")
os.makedirs(huge_mnt_dir)
mount_output = subprocess.check_output('mount', stderr = subprocess.STDOUT).decode(errors='replace')
if 'hugetlbfs' not in mount_output:
os.system('mount -t hugetlbfs nodev %s' % huge_mnt_dir)
for socket_id in range(2):
filename = '/sys/devices/system/node/node%d/hugepages/hugepages-2048kB/nr_hugepages' % socket_id
if not os.path.isfile(filename):
if socket_id == 0:
print('WARNING: hugepages config file (%s) does not exist!' % filename)
continue
if wanted_count is None:
if self.m_cfg_dict[0].get('low_end', False):
if socket_id == 0:
if map_driver.parent_args and map_driver.parent_args.limit_ports:
if_count = map_driver.parent_args.limit_ports
else:
if_count = self.m_cfg_dict[0].get('port_limit', len(self.m_cfg_dict[0]['interfaces']))
wanted_count = 20 + 40 * if_count
else:
wanted_count = 1 # otherwise, DPDK will not be able to see the device
else:
wanted_count = 2048
with open(filename) as f:
configured_hugepages = int(f.read())
if configured_hugepages < wanted_count:
os.system('echo %d > %s' % (wanted_count, filename))
time.sleep(0.1)
with open(filename) as f: # verify
configured_hugepages = int(f.read())
if configured_hugepages < wanted_count:
print('WARNING: tried to configure %d hugepages for socket %d, but result is: %d' % (wanted_count, socket_id, configured_hugepages))
def run_scapy_server(self):
if map_driver.parent_args and map_driver.parent_args.stl and not map_driver.parent_args.no_scapy_server:
try:
master_core = self.m_cfg_dict[0]['platform']['master_thread_id']
except:
master_core = 0
ret = os.system('%s scapy_daemon_server restart -c %s' % (sys.executable, master_core))
if ret:
print("Could not start scapy_daemon_server, which is needed by GUI to create packets.\nIf you don't need it, use --no-scapy-server flag.")
sys.exit(-1)
# check vdev Linux interfaces status
# return True if interfaces are vdev
def check_vdev(self, if_list):
if not if_list:
return
af_names = []
ifname_re = re.compile('iface\s*=\s*([^\s,]+)')
found_vdev = False
found_pdev = False
for iface in if_list:
if iface == 'dummy':
continue
elif '--vdev' in iface:
found_vdev = True
if 'net_af_packet' in iface:
res = ifname_re.search(iface)
if res:
af_names.append(res.group(1))
elif ':' not in iface: # no PCI => assume af_packet
found_vdev = True
af_names.append(iface)
else:
found_pdev = True
if found_vdev:
if found_pdev:
raise DpdkSetup('You have mix of vdev and pdev interfaces in config file!')
for name in af_names:
if not os.path.exists('/sys/class/net/%s' % name):
raise DpdkSetup('ERROR: Could not find Linux interface %s.' % name)
oper_state = '/sys/class/net/%s/operstate' % name
if os.path.exists(oper_state):
with open(oper_state) as f:
f_cont = f.read().strip()
if f_cont in ('down', 'DOWN'):
raise DpdkSetup('ERROR: Requested Linux interface %s is DOWN.' % name)
return found_vdev
def check_trex_running(self, if_list):
if if_list and map_driver.args.parent and self.m_cfg_dict[0].get('enable_zmq_pub', True):
publisher_port = self.m_cfg_dict[0].get('zmq_pub_port', 4500)
pid = dpdk_nic_bind.get_tcp_port_usage(publisher_port)
if pid:
cmdline = dpdk_nic_bind.read_pid_cmdline(pid)
print('ZMQ port is used by following process:\npid: %s, cmd: %s' % (pid, cmdline))
sys.exit(-1)
# verify that all interfaces of i40e NIC are in use by current instance of TRex
def check_i40e_binds(self, if_list):
# i40e device IDs taked from dpdk/drivers/net/i40e/base/i40e_devids.h
i40e_device_ids = [0x1572, 0x1574, 0x1580, 0x1581, 0x1583, 0x1584, 0x1585, 0x1586, 0x1587, 0x1588, 0x1589, 0x158A, 0x158B]
iface_without_slash = set()
for iface in if_list:
iface_without_slash.add(self.split_pci_key(iface))
show_warning_devices = set()
for iface in iface_without_slash:
if iface == 'dummy':
continue
iface = self.split_pci_key(iface)
if self.m_devices[iface]['Device'] not in i40e_device_ids: # not i40e
return
iface_pci = iface.split('.')[0]
for device in self.m_devices.values():
if device['Slot'] in iface_without_slash: # we use it
continue
if iface_pci == device['Slot'].split('.')[0]:
if device.get('Driver_str') == 'i40e':
print('ERROR: i40e interface %s is under Linux and will interfere with TRex interface %s' % (device['Slot'], iface))
print('See following link for more information: https://trex-tgn.cisco.com/youtrack/issue/trex-528')
print('Unbind the interface from Linux with following command:')
print(' sudo ./dpdk_nic_bind.py -u %s' % device['Slot'])
print('')
sys.exit(-1)
if device.get('Driver_str') in dpdk_nic_bind.dpdk_drivers:
show_warning_devices.add(device['Slot'])
for dev in show_warning_devices:
print('WARNING: i40e interface %s is under DPDK driver and might interfere with current TRex interfaces.' % dev)
def do_run (self, only_check_all_mlx=False):
""" returns code that specifies if interfaces are Mellanox/Napatech etc. """
self.load_config_file()
self.preprocess_astf_file_is_needed()
self.verify_stf_file()
if (map_driver.parent_args is None or
map_driver.parent_args.dump_interfaces is None or
(map_driver.parent_args.dump_interfaces == [] and
map_driver.parent_args.cfg)):
if_list=if_list_remove_sub_if(self.m_cfg_dict[0]['interfaces'])
else:
if_list = map_driver.parent_args.dump_interfaces
if not if_list:
self.run_dpdk_lspci()
for dev in self.m_devices.values():
if dev.get('Driver_str') in dpdk_nic_bind.dpdk_drivers + dpdk_nic_bind.dpdk_and_kernel:
if_list.append(dev['Slot'])
if self.check_vdev(if_list):
self.check_trex_running(if_list)
self.run_scapy_server()
# no need to config hugepages
return
self.run_dpdk_lspci()
if_list = list(map(self.pci_name_to_full_name, if_list))
# check how many mellanox cards we have
Mellanox_cnt=0;
dummy_cnt=0
for key in if_list:
if key == 'dummy':
dummy_cnt += 1
continue
key = self.split_pci_key(key)
if key not in self.m_devices:
err=" %s does not exist " %key;
raise DpdkSetup(err)
if 'Vendor_str' not in self.m_devices[key]:
err=" %s does not have Vendor_str " %key;
raise DpdkSetup(err)
if 'Mellanox' in self.m_devices[key]['Vendor_str']:
Mellanox_cnt += 1
if not (map_driver.parent_args and map_driver.parent_args.dump_interfaces):
if (Mellanox_cnt > 0) and ((Mellanox_cnt + dummy_cnt) != len(if_list)):
err = "All driver should be from one vendor. You have at least one driver from Mellanox but not all."
raise DpdkSetup(err)
if Mellanox_cnt > 0:
self.set_only_mellanox_nics()
if self.get_only_mellanox_nics():
if not map_driver.parent_args.no_ofed_check:
self.verify_ofed_os()
self.check_ofed_version()
for key in if_list:
if key == 'dummy':
continue
key = self.split_pci_key(key)
if 'Virtual' not in self.m_devices[key]['Device_str']:
pci_id = self.m_devices[key]['Slot_str']
self.tune_mlx_device(pci_id)
if 'Interface' in self.m_devices[key]:
dev_ids = self.m_devices[key]['Interface'].split(",")
for dev_id in dev_ids:
self.disable_flow_control_mlx_device (dev_id)
self.set_max_mtu_mlx_device(dev_id)
if only_check_all_mlx:
if Mellanox_cnt > 0:
sys.exit(MLX_EXIT_CODE);
else:
sys.exit(0);
self.check_i40e_binds(if_list)
self.check_trex_running(if_list)
self.config_hugepages() # should be after check of running TRex
self.run_scapy_server()
Napatech_cnt=0;
to_bind_list = []
for key in if_list:
if key == 'dummy':
continue
key = self.split_pci_key(key)
if key not in self.m_devices:
err=" %s does not exist " %key;
raise DpdkSetup(err)
if 'Napatech' in self.m_devices[key]['Vendor_str']:
# These adapters doesn't need binding
Napatech_cnt += 1
continue
if self.m_devices[key].get('Driver_str') not in (dpdk_nic_bind.dpdk_drivers + dpdk_nic_bind.dpdk_and_kernel):
to_bind_list.append(key)
if Napatech_cnt:
# This is currently a hack needed until the DPDK NTACC PMD can do proper
# cleanup.
os.system("ipcs | grep 2117a > /dev/null && ipcrm shm `ipcs | grep 2117a | cut -d' ' -f2` > /dev/null")
if to_bind_list:
if Mellanox_cnt:
ret = self.do_bind_all('mlx5_core', to_bind_list)
if ret:
ret = self.do_bind_all('mlx4_core', to_bind_list)
if ret:
raise DpdkSetup('Unable to bind interfaces to driver mlx5_core/mlx4_core.')
return MLX_EXIT_CODE
else:
# if igb_uio is ready, use it as safer choice, afterwards try vfio-pci
if load_igb_uio():
print('Trying to bind to igb_uio ...')
ret = self.do_bind_all('igb_uio', to_bind_list)
if ret:
raise DpdkSetup('Unable to bind interfaces to driver igb_uio.') # module present, loaded, but unable to bind
return
try:
print('Trying to bind to vfio-pci ...')
self.try_bind_to_vfio_pci(to_bind_list)
return
except VFIOBindErr as e:
pass
#print(e)
print('Trying to compile and bind to igb_uio ...')
compile_and_load_igb_uio()
ret = self.do_bind_all('igb_uio', to_bind_list)
if ret:
raise DpdkSetup('Unable to bind interfaces to driver igb_uio.')
elif Mellanox_cnt:
return MLX_EXIT_CODE
elif Napatech_cnt:
return NTACC_EXIT_CODE
def do_return_to_linux(self):
if not self.m_devices:
self.run_dpdk_lspci()
dpdk_interfaces = []
check_drivers = set()
for device in self.m_devices.values():
if device.get('Driver_str') in dpdk_nic_bind.dpdk_drivers:
dpdk_interfaces.append(device['Slot'])
check_drivers.add(device['Driver_str'])
if not dpdk_interfaces:
print('No DPDK bound interfaces.')
return
any_driver_used = False
for driver in check_drivers:
if dpdk_nic_bind.is_module_used(driver):
any_driver_used = True
if any_driver_used:
pid = dpdk_nic_bind.get_pid_using_pci(dpdk_interfaces)
if pid:
cmdline = dpdk_nic_bind.read_pid_cmdline(pid)
print('DPDK interfaces are in use. Unbinding them might cause following process to hang:\npid: %s, cmd: %s' % (pid, cmdline))
if not dpdk_nic_bind.confirm('Confirm (y/N):'):
sys.exit(-1)
# DPDK => Linux
drivers_table = {
'net_ixgbe': 'ixgbe',
'net_ixgbe_vf': 'ixgbevf',
'net_e1000_igb': 'igb',
'net_i40e': 'i40e',
'net_i40e_vf': 'i40evf',
'net_e1000_em': 'e1000',
'net_vmxnet3': 'vmxnet3',
'net_virtio': 'virtio-pci',
'net_enic': 'enic',
}
nics_info = dpdk_nic_bind.get_info_from_trex(dpdk_interfaces)
if not nics_info:
raise DpdkSetup('Could not determine interfaces information. Try to run manually: sudo ./t-rex-64 --dump-interfaces')
for pci, info in nics_info.items():
if pci not in self.m_devices:
raise DpdkSetup('Internal error: PCI %s is not found among devices' % pci)
dev = self.m_devices[pci]
if info['TRex_Driver'] not in drivers_table:
raise DpdkSetup("Got unknown driver '%s', description: %s" % (info['TRex_Driver'], dev['Device_str']))
linux_driver = drivers_table[info['TRex_Driver']]
if linux_driver not in dpdk_nic_bind.get_loaded_modules():
print("No Linux driver installed, or wrong module name: %s" % linux_driver)
else:
print('Returning to Linux %s' % pci)
dpdk_nic_bind.bind_one(pci, linux_driver, False)
def split_pci_key(self, pci_id):
return pci_id.split('/')[0]
def _get_cpu_topology(self):
cpu_topology_file = '/proc/cpuinfo'
# physical processor -> physical core -> logical processing units (threads)
cpu_topology = OrderedDict()
if not os.path.exists(cpu_topology_file):
raise DpdkSetup('File with CPU topology (%s) does not exist.' % cpu_topology_file)
with open(cpu_topology_file) as f:
for lcore in f.read().split('\n\n'):
if not lcore:
continue
lcore_dict = OrderedDict()
for line in lcore.split('\n'):
key, val = line.split(':', 1)
lcore_dict[key.strip()] = val.strip()
if 'processor' not in lcore_dict:
continue
numa = int(lcore_dict.get('physical id', -1))
if numa not in cpu_topology:
cpu_topology[numa] = OrderedDict()
core = int(lcore_dict.get('core id', lcore_dict['processor']))
if core not in cpu_topology[numa]:
cpu_topology[numa][core] = []
cpu_topology[numa][core].append(int(lcore_dict['processor']))
if not cpu_topology:
raise DpdkSetup('Could not determine CPU topology from %s' % cpu_topology_file)
return cpu_topology
# input: list of different descriptions of interfaces: index, pci, name etc.
# Binds to dpdk wanted interfaces, not bound to any driver.
# output: list of maps of devices in dpdk_* format (self.m_devices.values())
def _get_wanted_interfaces(self, input_interfaces, get_macs = True):
if type(input_interfaces) is not list:
raise DpdkSetup('type of input interfaces should be list')
if not len(input_interfaces):
raise DpdkSetup('Please specify interfaces to use in the config')
if len(input_interfaces) % 2:
raise DpdkSetup('Please specify even number of interfaces')
wanted_interfaces = []
sorted_pci = sorted(self.m_devices.keys())
for interface in input_interfaces:
if interface == 'dummy':
dev = {}
dev['Vendor_str'] = ''
dev['Slot'] = ''
dev['Slot_str'] = 'dummy'
dev['Device_str'] = 'dummy'
dev['NUMA'] = 0
dev['MAC'] = '00:00:00:00:00:00'
dev['Interface_argv'] = interface
wanted_interfaces.append(dict(dev))
continue
sub_interface = None
if "/" in interface:
interface,sub_interface = interface.split("/")
dev = None
try:
interface = int(interface)
if interface < 0 or interface >= len(sorted_pci):
raise DpdkSetup('Index of an interfaces should be in range 0:%s' % (len(sorted_pci) - 1))
dev = self.m_devices[sorted_pci[interface]]
except ValueError:
for d in self.m_devices.values():
if interface in (d['Interface'], d['Slot'], d['Slot_str']):
dev = d
break
if not dev:
raise DpdkSetup('Could not find information about this interface: %s' % interface)
if dev in wanted_interfaces and not sub_interface:
raise DpdkSetup('Interface %s is specified twice' % interface)
dev['Interface_argv'] = interface
if sub_interface:
nt_devs = dpdk_nic_bind.collect_nt_dev_info()
if nt_devs is None:
raise DpdkSetup('Sorry, for this script to function with Napatech SmartNICs, you either need ntservice running or alternatively unload 3gd kernel module')
dev['sub_interface'] = "/" + sub_interface
sub_interface = int(sub_interface)
try:
num_ports = nt_devs[dev["Slot"]].get("num_ports", 0)
except KeyError:
raise DpdkSetup('Sorry, I know nothing about sub interface %d/%d' % (interface,sub_interface))
if sub_interface >= num_ports or sub_interface < 0 :
raise DpdkSetup('Sub interface %s/%d is invalid (valid range: %s/0 - %s/%d)' %
(interface, sub_interface, interface, interface, num_ports-1))
if nt_devs:
dev['MAC'] = nt_devs[dev["Slot"]].get("Mac_" + str(sub_interface), dev["MAC"])
wanted_interfaces.append(dict(dev))
if get_macs:
unbound = []
dpdk_bound = []
for interface in wanted_interfaces:
if 'Driver_str' not in interface and 'Napatech' not in interface['Vendor_str']:
unbound.append(interface['Slot'])
elif interface.get('Driver_str') in dpdk_nic_bind.dpdk_drivers:
dpdk_bound.append(interface['Slot'])
if unbound or dpdk_bound:
for pci, info in dpdk_nic_bind.get_info_from_trex(unbound + dpdk_bound).items():
if pci not in self.m_devices:
raise DpdkSetup('Internal error: PCI %s is not found among devices' % pci)
self.m_devices[pci].update(info)
return wanted_interfaces
def do_create(self):
ips = map_driver.args.ips
def_gws = map_driver.args.def_gws
dest_macs = map_driver.args.dest_macs
if map_driver.args.force_macs:
ip_config = False
if ips:
raise DpdkSetup("If using --force-macs, should not specify ips")
if def_gws:
raise DpdkSetup("If using --force-macs, should not specify default gateways")
elif ips:
ip_config = True
if not def_gws:
raise DpdkSetup("If specifying ips, must specify also def-gws")
if dest_macs:
raise DpdkSetup("If specifying ips, should not specify dest--macs")
if len(ips) != len(def_gws) or len(ips) != len(map_driver.args.create_interfaces):
raise DpdkSetup("Number of given IPs should equal number of given def-gws and number of interfaces")
else:
if dest_macs:
ip_config = False
else:
ip_config = True
# gather info about NICS from dpdk_nic_bind.py
if not self.m_devices:
self.run_dpdk_lspci()
wanted_interfaces = self._get_wanted_interfaces(map_driver.args.create_interfaces, get_macs = not ip_config)
for i, interface in enumerate(wanted_interfaces):
dual_index = i + 1 - (i % 2) * 2
if ip_config:
if isinstance(ips, list) and len(ips) > i:
interface['ip'] = ips[i]
else:
interface['ip'] = '.'.join([str(i+1) for _ in range(4)])
if isinstance(def_gws, list) and len(def_gws) > i:
interface['def_gw'] = def_gws[i]
else:
interface['def_gw'] = '.'.join([str(dual_index+1) for _ in range(4)])
else:
dual_if = wanted_interfaces[dual_index]
if 'MAC' not in interface:
raise DpdkSetup('Could not determine MAC of interface: %s. Please verify with -t flag.' % interface['Interface_argv'])
if 'MAC' not in dual_if:
raise DpdkSetup('Could not determine MAC of interface: %s. Please verify with -t flag.' % dual_if['Interface_argv'])
interface['src_mac'] = interface['MAC']
if isinstance(dest_macs, list) and len(dest_macs) > i:
interface['dest_mac'] = dest_macs[i]
else:
interface['dest_mac'] = dual_if['MAC']
interface['loopback_dest'] = True
config = ConfigCreator(self._get_cpu_topology(), wanted_interfaces, include_lcores = map_driver.args.create_include, exclude_lcores = map_driver.args.create_exclude,
only_first_thread = map_driver.args.no_ht, ignore_numa = map_driver.args.ignore_numa,
prefix = map_driver.args.prefix, zmq_rpc_port = map_driver.args.zmq_rpc_port, zmq_pub_port = map_driver.args.zmq_pub_port)
if map_driver.args.output_config:
config.create_config(filename = map_driver.args.output_config)
else:
print('### Dumping config to screen, use -o flag to save to file')
config.create_config(print_config = True)
def do_interactive_create(self):
ignore_numa = False
cpu_topology = self._get_cpu_topology()
total_lcores = sum([len(lcores) for cores in cpu_topology.values() for lcores in cores.values()])
if total_lcores < 1:
raise DpdkSetup('Script could not determine number of cores of the system, exiting.')
elif total_lcores < 2:
if dpdk_nic_bind.confirm("You only have 1 core and can't run TRex at all. Ignore and continue? (y/N): "):
ignore_numa = True
else:
sys.exit(1)
elif total_lcores < 3:
if dpdk_nic_bind.confirm("You only have 2 cores and will be able to run only stateful without latency checks.\nIgnore and continue? (y/N): "):
ignore_numa = True
else:
sys.exit(1)
if map_driver.args.force_macs:
ip_based = False
elif dpdk_nic_bind.confirm("By default, IP based configuration file will be created. Do you want to use MAC based config? (y/N)"):
ip_based = False
else:
ip_based = True
ip_addr_digit = 1
if not self.m_devices:
self.run_dpdk_lspci()
dpdk_nic_bind.show_table(get_macs = not ip_based)
print('Please choose even number of interfaces from the list above, either by ID , PCI or Linux IF')
print('Stateful will use order of interfaces: Client1 Server1 Client2 Server2 etc. for flows.')
print('Stateless can be in any order.')
numa = None
for dev in self.m_devices.values():
if numa is None:
numa = dev['NUMA']
elif numa != dev['NUMA']:
print('For performance, try to choose each pair of interfaces to be on the same NUMA.')
break
while True:
try:
input = dpdk_nic_bind.read_line('Enter list of interfaces separated by space (for example: 1 3) : ')
create_interfaces = input.replace(',', ' ').replace(';', ' ').split()
wanted_interfaces = self._get_wanted_interfaces(create_interfaces)
ConfigCreator._verify_devices_same_type(wanted_interfaces)
except Exception as e:
print(e)
continue
break
print('')
for interface in wanted_interfaces:
if interface['Active']:
print('Interface %s is active. Using it by TRex might close ssh connections etc.' % interface['Interface_argv'])
if not dpdk_nic_bind.confirm('Ignore and continue? (y/N): '):
sys.exit(-1)
for i, interface in enumerate(wanted_interfaces):
if not ip_based:
if 'MAC' not in interface:
raise DpdkSetup('Could not determine MAC of interface: %s. Please verify with -t flag.' % interface['Interface_argv'])
interface['src_mac'] = interface['MAC']
dual_index = i + 1 - (i % 2) * 2
dual_int = wanted_interfaces[dual_index]
if not ignore_numa and interface['NUMA'] != dual_int['NUMA']:
print('NUMA is different at pair of interfaces: %s and %s. It will reduce performance.' % (interface['Interface_argv'], dual_int['Interface_argv']))
if dpdk_nic_bind.confirm('Ignore and continue? (y/N): '):
ignore_numa = True
print('')
else:
return
if ip_based:
if ip_addr_digit % 2 == 0:
dual_ip_digit = ip_addr_digit - 1
else:
dual_ip_digit = ip_addr_digit + 1
ip = '.'.join([str(ip_addr_digit) for _ in range(4)])
def_gw= '.'.join([str(dual_ip_digit) for _ in range(4)])
ip_addr_digit += 1
print("For interface %s, assuming loopback to it's dual interface %s." % (interface['Interface_argv'], dual_int['Interface_argv']))
if dpdk_nic_bind.confirm("Putting IP %s, default gw %s Change it?(y/N)." % (ip, def_gw)):
while True:
ip = dpdk_nic_bind.read_line('Please enter IP address for interface %s: ' % interface['Interface_argv'])
if not ConfigCreator._verify_ip(ip):
print ("Bad IP address format")
else:
break
while True:
def_gw = dpdk_nic_bind.read_line('Please enter default gateway for interface %s: ' % interface['Interface_argv'])
if not ConfigCreator._verify_ip(def_gw):
print ("Bad IP address format")
else:
break
wanted_interfaces[i]['ip'] = ip
wanted_interfaces[i]['def_gw'] = def_gw
else:
dest_mac = dual_int['MAC']
loopback_dest = True
print("For interface %s, assuming loopback to it's dual interface %s." % (interface['Interface_argv'], dual_int['Interface_argv']))
if dpdk_nic_bind.confirm("Destination MAC is %s. Change it to MAC of DUT? (y/N)." % dest_mac):
while True:
input_mac = dpdk_nic_bind.read_line('Please enter new destination MAC of interface %s: ' % interface['Interface_argv'])
try:
if input_mac:
ConfigCreator.verify_mac(input_mac) # verify format
dest_mac = input_mac
loopback_dest = False
else:
print('Leaving the loopback MAC.')
except Exception as e:
print(e)
continue
break
wanted_interfaces[i]['dest_mac'] = dest_mac
wanted_interfaces[i]['loopback_dest'] = loopback_dest
config = ConfigCreator(cpu_topology, wanted_interfaces, include_lcores = map_driver.args.create_include, exclude_lcores = map_driver.args.create_exclude,
only_first_thread = map_driver.args.no_ht, ignore_numa = map_driver.args.ignore_numa or ignore_numa,
prefix = map_driver.args.prefix, zmq_rpc_port = map_driver.args.zmq_rpc_port, zmq_pub_port = map_driver.args.zmq_pub_port)
if dpdk_nic_bind.confirm('Print preview of generated config? (Y/n)', default = True):
config.create_config(print_config = True)
if dpdk_nic_bind.confirm('Save the config to file? (Y/n)', default = True):
print('Default filename is /etc/trex_cfg.yaml')
filename = dpdk_nic_bind.read_line('Press ENTER to confirm or enter new file: ')
if not filename:
filename = '/etc/trex_cfg.yaml'
config.create_config(filename = filename)
def parse_parent_cfg (parent_cfg):
parent_parser = argparse.ArgumentParser(add_help = False)
parent_parser.add_argument('-?', '-h', '--help', dest = 'help', action = 'store_true')
parent_parser.add_argument('--cfg', default='')
parent_parser.add_argument('--prefix', default='')
parent_parser.add_argument('--dump-interfaces', nargs='*', default=None)
parent_parser.add_argument('--no-ofed-check', action = 'store_true')
parent_parser.add_argument('--no-scapy-server', action = 'store_true')
parent_parser.add_argument('--no-watchdog', action = 'store_true')
parent_parser.add_argument('--astf', action = 'store_true')
parent_parser.add_argument('--limit-ports', type = int)
parent_parser.add_argument('-f', dest = 'file')
parent_parser.add_argument('-t', dest = 'tunable',default=None)
parent_parser.add_argument('-i', action = 'store_true', dest = 'stl', default = False)
map_driver.parent_args, _ = parent_parser.parse_known_args(shlex.split(parent_cfg))
if map_driver.parent_args.help:
sys.exit(0)
if map_driver.parent_args.limit_ports is not None:
if map_driver.parent_args.limit_ports % 2:
raise DpdkSetup('ERROR: --limit-ports CLI argument must be even number, got: %s' % map_driver.parent_args.limit_ports)
if map_driver.parent_args.limit_ports <= 0:
raise DpdkSetup('ERROR: --limit-ports CLI argument must be positive, got: %s' % map_driver.parent_args.limit_ports)
def process_options ():
parser = argparse.ArgumentParser(usage="""
Examples:
---------
To return to Linux the DPDK bound interfaces (for ifconfig etc.)
sudo ./dpdk_set_ports.py -L
To create TRex config file using interactive mode
sudo ./dpdk_set_ports.py -i
To create a default config file (example)
sudo ./dpdk_setup_ports.py -c 02:00.0 02:00.1 -o /etc/trex_cfg.yaml
To show interfaces status
sudo ./dpdk_set_ports.py -s
To see more detailed info on interfaces (table):
sudo ./dpdk_set_ports.py -t
""",
description=" unbind dpdk interfaces ",
epilog=" written by hhaim");
parser.add_argument("-l", '-L', "--linux", action='store_true',
help=""" Return all DPDK interfaces to Linux driver """,
)
parser.add_argument("--cfg",
help=""" configuration file name """,
)
parser.add_argument("--parent",
help=argparse.SUPPRESS
)
parser.add_argument('--dump-pci-description', help=argparse.SUPPRESS, dest='dump_pci_desc', action='store_true')
parser.add_argument("-i", "--interactive", action='store_true',
help=""" Create TRex config in interactive mode """,
)
parser.add_argument("-c", "--create", nargs='*', default=None, dest='create_interfaces', metavar='<interface>',
help="""Try to create a configuration file by specifying needed interfaces by PCI address or Linux names: eth1 etc.""",
)
parser.add_argument("--ci", "--cores-include", nargs='*', default=[], dest='create_include', metavar='<cores>',
help="""White list of cores to use. Make sure there is enough for each NUMA.""",
)
parser.add_argument("--ce", "--cores-exclude", nargs='*', default=[], dest='create_exclude', metavar='<cores>',
help="""Black list of cores to exclude. Make sure there will be enough for each NUMA.""",
)
parser.add_argument("--no-ht", default=False, dest='no_ht', action='store_true',
help="""Use only one thread of each Core in created config yaml (No Hyper-Threading).""",
)
parser.add_argument("--dest-macs", nargs='*', default=[], action='store',
help="""Destination MACs to be used in created yaml file. Without them, will assume loopback (0<->1, 2<->3 etc.)""",
)
parser.add_argument("--force-macs", default=False, action='store_true',
help="""Use MACs in created config file.""",
)
parser.add_argument("--ips", nargs='*', default=[], action='store',
help="""IP addresses to be used in created yaml file. Without them, will assume loopback (0<->1, 2<->3 etc.)""",
)
parser.add_argument("--def-gws", nargs='*', default=[], action='store',
help="""Default gateways to be used in created yaml file. Without them, will assume loopback (0<->1, 2<->3 etc.)""",
)
parser.add_argument("-o", default=None, action='store', metavar='PATH', dest = 'output_config',
help="""Output the config to this file.""",
)
parser.add_argument("--prefix", default=None, action='store',
help="""Advanced option: prefix to be used in TRex config in case of parallel instances.""",
)
parser.add_argument("--zmq-pub-port", default=None, action='store',
help="""Advanced option: ZMQ Publisher port to be used in TRex config in case of parallel instances.""",
)
parser.add_argument("--zmq-rpc-port", default=None, action='store',
help="""Advanced option: ZMQ RPC port to be used in TRex config in case of parallel instances.""",
)
parser.add_argument("--ignore-numa", default=False, action='store_true',
help="""Advanced option: Ignore NUMAs for config creation. Use this option only if you have to, as it will reduce performance.""",
)
parser.add_argument("-s", "--show", action='store_true',
help=""" show the status """,
)
parser.add_argument("-t", "--table", action='store_true',
help=""" show table with NICs info """,
)
parser.add_argument('--version', action='version',
version="0.2" )
map_driver.args = parser.parse_args();
if map_driver.args.parent :
parse_parent_cfg (map_driver.args.parent)
if map_driver.parent_args.cfg:
map_driver.cfg_file = map_driver.parent_args.cfg;
if map_driver.parent_args.prefix:
map_driver.prefix = map_driver.parent_args.prefix
if map_driver.args.cfg :
map_driver.cfg_file = map_driver.args.cfg;
def main ():
try:
if os.getuid() != 0:
raise DpdkSetup('Please run this program as root/with sudo')
process_options ()
if map_driver.args.show:
dpdk_nic_bind.show_status()
return
if map_driver.args.table:
dpdk_nic_bind.show_table()
return
if map_driver.args.dump_pci_desc:
dpdk_nic_bind.dump_pci_description()
return
obj =CIfMap(map_driver.cfg_file);
if map_driver.args.create_interfaces is not None:
obj.do_create();
elif map_driver.args.interactive:
obj.do_interactive_create();
elif map_driver.args.linux:
obj.do_return_to_linux();
elif map_driver.parent_args is None or map_driver.parent_args.dump_interfaces is None:
ret = obj.do_run()
print('The ports are bound/configured.')
sys.exit(ret)
elif map_driver.parent_args.dump_interfaces:
obj.config_hugepages(1)
print('')
except DpdkSetup as e:
print(e)
sys.exit(-1)
except Exception:
traceback.print_exc()
sys.exit(-1)
except KeyboardInterrupt:
print('Ctrl+C')
sys.exit(-1)
if __name__ == '__main__':
main()
| 45.761612
| 203
| 0.575401
|
acfeeaf7ac308bbe453b24bcf9bee001b256b85e
| 8,498
|
py
|
Python
|
django/db/backends/postgresql_psycopg2/operations.py
|
jezdez-archive/django-old
|
9e28c4f4e90f8dfcfbb55bb13be437afb4f870e9
|
[
"BSD-3-Clause"
] | 1
|
2019-06-13T16:18:27.000Z
|
2019-06-13T16:18:27.000Z
|
django/db/backends/postgresql_psycopg2/operations.py
|
sirmmo/rango
|
9e28c4f4e90f8dfcfbb55bb13be437afb4f870e9
|
[
"BSD-3-Clause"
] | null | null | null |
django/db/backends/postgresql_psycopg2/operations.py
|
sirmmo/rango
|
9e28c4f4e90f8dfcfbb55bb13be437afb4f870e9
|
[
"BSD-3-Clause"
] | 1
|
2020-07-15T05:01:00.000Z
|
2020-07-15T05:01:00.000Z
|
from django.db.backends import BaseDatabaseOperations
class DatabaseOperations(BaseDatabaseOperations):
def __init__(self, connection):
super(DatabaseOperations, self).__init__(connection)
def date_extract_sql(self, lookup_type, field_name):
# http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
if lookup_type == 'week_day':
# For consistency across backends, we return Sunday=1, Saturday=7.
return "EXTRACT('dow' FROM %s) + 1" % field_name
else:
return "EXTRACT('%s' FROM %s)" % (lookup_type, field_name)
def date_interval_sql(self, sql, connector, timedelta):
"""
implements the interval functionality for expressions
format for Postgres:
(datefield + interval '3 days 200 seconds 5 microseconds')
"""
modifiers = []
if timedelta.days:
modifiers.append(u'%s days' % timedelta.days)
if timedelta.seconds:
modifiers.append(u'%s seconds' % timedelta.seconds)
if timedelta.microseconds:
modifiers.append(u'%s microseconds' % timedelta.microseconds)
mods = u' '.join(modifiers)
conn = u' %s ' % connector
return u'(%s)' % conn.join([sql, u'interval \'%s\'' % mods])
def date_trunc_sql(self, lookup_type, field_name):
# http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
return "DATE_TRUNC('%s', %s)" % (lookup_type, field_name)
def deferrable_sql(self):
return " DEFERRABLE INITIALLY DEFERRED"
def lookup_cast(self, lookup_type):
lookup = '%s'
# Cast text lookups to text to allow things like filter(x__contains=4)
if lookup_type in ('iexact', 'contains', 'icontains', 'startswith',
'istartswith', 'endswith', 'iendswith'):
lookup = "%s::text"
# Use UPPER(x) for case-insensitive lookups; it's faster.
if lookup_type in ('iexact', 'icontains', 'istartswith', 'iendswith'):
lookup = 'UPPER(%s)' % lookup
return lookup
def field_cast_sql(self, db_type):
if db_type == 'inet':
return 'HOST(%s)'
return '%s'
def last_insert_id(self, cursor, table_name, pk_name):
# Use pg_get_serial_sequence to get the underlying sequence name
# from the table name and column name (available since PostgreSQL 8)
cursor.execute("SELECT CURRVAL(pg_get_serial_sequence('%s','%s'))" % (
self.quote_name(table_name), pk_name))
return cursor.fetchone()[0]
def no_limit_value(self):
return None
def quote_name(self, name):
if name.startswith('"') and name.endswith('"'):
return name # Quoting once is enough.
return '"%s"' % name
def sql_flush(self, style, tables, sequences):
if tables:
# Perform a single SQL 'TRUNCATE x, y, z...;' statement. It allows
# us to truncate tables referenced by a foreign key in any other
# table.
sql = ['%s %s;' % \
(style.SQL_KEYWORD('TRUNCATE'),
style.SQL_FIELD(', '.join([self.quote_name(table) for table in tables]))
)]
# 'ALTER SEQUENCE sequence_name RESTART WITH 1;'... style SQL statements
# to reset sequence indices
for sequence_info in sequences:
table_name = sequence_info['table']
column_name = sequence_info['column']
if not (column_name and len(column_name) > 0):
# This will be the case if it's an m2m using an autogenerated
# intermediate table (see BaseDatabaseIntrospection.sequence_list)
column_name = 'id'
sql.append("%s setval(pg_get_serial_sequence('%s','%s'), 1, false);" % \
(style.SQL_KEYWORD('SELECT'),
style.SQL_TABLE(self.quote_name(table_name)),
style.SQL_FIELD(column_name))
)
return sql
else:
return []
def tablespace_sql(self, tablespace, inline=False):
if inline:
return "USING INDEX TABLESPACE %s" % self.quote_name(tablespace)
else:
return "TABLESPACE %s" % self.quote_name(tablespace)
def sequence_reset_sql(self, style, model_list):
from django.db import models
output = []
qn = self.quote_name
for model in model_list:
# Use `coalesce` to set the sequence for each model to the max pk value if there are records,
# or 1 if there are none. Set the `is_called` property (the third argument to `setval`) to true
# if there are records (as the max pk value is already in use), otherwise set it to false.
# Use pg_get_serial_sequence to get the underlying sequence name from the table name
# and column name (available since PostgreSQL 8)
for f in model._meta.local_fields:
if isinstance(f, models.AutoField):
output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" % \
(style.SQL_KEYWORD('SELECT'),
style.SQL_TABLE(qn(model._meta.db_table)),
style.SQL_FIELD(f.column),
style.SQL_FIELD(qn(f.column)),
style.SQL_FIELD(qn(f.column)),
style.SQL_KEYWORD('IS NOT'),
style.SQL_KEYWORD('FROM'),
style.SQL_TABLE(qn(model._meta.db_table))))
break # Only one AutoField is allowed per model, so don't bother continuing.
for f in model._meta.many_to_many:
if not f.rel.through:
output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" % \
(style.SQL_KEYWORD('SELECT'),
style.SQL_TABLE(qn(f.m2m_db_table())),
style.SQL_FIELD('id'),
style.SQL_FIELD(qn('id')),
style.SQL_FIELD(qn('id')),
style.SQL_KEYWORD('IS NOT'),
style.SQL_KEYWORD('FROM'),
style.SQL_TABLE(qn(f.m2m_db_table()))))
return output
def savepoint_create_sql(self, sid):
return "SAVEPOINT %s" % sid
def savepoint_commit_sql(self, sid):
return "RELEASE SAVEPOINT %s" % sid
def savepoint_rollback_sql(self, sid):
return "ROLLBACK TO SAVEPOINT %s" % sid
def prep_for_iexact_query(self, x):
return x
def check_aggregate_support(self, aggregate):
"""Check that the backend fully supports the provided aggregate.
The implementation of population statistics (STDDEV_POP and VAR_POP)
under Postgres 8.2 - 8.2.4 is known to be faulty. Raise
NotImplementedError if this is the database in use.
"""
if aggregate.sql_function in ('STDDEV_POP', 'VAR_POP'):
pg_version = self.connection.pg_version
if pg_version >= 80200 and pg_version <= 80204:
raise NotImplementedError('PostgreSQL 8.2 to 8.2.4 is known to have a faulty implementation of %s. Please upgrade your version of PostgreSQL.' % aggregate.sql_function)
def max_name_length(self):
"""
Returns the maximum length of an identifier.
Note that the maximum length of an identifier is 63 by default, but can
be changed by recompiling PostgreSQL after editing the NAMEDATALEN
macro in src/include/pg_config_manual.h .
This implementation simply returns 63, but can easily be overridden by a
custom database backend that inherits most of its behavior from this one.
"""
return 63
def last_executed_query(self, cursor, sql, params):
# http://initd.org/psycopg/docs/cursor.html#cursor.query
# The query attribute is a Psycopg extension to the DB API 2.0.
return cursor.query
def return_insert_id(self):
return "RETURNING %s", ()
def bulk_insert_sql(self, fields, num_values):
items_sql = "(%s)" % ", ".join(["%s"] * len(fields))
return "VALUES " + ", ".join([items_sql] * num_values)
| 44.031088
| 184
| 0.592375
|
acfeeca74ef7710d9287b7db68d6fedd46a4b53c
| 1,014
|
py
|
Python
|
main.py
|
seanwu1105/neural-network-sandbox
|
bebac433f1eb9aa16e17d13c6034319c1ee7fff4
|
[
"MIT"
] | 60
|
2019-08-06T23:59:20.000Z
|
2022-03-27T05:43:07.000Z
|
main.py
|
seanwu1105/neural-network-sandbox
|
bebac433f1eb9aa16e17d13c6034319c1ee7fff4
|
[
"MIT"
] | null | null | null |
main.py
|
seanwu1105/neural-network-sandbox
|
bebac433f1eb9aa16e17d13c6034319c1ee7fff4
|
[
"MIT"
] | 14
|
2019-09-17T12:34:55.000Z
|
2022-02-24T03:16:05.000Z
|
import os
import sys
import PyQt5.QtQml
import PyQt5.QtCore
import PyQt5.QtWidgets
from nn_sandbox.bridges import PerceptronBridge, MlpBridge, RbfnBridge, SomBridge
import nn_sandbox.backend.utils
if __name__ == '__main__':
os.environ['QT_QUICK_CONTROLS_STYLE'] = 'Default'
# XXX: Why I Have To Use QApplication instead of QGuiApplication? It seams
# QGuiApplication cannot load QML Chart libs!
app = PyQt5.QtWidgets.QApplication(sys.argv)
engine = PyQt5.QtQml.QQmlApplicationEngine()
bridges = {
'perceptronBridge': PerceptronBridge(),
'mlpBridge': MlpBridge(),
'rbfnBridge': RbfnBridge(),
'somBridge': SomBridge()
}
for name in bridges:
bridges[name].dataset_dict = nn_sandbox.backend.utils.read_data()
engine.rootContext().setContextProperty(name, bridges[name])
engine.load('./nn_sandbox/frontend/main.qml')
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
| 30.727273
| 82
| 0.680473
|
acfeecdc8cd22edefd9da9d34212d384d82e4cd9
| 1,287
|
py
|
Python
|
setup.py
|
xHossein/radiojavanapi
|
1ccf8af1e4c8688c10adbd56817b7da66d801712
|
[
"MIT"
] | 11
|
2021-02-08T10:04:49.000Z
|
2022-03-26T09:33:31.000Z
|
setup.py
|
xHossein/radiojavanapi
|
1ccf8af1e4c8688c10adbd56817b7da66d801712
|
[
"MIT"
] | 1
|
2022-02-07T15:28:40.000Z
|
2022-02-08T11:46:30.000Z
|
setup.py
|
xHossein/radiojavanapi
|
1ccf8af1e4c8688c10adbd56817b7da66d801712
|
[
"MIT"
] | 1
|
2022-03-26T09:39:09.000Z
|
2022-03-26T09:39:09.000Z
|
import pathlib
from setuptools import find_packages, setup
HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text(encoding='utf-8')
requirements = [
'requests==2.25.1',
'requests-toolbelt==0.9.1',
'PySocks==1.7.1',
'pydantic==1.8.1'
]
setup(
name='radiojavanapi',
version='0.2.2',
author='xHossein',
license='MIT',
url='https://github.com/xHossein/radiojavanapi',
install_requires=requirements,
keywords=['radiojavan private api','radiojavan-private-api','radiojavan api','radiojavan-api',
'rj api','rj-api','radiojavan','radio javan','radio-javan'
],
description='Fast and effective RadioJavan API Wrapper',
long_description=README,
long_description_content_type='text/markdown',
packages=find_packages(),
python_requires=">=3.7",
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
]
)
| 33
| 99
| 0.625486
|
acfeed0f955f52d38a5b4256129978a4d4a1892a
| 651
|
py
|
Python
|
sirbro_rest_example_cli/sirbro_app/api/apiv1.py
|
bboortz/sirbro
|
f0ea4d1dfba262ea8149dd7131a712255b2896ae
|
[
"Apache-2.0"
] | null | null | null |
sirbro_rest_example_cli/sirbro_app/api/apiv1.py
|
bboortz/sirbro
|
f0ea4d1dfba262ea8149dd7131a712255b2896ae
|
[
"Apache-2.0"
] | null | null | null |
sirbro_rest_example_cli/sirbro_app/api/apiv1.py
|
bboortz/sirbro
|
f0ea4d1dfba262ea8149dd7131a712255b2896ae
|
[
"Apache-2.0"
] | null | null | null |
from sirbro_app.appconfig import AppConfig
from sirbro_lib.logger import getLogger
from sirbro_lib.client import BaseClient
import urllib.request
LOGGER = getLogger('apiv1')
API_VERSION = "v1"
BASE_URL = "%s/%s" % (AppConfig.BASE_URL, API_VERSION)
class Client(BaseClient):
def __init__(self):
self.BASE_URL = "%s/%s" % (AppConfig.BASE_URL, API_VERSION)
def get_alive(self):
result = self.get_request("/alive")
return result
def get_info(self):
result = self.get_request("/info")
return result
def get_config(self):
result = self.get_request("/config")
return result
| 20.34375
| 67
| 0.674347
|
acfeed199af18df472a89ca1616664d925f4748d
| 88
|
py
|
Python
|
tutorials/alice_bob_lab/{{cookiecutter.repo_name}}/{{cookiecutter.model_name}}/__init__.py
|
modelyst/dbgen-model-template
|
39c3b84527bc4f01ea3f810d7873e6edf8f056c3
|
[
"Apache-2.0"
] | null | null | null |
tutorials/alice_bob_lab/{{cookiecutter.repo_name}}/{{cookiecutter.model_name}}/__init__.py
|
modelyst/dbgen-model-template
|
39c3b84527bc4f01ea3f810d7873e6edf8f056c3
|
[
"Apache-2.0"
] | null | null | null |
tutorials/alice_bob_lab/{{cookiecutter.repo_name}}/{{cookiecutter.model_name}}/__init__.py
|
modelyst/dbgen-model-template
|
39c3b84527bc4f01ea3f810d7873e6edf8f056c3
|
[
"Apache-2.0"
] | null | null | null |
"""{{cookiecutter.model_name}} DBGen Model"""
__version__ = "{{cookiecutter.version}}"
| 22
| 45
| 0.704545
|
acfeed927f907c32cb06a37ba956dd7b72d10a0f
| 7,173
|
py
|
Python
|
qvantum/check_circuit.py
|
vorpex/qvantum
|
07e9f749e0a6c9b2ffdfa3e562ca52f23bd4d2a8
|
[
"MIT"
] | 1
|
2019-05-13T06:28:25.000Z
|
2019-05-13T06:28:25.000Z
|
qvantum/check_circuit.py
|
vorpex/qvantum
|
07e9f749e0a6c9b2ffdfa3e562ca52f23bd4d2a8
|
[
"MIT"
] | null | null | null |
qvantum/check_circuit.py
|
vorpex/qvantum
|
07e9f749e0a6c9b2ffdfa3e562ca52f23bd4d2a8
|
[
"MIT"
] | null | null | null |
'''checking functions for circuit class'''
# pylint: disable=E1101, W1401
from . import layer
from . import register
def circuit_init_check(function):
"""Decorator to check the arguments of initialization function in circuit class.
Arguments:
function {} -- The tested function
"""
def wrapper(self, layer_list):
"""Method to initialize an instance of the Circuit class. The argument must be a list
of objects in the Layer class with the same size.
Arguments:
layer_list {list} -- List of objects from Layer class
Raises:
ValueError, TypeError
Examples:
>>> import qvantum
>>>
>>> l1 = qvantum.Layer([qvantum.Hadamard(), qvantum.Gate()])
>>> l2 = qvantum.Layer([qvantum.PauliY(), qvantum.PauliX()])
>>> c = qvantum.Circuit([l1, l2])
>>> c.get_layer_list()
OrderedDict([(0, <qvantum.layer.Layer at 0x27b474c2cf8>), (1, <qvantum.layer.Layer at 0x27b47bf2198>)])
>>> c.get_nth_layer(0)
<qvantum.layer.Layer at 0x27b474c2cf8>
"""
if isinstance(layer_list, list) \
and all(isinstance(elem, layer.Layer) for elem in layer_list):
return function(self, layer_list)
else:
raise TypeError('Invalid input! Argument must be a list of layer objects.')
return wrapper
def get_nth_layer_check(function):
"""Decorator to check the arguments of getting nth layer function.
Arguments:
function {} -- The tested function
"""
def wrapper(self, nth):
"""Method to return the n-th layer in the current Circuit object. The parameter must be
between 0 and the actual number of the layers.
Arguments:
nth {int} -- Number of nth possible layer
Raises:
TypeError
Examples:
>>> import qvantum
>>>
>>> l1 = qvantum.Layer([qvantum.Hadamard(), qvantum.Gate()])
>>> l2 = qvantum.Layer([qvantum.PauliY(), qvantum.PauliX()])
>>> c = qvantum.Circuit([l1, l2])
>>> c.get_layer_list()
OrderedDict([(0, <qvantum.layer.Layer at 0x27b474c2cf8>), (1, <qvantum.layer.Layer at 0x27b47bf2198>)])
>>> c.get_nth_layer(1)
<qvantum.layer.Layer at 0x27b47bf2198>
"""
if isinstance(nth, int):
return function(self, nth)
else:
raise TypeError('Invalid input! Argument must be integer.')
return wrapper
def delete_layer_check(function):
"""Decorator to check the arguments of deleting layer function.
Arguments:
function {} -- The tested function
"""
def wrapper(self, nth):
"""Method to delete the n-th layer from the current Circuit object. The parameter must
be equal to or bigger than 0 and less than the actual number of the layers in the Circuit.
Arguments:
nth {int} -- Number of layer to be deleted
Raises:
ValueError, TypeError
Examples:
>>> import qvantum
>>>
>>> l1 = qvantum.Layer([qvantum.Hadamard(), qvantum.Gate()])
>>> l2 = qvantum.Layer([qvantum.CNOT(1, 0)])
>>> c = qvantum.Circuit([l1, l2])
>>> c.get_layer_list()
OrderedDict([(0, <qvantum.layer.Layer at 0x27b47e65630>), (1, <qvantum.layer.Layer at 0x27b47e65cc0>)])
>>> c.delete_layer(0)
>>> c.get_layer_list()
OrderedDict([(0, <qvantum.layer.Layer at 0x27b47e65cc0>)])
"""
if isinstance(nth, int):
return function(self, nth)
else:
raise TypeError('Invalid input! Argument must be integer.')
return wrapper
def insert_layer_check(function):
"""Decorator to check the arguments of inserting layer function.
Arguments:
function {} -- The tested function
"""
def wrapper(self, l, nth):
"""Method to insert a Layer object into the n-th place in the current Circuit object. The
first parameter must be a Layer object while the second parameter must be equal to or
bigger than 0 and equal to or less than the actual size of the layers in the Circuit. The
size of the Layer object must be equal to the size of the already used Layers in the
Circuit.
Arguments:
l {layer} -- Layer to be inserted
nth {int} -- Index where the layer to be inserted
Raises:
ValueError, TypeError
Examples:
>>> import qvantum
>>>
>>> l1 = qvantum.Layer([qvantum.Hadamard(), qvantum.Gate()])
>>> l2 = qvantum.Layer([qvantum.CNOT(1, 0)])
>>> c = qvantum.Circuit([l1, l2])
>>> c.get_layer_list()
OrderedDict([(0, <qvantum.layer.Layer at 0x27b47de9898>), (1, <qvantum.layer.Layer at 0x27b47de9550>)])
>>> l3 = qvantum.Layer([qvantum.Swap()])
>>> c.insert_layer(l3, 1)
>>> c.get_layer_list()
OrderedDict([(0, <qvantum.layer.Layer at 0x27b47de9898>), (1, <qvantum.layer.Layer at 0x27b47e5dc50>), (2, <qvantum.layer.Layer at 0x27b47de9550>)])
"""
if isinstance(l, layer.Layer) and isinstance(nth, int):
return function(self, l, nth)
else:
raise TypeError('Invalid input! Argument must be a pair of layer object and integer.')
return wrapper
def run_check(function):
"""Decorator to check the arguments of running circuit function.
Arguments:
function {} -- The tested function
"""
def wrapper(self, r):
"""Method to perform the computational process on a Register object as input and returns
the result. The size of the Register object and the size of the Circuit object must be
equal.
Arguments:
r {register} -- Register which the circuit is applied on
Raises:
ValueError, TypeError
Examples:
>>> import qvantum
>>>
>>> q1 = qvantum.Random_Qubit()
>>> q2 = qvantum.Random_Qubit()
>>> r = qvantum.Register([q1, q2])
>>> r.show()
'|Ψ> = (-0.8867+0.1861i)|00> + (-0.2437-0.1838i)|01> + (0.2726+0.0534i)|10> + (0.0469+0.0810i)|11>'
>>> l1 = qvantum.Layer([qvantum.Hadamard(), qvantum.Gate()])
>>> l2 = qvantum.Layer([qvantum.CNOT(1, 0)])
>>> c = qvantum.Circuit([l1, l2])
>>> c.run(r)
>>> r.show()
'|Ψ> = (-0.4342+0.1693i)|00> + (-0.2054-0.1873i)|01> + (-0.8198+0.0938i)|10> + (-0.1392-0.0727i)|11>'
"""
if isinstance(r, register.Register):
return function(self, r)
else:
raise TypeError('Invalid input! Argument must be a register object.')
return wrapper
| 34.990244
| 160
| 0.557786
|
acfeee0de2ebf2f9d0b4d6b633b072daed8e9128
| 1,174
|
py
|
Python
|
make_static_dyno.py
|
DynoBits/generate-bitbirds
|
9443f32be90925a0b791989e67e2acf7fa733da9
|
[
"MIT"
] | 3
|
2021-08-06T17:22:10.000Z
|
2022-03-18T12:55:46.000Z
|
make_static_dyno.py
|
DynoBits/generate-bitbirds
|
9443f32be90925a0b791989e67e2acf7fa733da9
|
[
"MIT"
] | null | null | null |
make_static_dyno.py
|
DynoBits/generate-bitbirds
|
9443f32be90925a0b791989e67e2acf7fa733da9
|
[
"MIT"
] | 3
|
2021-03-26T18:02:41.000Z
|
2021-11-16T09:51:24.000Z
|
import dyno_colors as dc
from dyno_bit import DynoBit
from dyno_gif import make_temp_file_names, remove_temp_files, save_dyno_gif
# For random list choice
from random import choice
# Set save_dyno to false if random needed - debugging gif generation script
def make_static_dyno(gif_name, dyno=DynoBit(), static_color_list=None, save_dyno=True):
frame_count = 10
temp_file_names = make_temp_file_names(frame_count, "temp_static")
background_color_index_list = dyno.get_background_index_list()
dyno_pixels = dyno.pixels()
# Change backgroud color based on activity if not supplied
if static_color_list == None:
if dyno.activity == "Diurnal":
static_color_list = dc.COLOR_LIST_LIGHT_GREYS
if dyno.activity == "Nocturnal":
static_color_list = dc.COLOR_LIST_DARK_GREYS
# Apply power and write temp dyno images
for file in temp_file_names:
for i in background_color_index_list:
dyno_pixels[i] = choice(static_color_list)
dyno.save_dyno_image(dyno_pixels, file)
if save_dyno:
save_dyno_gif(gif_name, temp_file_names, bounce=False, fps=25)
remove_temp_files(temp_file_names)
| 34.529412
| 87
| 0.752981
|
acfeee31d618c33c81d07bad08baa36537302197
| 11,798
|
py
|
Python
|
kinova_demo/nodes/kinova_demo/robot_control_modules.py
|
Aachen-Armchair-Engineers/kinova-ros
|
8735e8a964df7836855e9b1b128e1d7a6134af4e
|
[
"BSD-3-Clause"
] | null | null | null |
kinova_demo/nodes/kinova_demo/robot_control_modules.py
|
Aachen-Armchair-Engineers/kinova-ros
|
8735e8a964df7836855e9b1b128e1d7a6134af4e
|
[
"BSD-3-Clause"
] | null | null | null |
kinova_demo/nodes/kinova_demo/robot_control_modules.py
|
Aachen-Armchair-Engineers/kinova-ros
|
8735e8a964df7836855e9b1b128e1d7a6134af4e
|
[
"BSD-3-Clause"
] | null | null | null |
#!/usr/bin/env python3
"""A set of example functions that can be used to control the arm"""
import rospy
import actionlib
import kinova_msgs.msg
import geometry_msgs.msg
import tf
import std_msgs.msg
import math
import thread
from kinova_msgs.srv import *
from sensor_msgs.msg import JointState
import argparse
def argumentParser(argument):
""" Argument parser """
parser = argparse.ArgumentParser(description='Drive robot joint to command position')
parser.add_argument('kinova_robotType', metavar='kinova_robotType', type=str, default='j2n6a300',
help='kinova_RobotType is in format of: [{j|m|r|c}{1|2}{s|n}{4|6|7}{s|a}{2|3}{0}{0}]. eg: j2n6a300 refers to jaco v2 6DOF assistive 3fingers. Please be noted that not all options are valided for different robot types.')
args_ = parser.parse_args(argument)
prefix = args_.kinova_robotType + "_"
nbJoints = int(args_.kinova_robotType[3])
return prefix, nbJoints
def joint_position_client(angle_set, prefix):
action_address = '/' + prefix + 'driver/joints_action/joint_angles'
client = actionlib.SimpleActionClient(action_address,
kinova_msgs.msg.ArmJointAnglesAction)
client.wait_for_server()
goal = kinova_msgs.msg.ArmJointAnglesGoal()
goal.angles.joint1 = angle_set[0]
goal.angles.joint2 = angle_set[1]
goal.angles.joint3 = angle_set[2]
goal.angles.joint4 = angle_set[3]
goal.angles.joint5 = angle_set[4]
goal.angles.joint6 = angle_set[5]
goal.angles.joint7 = angle_set[6]
client.send_goal(goal)
client.wait_for_result(rospy.Duration(100.0))
# Prints out the result of executing the action
return client.get_result()
def cartesian_pose_client(position, orientation, prefix):
"""Send a cartesian goal to the action server."""
action_address = '/' + prefix + 'driver/pose_action/tool_pose'
client = actionlib.SimpleActionClient(action_address, kinova_msgs.msg.ArmPoseAction)
client.wait_for_server()
goal = kinova_msgs.msg.ArmPoseGoal()
goal.pose.header = std_msgs.msg.Header(frame_id=(prefix + 'link_base'))
goal.pose.pose.position = geometry_msgs.msg.Point(
x=position[0], y=position[1], z=position[2])
goal.pose.pose.orientation = geometry_msgs.msg.Quaternion(
x=orientation[0], y=orientation[1], z=orientation[2], w=orientation[3])
print('goal.pose in client 1: {}'.format(goal.pose.pose)) # debug
client.send_goal(goal)
if client.wait_for_result(rospy.Duration(200.0)):
return client.get_result()
else:
client.cancel_all_goals()
print(' the cartesian action timed-out')
return None
def gripper_client(finger_positions, prefix):
"""Send a gripper goal to the action server."""
action_address = '/' + prefix + 'driver/fingers_action/finger_positions'
client = actionlib.SimpleActionClient(action_address,
kinova_msgs.msg.SetFingersPositionAction)
client.wait_for_server()
goal = kinova_msgs.msg.SetFingersPositionGoal()
goal.fingers.finger1 = float(finger_positions[0])
goal.fingers.finger2 = float(finger_positions[1])
goal.fingers.finger3 = float(finger_positions[2])
client.send_goal(goal)
if client.wait_for_result(rospy.Duration(50.0)):
return client.get_result()
else:
client.cancel_all_goals()
rospy.logwarn(' the gripper action timed-out')
return None
def homeRobot(prefix):
service_address = '/' + prefix + 'driver/in/home_arm'
rospy.wait_for_service(service_address)
try:
home = rospy.ServiceProxy(service_address, HomeArm)
home()
return None
except rospy.ServiceException, e:
print ("Service call failed: %s"%e)
def activateNullSpaceMode(duration_sec, prefix):
service_address = '/' + prefix + 'driver/in/set_null_space_mode_state'
rospy.wait_for_service(service_address)
try:
SetNullSpaceMode = rospy.ServiceProxy(service_address, SetNullSpaceModeState)
SetNullSpaceMode(1)
except rospy.ServiceException, e:
print ("Service call failed: %s"%e)
rospy.sleep(duration_sec)
try:
SetNullSpaceMode(0)
return None
except rospy.ServiceException, e:
print ("Service call failed: %s"%e)
def publishVelCmd(jointCmds, duration_sec, prefix):
#subscriber to get feedback
topic_name = '/' + prefix + 'driver/out/joint_state'
max_error = [0,0,0,0,0,0,0]
counter = [0]
sub = rospy.Subscriber(topic_name, JointState, getFeedbackCallback, (jointCmds,'velocity',max_error,counter))
topic_name = '/' + prefix + 'driver/in/joint_velocity'
pub = rospy.Publisher(topic_name, kinova_msgs.msg.JointVelocity, queue_size=1)
jointCmd = kinova_msgs.msg.JointVelocity()
jointCmd.joint1 = jointCmds[0];
jointCmd.joint2 = jointCmds[1];
jointCmd.joint3 = jointCmds[2];
jointCmd.joint4 = jointCmds[3];
jointCmd.joint5 = jointCmds[4];
jointCmd.joint6 = jointCmds[5];
jointCmd.joint7 = jointCmds[6];
joint_cmd_for_error_comp = jointCmd
count = 0
rate = rospy.Rate(100)
L = []
thread.start_new_thread(input_thread, (L,))
while (count < 100*duration_sec):
count = count + 1
#rospy.loginfo("I will publish to the topic %d", count)
pub.publish(jointCmd)
rate.sleep()
if L:
break
sub.unregister()
print ("max error %f %f %f %f %f %f %f" %(max_error[0], max_error[1], max_error[2], max_error[3], max_error[4], max_error[5], max_error[6]))
def publishCatesianVelocityCommands(cartVel, duration_sec, prefix):
topic_name = '/' + prefix + 'driver/in/cartesian_velocity'
#publish joint torque commands
pub = rospy.Publisher(topic_name, kinova_msgs.msg.PoseVelocity, queue_size=1)
poseVelCmd = kinova_msgs.msg.PoseVelocity()
poseVelCmd.twist_linear_x = cartVel[0];
poseVelCmd.twist_linear_y = cartVel[1];
poseVelCmd.twist_linear_z = cartVel[2];
poseVelCmd.twist_angular_x = cartVel[3];
poseVelCmd.twist_angular_y = cartVel[4];
poseVelCmd.twist_angular_z = cartVel[5];
count = 0
rate = rospy.Rate(100)
while (count < 100*duration_sec):
count = count + 1
pub.publish(poseVelCmd)
rate.sleep()
def publishForceCmd(force_cmds, duration_sec, prefix):
#use service to set torque control parameters
service_address = '/' + prefix + 'driver/in/set_torque_control_parameters'
rospy.wait_for_service(service_address)
try:
setTorqueParameters = rospy.ServiceProxy(service_address, SetTorqueControlParameters)
setTorqueParameters()
except rospy.ServiceException, e:
print ("Service call failed: %s"%e)
return None
#use service to switch to torque control
service_address = '/' + prefix + 'driver/in/set_torque_control_mode'
rospy.wait_for_service(service_address)
try:
switchTorquemode = rospy.ServiceProxy(service_address, SetTorqueControlMode)
switchTorquemode(1)
except rospy.ServiceException, e:
print ("Service call failed: %s"%e)
return None
#publish joint torque commands
topic_name = '/' + prefix + 'driver/in/cartesian_force'
pub = rospy.Publisher(topic_name, kinova_msgs.msg.CartesianForce, queue_size=1)
force = kinova_msgs.msg.CartesianForce()
force.force_x = force_cmds[0];
force.force_y = force_cmds[1];
force.force_z = force_cmds[2];
force.torque_x = force_cmds[3];
force.torque_y = force_cmds[4];
force.torque_z = force_cmds[5];
count = 0
rate = rospy.Rate(100)
L = []
thread.start_new_thread(input_thread, (L,))
while (count < 100*duration_sec):
count = count + 1
pub.publish(force)
rate.sleep()
if L: break
#use service to switch to position control
try:
switchTorquemode(0)
return None
except rospy.ServiceException, e:
print ("Service call failed: %s"%e)
return None
def publishTorqueCmd(jointCmds, duration_sec, prefix):
#use service to set torque control parameters
service_address = '/' + prefix + 'driver/in/set_torque_control_parameters'
rospy.wait_for_service(service_address)
try:
setTorqueParameters = rospy.ServiceProxy(service_address, SetTorqueControlParameters)
setTorqueParameters()
except rospy.ServiceException, e:
print ("Service call failed: %s"%e)
return None
#use service to switch to torque control
service_address = '/' + prefix + 'driver/in/set_torque_control_mode'
rospy.wait_for_service(service_address)
try:
switchTorquemode = rospy.ServiceProxy(service_address, SetTorqueControlMode)
switchTorquemode(1)
except rospy.ServiceException, e:
print ("Service call failed: %s"%e)
return None
#subscriber to get feedback
topic_name = '/' + prefix + 'driver/out/joint_state'
max_error = [0,0,0,0,0,0,0]
counter = [0]
sub = rospy.Subscriber(topic_name, JointState, getFeedbackCallback, (jointCmds,'torque',max_error,counter))
#publish joint torque commands
topic_name = '/' + prefix + 'driver/in/joint_torque'
pub = rospy.Publisher(topic_name, kinova_msgs.msg.JointTorque, queue_size=1)
jointCmd = kinova_msgs.msg.JointTorque()
jointCmd.joint1 = jointCmds[0];
jointCmd.joint2 = jointCmds[1];
jointCmd.joint3 = jointCmds[2];
jointCmd.joint4 = jointCmds[3];
jointCmd.joint5 = jointCmds[4];
jointCmd.joint6 = jointCmds[5];
jointCmd.joint7 = jointCmds[6];
count = 0
rate = rospy.Rate(100)
L = []
thread.start_new_thread(input_thread, (L,))
while (count<100*duration_sec):
pub.publish(jointCmd)
count = count + 1
rate.sleep()
if L: break
sub.unregister()
print ("max error %f %f %f %f %f %f %f" %(max_error[0], max_error[1], max_error[2], max_error[3], max_error[4], max_error[5], max_error[6]))
#use service to switch to position control
try:
switchTorquemode(0)
return None
except rospy.ServiceException, e:
print ("Service call failed: %s"%e)
return None
def ZeroTorque(prefix):
#move robot to candle like pose
#result = joint_position_client([180]*7)
print ("torque before setting zero")
topic_name = '/' + prefix + 'driver/out/joint_torques'
sub_once = rospy.Subscriber(topic_name, kinova_msgs.msg.JointAngles, printTorqueVaules)
rospy.wait_for_message(topic_name, kinova_msgs.msg.JointAngles, timeout=2)
sub_once.unregister()
#call zero torque
service_address = '/' + prefix + 'driver/in/set_zero_torques'
rospy.wait_for_service(service_address)
try:
zeroTorques = rospy.ServiceProxy(service_address, ZeroTorques)
zeroTorques()
except rospy.ServiceException, e:
print ("Service call failed: %s"%e)
return None
rospy.sleep(0.5)
print ("torque after setting zero")
sub_once = rospy.Subscriber(topic_name, kinova_msgs.msg.JointAngles, printTorqueVaules)
rospy.wait_for_message(topic_name, kinova_msgs.msg.JointAngles, timeout=2)
sub_once.unregister()
def printTorqueVaules(torques):
print ("Torque - {}, {}, {}, {}, {}, {}, {}".format(torques.joint1,
torques.joint2, torques.joint3, torques.joint4,
torques.joint5, torques.joint6, torques.joint7))
def input_thread(L):
raw_input("Press return to return to position control mode")
L.append(None)
def getFeedbackCallback(data,args):
#generic but joint_state/effort is not published by kinova_driver
joint_cmd = args[0]
error_type = args[1]
max_error = args[2]
count = args[3]
for i in range(0,len(joint_cmd)):
if error_type == 'velocity':
error = abs(joint_cmd[i] - data.velocity[i]*180/3.1415)
if error_type == 'torque':
error = abs(joint_cmd[i] - data.effort[i])
if count[0]>50:
max_error[i] = max(error,max_error[i])
count[0] = count[0] +1
| 34.905325
| 243
| 0.699525
|
acfeee438d066d2e298abfec68cf84d1a54d5b29
| 15,396
|
py
|
Python
|
horizon/openstack_dashboard/usage/quotas.py
|
sreenathmenon/openstackTFA
|
8c765f2728b82cf78c4d2bfd5c6a36ebf9302f2b
|
[
"Apache-2.0"
] | null | null | null |
horizon/openstack_dashboard/usage/quotas.py
|
sreenathmenon/openstackTFA
|
8c765f2728b82cf78c4d2bfd5c6a36ebf9302f2b
|
[
"Apache-2.0"
] | null | null | null |
horizon/openstack_dashboard/usage/quotas.py
|
sreenathmenon/openstackTFA
|
8c765f2728b82cf78c4d2bfd5c6a36ebf9302f2b
|
[
"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.
from collections import defaultdict
import itertools
import logging
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon.utils.memoized import memoized # noqa
from openstack_dashboard.api import base
from openstack_dashboard.api import cinder
from openstack_dashboard.api import network
from openstack_dashboard.api import neutron
from openstack_dashboard.api import nova
from openstack_dashboard import policy
LOG = logging.getLogger(__name__)
NOVA_QUOTA_FIELDS = ("metadata_items",
"cores",
"instances",
"injected_files",
"injected_file_content_bytes",
"ram",
"floating_ips",
"fixed_ips",
"security_groups",
"security_group_rules",)
MISSING_QUOTA_FIELDS = ("key_pairs",
"injected_file_path_bytes",)
CINDER_QUOTA_FIELDS = ("volumes",
"snapshots",
"gigabytes",)
NEUTRON_QUOTA_FIELDS = ("network",
"subnet",
"port",
"router",
"floatingip",
"security_group",
"security_group_rule",
)
QUOTA_FIELDS = NOVA_QUOTA_FIELDS + CINDER_QUOTA_FIELDS + NEUTRON_QUOTA_FIELDS
QUOTA_NAMES = {
"metadata_items": _('Metadata Items'),
"cores": _('VCPUs'),
"instances": _('Instances'),
"injected_files": _('Injected Files'),
"injected_file_content_bytes": _('Injected File Content Bytes'),
"ram": _('RAM (MB)'),
"floating_ips": _('Floating IPs'),
"fixed_ips": _('Fixed IPs'),
"security_groups": _('Security Groups'),
"security_group_rules": _('Security Group Rules'),
"key_pairs": _('Key Pairs'),
"injected_file_path_bytes": _('Injected File Path Bytes'),
"volumes": _('Volumes'),
"snapshots": _('Volume Snapshots'),
"gigabytes": _('Total Size of Volumes and Snapshots (GB)'),
"network": _("Networks"),
"subnet": _("Subnets"),
"port": _("Ports"),
"router": _("Routers"),
"floatingip": _('Floating IPs'),
"security_group": _("Security Groups"),
"security_group_rule": _("Security Group Rules")
}
class QuotaUsage(dict):
"""Tracks quota limit, used, and available for a given set of quotas."""
def __init__(self):
self.usages = defaultdict(dict)
def __contains__(self, key):
return key in self.usages
def __getitem__(self, key):
return self.usages[key]
def __setitem__(self, key, value):
raise NotImplementedError("Directly setting QuotaUsage values is not "
"supported. Please use the add_quota and "
"tally methods.")
def __repr__(self):
return repr(dict(self.usages))
def get(self, key, default=None):
return self.usages.get(key, default)
def add_quota(self, quota):
"""Adds an internal tracking reference for the given quota."""
if quota.limit is None or quota.limit == -1:
# Handle "unlimited" quotas.
self.usages[quota.name]['quota'] = float("inf")
self.usages[quota.name]['available'] = float("inf")
else:
self.usages[quota.name]['quota'] = int(quota.limit)
def tally(self, name, value):
"""Adds to the "used" metric for the given quota."""
value = value or 0 # Protection against None.
# Start at 0 if this is the first value.
if 'used' not in self.usages[name]:
self.usages[name]['used'] = 0
# Increment our usage and update the "available" metric.
self.usages[name]['used'] += int(value) # Fail if can't coerce to int.
self.update_available(name)
def update_available(self, name):
"""Updates the "available" metric for the given quota."""
available = self.usages[name]['quota'] - self.usages[name]['used']
if available < 0:
available = 0
self.usages[name]['available'] = available
def _get_quota_data(request, method_name, disabled_quotas=None,
tenant_id=None):
quotasets = []
if not tenant_id:
tenant_id = request.user.tenant_id
quotasets.append(getattr(nova, method_name)(request, tenant_id))
qs = base.QuotaSet()
if disabled_quotas is None:
disabled_quotas = get_disabled_quotas(request)
if 'volumes' not in disabled_quotas:
try:
quotasets.append(getattr(cinder, method_name)(request, tenant_id))
except cinder.ClientException:
disabled_quotas.extend(CINDER_QUOTA_FIELDS)
msg = _("Unable to retrieve volume limit information.")
exceptions.handle(request, msg)
for quota in itertools.chain(*quotasets):
if quota.name not in disabled_quotas:
qs[quota.name] = quota.limit
return qs
def get_default_quota_data(request, disabled_quotas=None, tenant_id=None):
return _get_quota_data(request,
"default_quota_get",
disabled_quotas=disabled_quotas,
tenant_id=tenant_id)
def get_tenant_quota_data(request, disabled_quotas=None, tenant_id=None):
qs = _get_quota_data(request,
"tenant_quota_get",
disabled_quotas=disabled_quotas,
tenant_id=tenant_id)
# TODO(jpichon): There is no API to get the default system quotas
# in Neutron (cf. LP#1204956), so for now handle tenant quotas here.
# This should be handled in _get_quota_data() eventually.
if not disabled_quotas:
return qs
# Check if neutron is enabled by looking for network and router
if 'network' and 'router' not in disabled_quotas:
tenant_id = tenant_id or request.user.tenant_id
neutron_quotas = neutron.tenant_quota_get(request, tenant_id)
if 'floating_ips' in disabled_quotas:
# Neutron with quota extension disabled
if 'floatingip' in disabled_quotas:
qs.add(base.QuotaSet({'floating_ips': -1}))
# Neutron with quota extension enabled
else:
# Rename floatingip to floating_ips since that's how it's
# expected in some places (e.g. Security & Access' Floating IPs)
fips_quota = neutron_quotas.get('floatingip').limit
qs.add(base.QuotaSet({'floating_ips': fips_quota}))
if 'security_groups' in disabled_quotas:
if 'security_group' in disabled_quotas:
qs.add(base.QuotaSet({'security_groups': -1}))
# Neutron with quota extension enabled
else:
# Rename security_group to security_groups since that's how it's
# expected in some places (e.g. Security & Access' Security Groups)
sec_quota = neutron_quotas.get('security_group').limit
qs.add(base.QuotaSet({'security_groups': sec_quota}))
if 'network' in disabled_quotas:
for item in qs.items:
if item.name == 'networks':
qs.items.remove(item)
break
else:
net_quota = neutron_quotas.get('network').limit
qs.add(base.QuotaSet({'networks': net_quota}))
if 'subnet' in disabled_quotas:
for item in qs.items:
if item.name == 'subnets':
qs.items.remove(item)
break
else:
net_quota = neutron_quotas.get('subnet').limit
qs.add(base.QuotaSet({'subnets': net_quota}))
if 'router' in disabled_quotas:
for item in qs.items:
if item.name == 'routers':
qs.items.remove(item)
break
else:
router_quota = neutron_quotas.get('router').limit
qs.add(base.QuotaSet({'routers': router_quota}))
return qs
def get_disabled_quotas(request):
disabled_quotas = []
# Cinder
if not base.is_service_enabled(request, 'volume'):
disabled_quotas.extend(CINDER_QUOTA_FIELDS)
# Neutron
if not base.is_service_enabled(request, 'network'):
disabled_quotas.extend(NEUTRON_QUOTA_FIELDS)
else:
# Remove the nova network quotas
disabled_quotas.extend(['floating_ips', 'fixed_ips'])
if neutron.is_extension_supported(request, 'security-group'):
# If Neutron security group is supported, disable Nova quotas
disabled_quotas.extend(['security_groups', 'security_group_rules'])
else:
# If Nova security group is used, disable Neutron quotas
disabled_quotas.extend(['security_group', 'security_group_rule'])
try:
if not neutron.is_quotas_extension_supported(request):
disabled_quotas.extend(NEUTRON_QUOTA_FIELDS)
except Exception:
LOG.exception("There was an error checking if the Neutron "
"quotas extension is enabled.")
return disabled_quotas
def _get_tenant_compute_usages(request, usages, disabled_quotas, tenant_id):
if tenant_id:
# determine if the user has permission to view across projects
# there are cases where an administrator wants to check the quotas
# on a project they are not scoped to
all_tenants = policy.check((("compute", "compute:get_all_tenants"),),
request)
instances, has_more = nova.server_list(
request, search_opts={'tenant_id': tenant_id},
all_tenants=all_tenants)
else:
instances, has_more = nova.server_list(request)
# Fetch deleted flavors if necessary.
flavors = dict([(f.id, f) for f in nova.flavor_list(request)])
missing_flavors = [instance.flavor['id'] for instance in instances
if instance.flavor['id'] not in flavors]
for missing in missing_flavors:
if missing not in flavors:
try:
flavors[missing] = nova.flavor_get(request, missing)
except Exception:
flavors[missing] = {}
exceptions.handle(request, ignore=True)
usages.tally('instances', len(instances))
# Sum our usage based on the flavors of the instances.
for flavor in [flavors[instance.flavor['id']] for instance in instances]:
usages.tally('cores', getattr(flavor, 'vcpus', None))
usages.tally('ram', getattr(flavor, 'ram', None))
# Initialise the tally if no instances have been launched yet
if len(instances) == 0:
usages.tally('cores', 0)
usages.tally('ram', 0)
def _get_tenant_network_usages(request, usages, disabled_quotas, tenant_id):
floating_ips = []
try:
if network.floating_ip_supported(request):
floating_ips = network.tenant_floating_ip_list(request)
except Exception:
pass
usages.tally('floating_ips', len(floating_ips))
if 'security_group' not in disabled_quotas:
security_groups = []
security_groups = network.security_group_list(request)
usages.tally('security_groups', len(security_groups))
if 'network' not in disabled_quotas:
networks = []
networks = neutron.network_list(request, shared=False)
if tenant_id:
networks = filter(lambda net: net.tenant_id == tenant_id, networks)
usages.tally('networks', len(networks))
if 'subnet' not in disabled_quotas:
subnets = []
subnets = neutron.subnet_list(request)
usages.tally('subnets', len(subnets))
if 'router' not in disabled_quotas:
routers = []
routers = neutron.router_list(request)
if tenant_id:
routers = filter(lambda rou: rou.tenant_id == tenant_id, routers)
usages.tally('routers', len(routers))
def _get_tenant_volume_usages(request, usages, disabled_quotas, tenant_id):
if 'volumes' not in disabled_quotas:
try:
if tenant_id:
opts = {'all_tenants': 1, 'project_id': tenant_id}
volumes = cinder.volume_list(request, opts)
snapshots = cinder.volume_snapshot_list(request, opts)
else:
volumes = cinder.volume_list(request)
snapshots = cinder.volume_snapshot_list(request)
usages.tally('gigabytes', sum([int(v.size) for v in volumes]))
usages.tally('volumes', len(volumes))
usages.tally('snapshots', len(snapshots))
except cinder.ClientException:
msg = _("Unable to retrieve volume limit information.")
exceptions.handle(request, msg)
@memoized
def tenant_quota_usages(request, tenant_id=None):
"""Get our quotas and construct our usage object.
If no tenant_id is provided, a the request.user.project_id
is assumed to be used
"""
if not tenant_id:
tenant_id = request.user.project_id
disabled_quotas = get_disabled_quotas(request)
usages = QuotaUsage()
for quota in get_tenant_quota_data(request,
disabled_quotas=disabled_quotas,
tenant_id=tenant_id):
usages.add_quota(quota)
# Get our usages.
_get_tenant_compute_usages(request, usages, disabled_quotas, tenant_id)
_get_tenant_network_usages(request, usages, disabled_quotas, tenant_id)
_get_tenant_volume_usages(request, usages, disabled_quotas, tenant_id)
return usages
def tenant_limit_usages(request):
# TODO(licostan): This method shall be removed from Quota module.
# ProjectUsage/BaseUsage maybe used instead on volume/image dashboards.
limits = {}
try:
limits.update(nova.tenant_absolute_limits(request))
except Exception:
msg = _("Unable to retrieve compute limit information.")
exceptions.handle(request, msg)
if base.is_service_enabled(request, 'volume'):
try:
limits.update(cinder.tenant_absolute_limits(request))
volumes = cinder.volume_list(request)
snapshots = cinder.volume_snapshot_list(request)
# gigabytesUsed should be a total of volumes and snapshots
vol_size = sum([getattr(volume, 'size', 0) for volume
in volumes])
snap_size = sum([getattr(snap, 'size', 0) for snap
in snapshots])
limits['gigabytesUsed'] = vol_size + snap_size
limits['volumesUsed'] = len(volumes)
limits['snapshotsUsed'] = len(snapshots)
except cinder.ClientException:
msg = _("Unable to retrieve volume limit information.")
exceptions.handle(request, msg)
return limits
| 38.014815
| 79
| 0.627631
|
acfef01d7dcdcc7d172aa11d28e11dce2af05fa4
| 12,355
|
py
|
Python
|
swarm_search/src/ground_station_6_SIP.py
|
acr-iitkgp/swarm_search
|
3857edde0238c2f5d83a33c8969e6e3e3b9a3dcf
|
[
"MIT"
] | 6
|
2020-01-07T15:45:14.000Z
|
2021-06-19T12:14:20.000Z
|
swarm_search/src/ground_station_6_SIP.py
|
manthan99/swarm_search
|
3857edde0238c2f5d83a33c8969e6e3e3b9a3dcf
|
[
"MIT"
] | null | null | null |
swarm_search/src/ground_station_6_SIP.py
|
manthan99/swarm_search
|
3857edde0238c2f5d83a33c8969e6e3e3b9a3dcf
|
[
"MIT"
] | 3
|
2020-04-21T06:29:26.000Z
|
2020-11-23T05:39:41.000Z
|
from math import sin, cos, sqrt, atan2, radians
import copy
import matplotlib.pyplot as plt
import rospy
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import Pose2D
from swarm_search.msg import sip_goal2
from nav_msgs.msg import Odometry
from mavros_msgs.msg import State
from mavros_msgs.msg import PositionTarget
from mavros_msgs.msg import GlobalPositionTarget
from sensor_msgs.msg import NavSatFix
R1 = 6373000
sip_const = 3.0 # depends on the height and FOV of the camera
input_square = [[22.32175109,87.3048497], [22.3218015, 87.3052322], [22.3221194, 87.3051769], [22.3220840, 87.3047923]]
global drone_input
global drone_start
drone_input = [[22.3217391,87.3049194],[22.3217391,87.3049185],[22.3217391,87.3049154],[22.3217391,87.3049123]]
drone_start = drone_input[0]
global connected0
global armed0
global state0
global connected1
global armed1
global state1
global connected2
global armed2
global state2
global connected3
global armed3
global state3
global start_time
global i
i = 0
global j
j = 0
global target_0
global target_1
global target_2
global target_3
target_0 = sip_goal2()
target_1 = sip_goal2()
target_2 = sip_goal2()
target_3 = sip_goal2()
###############################
connected0 = 1
connected1 = 1
connected2 = 1
connected3 = 1
armed0 = 1
armed1 = 1
armed2 = 1
armed3 = 1
###############################
def gps_corner_sort(input_square, drone_start):
"""
Code returns a list containing the sorted gps coordinates from drone 0
Input the 4 gps vertices and the gps coordinates of drone 0
"""
sorted_gps = []
new_list = []
for i in range(0, len(input_square)):
sorted_gps.append(gps_dist(drone_start[0], drone_start[1], input_square[i][0], input_square[i][1]))
sorted_gps_m = copy.deepcopy(sorted_gps)
while sorted_gps_m:
minimum = sorted_gps_m[0]
j = 0
for i in range(0, len(sorted_gps_m)):
if sorted_gps_m[i] < minimum:
minimum = sorted_gps_m[i]
j = sorted_gps.index(minimum)
new_list.append(input_square[j])
sorted_gps_m.remove(minimum)
return(new_list)
def coordinate_axes(isl):
"""
returns the origin, x axes, y axes and vertice distance of the local coordinate system
Input is sorted list of gps vertices
"""
x = [0, 0]
y = [0, 0]
dist1 = gps_dist(isl[0][0], isl[0][1], isl[1][0], isl[1][1])
dist2 = gps_dist(isl[0][0], isl[0][1], isl[2][0], isl[2][1])
origin = isl[0]
x[0] = (isl[1][0] - isl[0][0]) / dist1
x[1] = (isl[1][1] - isl[0][1]) / dist1
y[0] = (isl[2][0] - isl[0][0]) / dist2
y[1] = (isl[2][1] - isl[0][1]) / dist2
return(origin, x, y, dist1)
def transform_to_gps(point, origin, x, y):
"""
Transforms the input point from the local frame to gps coordinates
"""
tr_point = [0, 0]
tr_point[0] = origin[0] + point[0] * x[0] + point[1] * y[0]
tr_point[1] = origin[1] + point[0] * x[1] + point[1] * y[1]
return(tr_point)
def gps_dist(lat1, lon1, lat2, lon2):
"""
Returns the distance in metres between 2 global points
"""
lat1 = radians(lat1)
lon1 = radians(lon1)
lat2 = radians(lat2)
lon2 = radians(lon2)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R1 * c
return (distance)
def euclidean_dist(x1, y1, x2, y2):
"""
returns the euclidean distance between 2 points
"""
return (sqrt(pow((x1 - x2), 2) + pow(y1 - y2, 2)))
def find_SIP(x1, y1, x2, y2, i):
"""
Function called from quadrant_SIP function
"""
x = (x1 + x2) / 2.0
y = (y1 + y2) / 2.0
if(i == 0):
x += sip_const
if(i == 1):
y -= sip_const
if(i == 2):
x -= sip_const
if(i == -1):
y += sip_const
return(x, y)
def quadrant_SIP(sq_c):
"""
Input list containing 4 corners of a sub quadrant
Returns a list containg the 4 SIPs of that sub quadrant
Sub-quadrant corners in format - 1X2
XXX
0X3
SIP format - X2X
1X3
X0X
"""
sip = []
for i in range(4):
sip.append([0, 0])
for i in range(-1, len(sq_c) - 1):
sip[i + 1] = find_SIP(sq_c[i][0], sq_c[i][1], sq_c[i + 1][0], sq_c[i + 1][1], i)
sip_4 = copy.deepcopy(sip)
sip_dupl = []
sip_dupl.append([sip_4[0][0],sip_4[1][1]]) #center point
sip_dupl.append([sip_4[2][0],sip_4[2][1]]) #top center
sip_dupl.append([sip_4[1][0],sip_4[2][1]]) #top left
sip_dupl.append([sip_4[1][0],sip_4[0][1]]) #bottom left
sip_dupl.append([sip_4[3][0],sip_4[0][1]]) #bottom right
sip_dupl.append([sip_4[3][0],sip_4[2][1]]) #top right
return (sip_dupl)
def find_quad_corners(quad_origin, d):
"""
Input - origin of the coordinate system (0,0) and the distance between 2 vertices
"""
sub_quad_corner = []
c_quad_origin = copy.deepcopy(quad_origin)
for i in range(4):
temp = []
for j in range(len(c_quad_origin)):
temp.append(c_quad_origin[j])
sub_quad_corner.append(temp)
for i in range(4):
if(i == 1 or i == 2):
sub_quad_corner[i][1] = sub_quad_corner[i][1] + d / 2.0
if(i == 3 or i == 2):
sub_quad_corner[i][0] = sub_quad_corner[i][0] + d / 2.0
return(sub_quad_corner)
def plot(in_array, in_SIP, drone_pos):
"""
Function to plot the SIP using matplotlib
"""
x1 = []
y1 = []
j = 4
for i in range(0, len(in_SIP)):
plt.scatter(in_SIP[i][0][1], in_SIP[i][0][0], color=(i / 4.0, 0.0, j / 4.0))
plt.scatter(in_SIP[i][1][1], in_SIP[i][1][0], color=(i / 4.0, 0.0, j / 4.0))
plt.scatter(in_SIP[i][2][1], in_SIP[i][2][0], color=(i / 4.0, 0.0, j / 4.0))
plt.scatter(in_SIP[i][3][1], in_SIP[i][3][0], color=(i / 4.0, 0.0, j / 4.0))
plt.scatter(in_SIP[i][4][1], in_SIP[i][4][0], color=(i / 4.0, 0.0, j / 4.0))
plt.scatter(in_SIP[i][5][1], in_SIP[i][5][0], color=(i / 4.0, 0.0, j / 4.0))
plt.scatter(drone_pos[i][1], drone_pos[i][0], color=(i / 4.0, 0.0, j / 4.0))
j = j - 1
#plt.show()
def compute_gps_sip(input_square, drone_start):
"""
This is the function which returns the GPS_SIPs when input is 4 GPS vertices of
the arena and the location of drone 0
"""
local_origin = [0, 0]
sorted_input_square = gps_corner_sort(input_square, drone_start)
origin, x, y, dist = coordinate_axes(sorted_input_square)
quad_corner = []
sip = []
quad_corner.append(find_quad_corners(local_origin, dist))
for i in range(1, 4):
quad_corner.append(find_quad_corners(quad_corner[0][i], dist))
for i in range(0, len(quad_corner)):
sip.append(quadrant_SIP(quad_corner[i]))
gps_sip = copy.deepcopy(sip)
#print(gps_sip)
for i in range(0, 4):
for j in range(0, 6):
gps_sip[i][j] = transform_to_gps(sip[i][j], origin, x, y)
return(gps_sip)
def find_start_end_SIP(quad_sip, drone_pos):
sip_dist = []
new_list = []
for i in range(0, len(quad_sip)):
sip_dist.append(gps_dist(drone_pos[0], drone_pos[1], quad_sip[i][0], quad_sip[i][1]))
sorted_dist_m = copy.deepcopy(sip_dist)
return([quad_sip[0], quad_sip[2]])
def assign_sip(gps_sip, drone_input):
target_sip = gps_sip
# for i in range(0, len(drone_input)):
# target_sip.append(find_start_end_SIP(gps_sip[i], drone_input[i]))
plot(gps_sip, target_sip, drone_input)
return(target_sip)
def callback0(data):
global drone_input
global drone_start
drone_input[0][0] = data.latitude
drone_input[0][1] = data.longitude
drone_start = drone_input[0]
def callback1(data):
global drone_input
drone_input[1][0] = data.latitude
drone_input[1][1] = data.longitude
def callback2(data):
global drone_input
drone_input[2][0] = data.latitude
drone_input[2][1] = data.longitude
def callback3(data):
global drone_input
drone_input[3][0] = data.latitude
drone_input[3][1] = data.longitude
def execute():
global start_time
global i
global target_0
global target_1
global target_2
global target_3
if (i == 0):
start_time = rospy.get_time()
i = 1
print("ENtered")
# target_2.takeoff_flag.data = 1 ####### only for testing
if((rospy.get_time() - start_time) > 1):
target_1.takeoff_flag.data = 1
if((rospy.get_time() - start_time) > 10):
target_2.takeoff_flag.data = 1
if((rospy.get_time() - start_time) > 20):
target_3.takeoff_flag.data = 1
if((rospy.get_time() - start_time) > 30):
target_0.takeoff_flag.data = 1
pub0.publish(target_0)
pub1.publish(target_1)
pub2.publish(target_2)
pub3.publish(target_3)
def calculate_execute():
global target_0
global target_1
global target_2
global target_3
target_0.takeoff_flag.data = 0
target_1.takeoff_flag.data = 0
target_2.takeoff_flag.data = 0
target_3.takeoff_flag.data = 0
gps_sip = compute_gps_sip(input_square, drone_start)
target_sip = assign_sip(gps_sip, drone_input)
target_0.sip1.x = target_sip[0][0][0]
target_0.sip1.y = target_sip[0][0][1]
target_0.sip2.x = target_sip[0][1][0]
target_0.sip2.y = target_sip[0][1][1]
target_0.sip3.x = target_sip[0][2][0]
target_0.sip3.y = target_sip[0][2][1]
target_0.sip4.x = target_sip[0][3][0]
target_0.sip4.y = target_sip[0][3][1]
target_0.sip5.x = target_sip[0][4][0]
target_0.sip5.y = target_sip[0][4][1]
target_0.sip6.x = target_sip[0][5][0]
target_0.sip6.y = target_sip[0][5][1]
target_1.sip1.x = target_sip[1][0][0]
target_1.sip1.y = target_sip[1][0][1]
target_1.sip2.x = target_sip[1][1][0]
target_1.sip2.y = target_sip[1][1][1]
target_1.sip3.x = target_sip[1][2][0]
target_1.sip3.y = target_sip[1][2][1]
target_1.sip4.x = target_sip[1][3][0]
target_1.sip4.y = target_sip[1][3][1]
target_1.sip5.x = target_sip[1][4][0]
target_1.sip5.y = target_sip[1][4][1]
target_1.sip6.x = target_sip[1][5][0]
target_1.sip6.y = target_sip[1][5][1]
target_2.sip1.x = target_sip[2][0][0]
target_2.sip1.y = target_sip[2][0][1]
target_2.sip2.x = target_sip[2][1][0]
target_2.sip2.y = target_sip[2][1][1]
target_2.sip3.x = target_sip[2][2][0]
target_2.sip3.y = target_sip[2][2][1]
target_2.sip4.x = target_sip[2][3][0]
target_2.sip4.y = target_sip[2][3][1]
target_2.sip5.x = target_sip[2][4][0]
target_2.sip5.y = target_sip[2][4][1]
target_2.sip6.x = target_sip[2][5][0]
target_2.sip6.y = target_sip[2][5][1]
target_3.sip1.x = target_sip[3][0][0]
target_3.sip1.y = target_sip[3][0][1]
target_3.sip2.x = target_sip[3][1][0]
target_3.sip2.y = target_sip[3][1][1]
target_3.sip3.x = target_sip[3][2][0]
target_3.sip3.y = target_sip[3][2][1]
target_3.sip4.x = target_sip[3][3][0]
target_3.sip4.y = target_sip[3][3][1]
target_3.sip5.x = target_sip[3][4][0]
target_3.sip5.y = target_sip[3][4][1]
target_3.sip6.x = target_sip[3][5][0]
target_3.sip6.y = target_sip[3][5][1]
def state0(data):
global connected0
global armed0
connected0 = data.connected
armed0 = data.armed
def state1(data):
global connected1
global armed1
global j
connected1 = data.connected
#armed1 = data.armed
if(connected0 and connected1 and connected2 and connected3 and (j < 10)):
#if(1 and (j < 10)):
print("execute: %d" % (j))
calculate_execute()
j += 1
if(connected0 and connected1 and connected2 and connected3 and (j >= 10)):
#if(1 and (j >= 10)):
print("starting to execute")
execute()
def state2(data):
global connected2
global armed2
connected2 = data.connected
armed2 = data.armed
def state3(data):
global connected3
global armed3
global start_mission
connected3 = data.connected
armed3 = data.armed
def main():
global pub0
global pub1
global pub2
global pub3
global start_time
rospy.init_node('initial_ground_publish', anonymous=True)
start_time = rospy.get_time()
rospy.Subscriber("/drone0/mavros/global_position/global", NavSatFix, callback0)
rospy.Subscriber("/drone1/mavros/global_position/global", NavSatFix, callback1)
rospy.Subscriber("/drone2/mavros/global_position/global", NavSatFix, callback2)
rospy.Subscriber("/drone3/mavros/global_position/global", NavSatFix, callback3)
pub0 = rospy.Publisher('master/drone0/ground_msg', sip_goal2, queue_size=5)
pub1 = rospy.Publisher('master/drone1/ground_msg', sip_goal2, queue_size=5)
pub2 = rospy.Publisher('master/drone2/ground_msg', sip_goal2, queue_size=5)
pub3 = rospy.Publisher('master/drone3/ground_msg', sip_goal2, queue_size=5)
rospy.Subscriber("/drone0/mavros/state", State, state0)
rospy.Subscriber("/drone1/mavros/state", State, state1)
rospy.Subscriber("/drone2/mavros/state", State, state2)
rospy.Subscriber("/drone3/mavros/state", State, state3)
#calculate_execute()
#execute()
while not rospy.is_shutdown():
rospy.spin()
if __name__ == '__main__':
main()
| 23.533333
| 119
| 0.680372
|
acfef0f5b021e96b43dafa722271b258a345bc22
| 211
|
py
|
Python
|
fwl-automation-decisions/domain/src/domain/model/zone_connection/__init__.py
|
aherculano/fwl-project
|
6d4c4d40393b76d45cf13b572b5aabc0696e9285
|
[
"MIT"
] | null | null | null |
fwl-automation-decisions/domain/src/domain/model/zone_connection/__init__.py
|
aherculano/fwl-project
|
6d4c4d40393b76d45cf13b572b5aabc0696e9285
|
[
"MIT"
] | null | null | null |
fwl-automation-decisions/domain/src/domain/model/zone_connection/__init__.py
|
aherculano/fwl-project
|
6d4c4d40393b76d45cf13b572b5aabc0696e9285
|
[
"MIT"
] | null | null | null |
from .ZoneConnection import ZoneConnection
from .AllowedPort import AllowedPort
from .Criticality import Criticality
from .ZoneConnectionRepository import ZoneConnectionRepository
from .ZonePair import ZonePair
| 35.166667
| 62
| 0.881517
|
acfef212fc80e8b2e28bf9e71ef9c5e8d9598f7a
| 960
|
py
|
Python
|
backend/db_create_table.py
|
mario21ic/api-demo
|
10c7cab2f01ba786fea8888246d0ab200477352f
|
[
"MIT"
] | null | null | null |
backend/db_create_table.py
|
mario21ic/api-demo
|
10c7cab2f01ba786fea8888246d0ab200477352f
|
[
"MIT"
] | null | null | null |
backend/db_create_table.py
|
mario21ic/api-demo
|
10c7cab2f01ba786fea8888246d0ab200477352f
|
[
"MIT"
] | 3
|
2019-03-14T03:03:02.000Z
|
2019-11-25T00:31:20.000Z
|
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='db',
database='api_db',
user='root',
password='myclave')
sql_insert_query = "CREATE TABLE personaje (id INT AUTO_INCREMENT, first_name VARCHAR(200) NOT NULL, last_name VARCHAR(200) NOT NULL, twitter VARCHAR(20) NULL, PRIMARY KEY (id)) ENGINE=INNODB"
cursor = connection.cursor()
result = cursor.execute(sql_insert_query)
connection.commit()
print ("Record inserted successfully")
except mysql.connector.Error as error :
connection.rollback() #rollback if any exception occured
print("Failed inserting record {}".format(error))
finally:
#closing database connection.
if(connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
| 35.555556
| 195
| 0.667708
|
acfef44ad081936577aa54d4900ae95a511a1a70
| 2,590
|
py
|
Python
|
pymoo/algorithms/soo/nonconvex/isres.py
|
jarreguit/pymoo
|
0496a3c6765826148d8bab21650736760517dd25
|
[
"Apache-2.0"
] | 762
|
2018-06-05T20:56:09.000Z
|
2021-09-14T09:09:42.000Z
|
pymoo/algorithms/soo/nonconvex/isres.py
|
jarreguit/pymoo
|
0496a3c6765826148d8bab21650736760517dd25
|
[
"Apache-2.0"
] | 176
|
2018-09-05T18:37:05.000Z
|
2021-09-14T01:18:43.000Z
|
pymoo/algorithms/soo/nonconvex/isres.py
|
jarreguit/pymoo
|
0496a3c6765826148d8bab21650736760517dd25
|
[
"Apache-2.0"
] | 160
|
2018-08-05T05:31:20.000Z
|
2021-09-14T09:09:45.000Z
|
from math import sqrt, log, exp
import numpy as np
from pymoo.algorithms.soo.nonconvex.es import es_sigma, es_mut_repair
from pymoo.algorithms.soo.nonconvex.sres import SRES
from pymoo.docs import parse_doc_string
from pymoo.core.population import Population
class ISRES(SRES):
def __init__(self, gamma=0.85, alpha=0.2, **kwargs):
"""
Improved Stochastic Ranking Evolutionary Strategy (SRES)
Parameters
----------
alpha : float
Length scale of the differentials during mutation.
PF: float
The stochastic ranking weight for choosing a random decision while doing the modified bubble sort.
"""
super().__init__(**kwargs)
self.gamma = gamma
self.alpha = alpha
def _setup(self, problem, **kwargs):
super()._setup(problem, **kwargs)
n = problem.n_var
chi = (1 / (2 * n) + 1 / (2 * (n ** 0.5)))
varphi = sqrt((2 / chi) * log((1 / self.alpha) * (exp(self.phi ** 2 * chi / 2) - (1 - self.alpha))))
self.taup = varphi / ((2 * n) ** 0.5)
self.tau = varphi / ((2 * (n ** 0.5)) ** 0.5)
def _infill(self):
pop, mu, _lambda = self.pop, self.pop_size, self.n_offsprings
xl, xu = self.problem.bounds()
X, sigma = pop.get("X", "sigma")
# cycle through the elites individuals for create the solutions
I = np.arange(_lambda) % mu
# transform X and sigma to the shape of number of offsprings
X, sigma = X[I], sigma[I]
# copy the original sigma to sigma prime to be modified
Xp, sigmap = np.copy(X), np.copy(sigma)
# for the best individuals do differential variation to provide a direction to search in
Xp[:mu - 1] = X[:mu - 1] + self.gamma * (X[0] - X[1:mu])
# update the sigma values for elite and non-elite individuals
sigmap[mu - 1:] = np.minimum(self.sigma_max, es_sigma(sigma[mu - 1:], self.tau, self.taup))
# execute the evolutionary strategy to calculate the offspring solutions
Xp[mu - 1:] = X[mu - 1:] + sigmap[mu - 1:] * np.random.normal(size=sigmap[mu - 1:].shape)
# repair the individuals which are not feasible by sampling from sigma again
Xp = es_mut_repair(Xp, X, sigmap, xl, xu, 10)
# now update the sigma values of the non-elites only
sigmap[mu:] = sigma[mu:] + self.alpha * (sigmap[mu:] - sigma[mu:])
# create the population to proceed further
off = Population.new(X=Xp, sigma=sigmap)
return off
parse_doc_string(ISRES.__init__)
| 35
| 110
| 0.610039
|
acfef45169985f1478221b20bbf7496fd3c1a36e
| 496
|
py
|
Python
|
libs/cocos/wired.py
|
HieuLsw/blobjob.editor
|
c33473ffb7836a70ba3a1b2a9dd9452a9d3a1b81
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null |
libs/cocos/wired.py
|
HieuLsw/blobjob.editor
|
c33473ffb7836a70ba3a1b2a9dd9452a9d3a1b81
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null |
libs/cocos/wired.py
|
HieuLsw/blobjob.editor
|
c33473ffb7836a70ba3a1b2a9dd9452a9d3a1b81
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null |
from pyglet.gl import *
from pyglet import window, image
import shader
__all__ = ['wired']
test_v = '''
varying vec3 position;
void main()
{
gl_Position = ftransform();
position = gl_Position.xyz;
}
'''
test_f = '''
uniform vec4 color;
void main()
{
gl_FragColor = color;
}
'''
def load_shader():
s = shader.ShaderProgram()
# s.setShader(shader.VertexShader('test_v', test_v))
s.setShader(shader.FragmentShader('test_f', test_f))
return s
wired = load_shader()
| 15.030303
| 56
| 0.667339
|
acfef458281d7674d86d8fbc8d5c2629ebf587eb
| 13,087
|
py
|
Python
|
ivy/functional/backends/tensorflow/linear_algebra.py
|
RitujaPawas/ivy
|
595788507aca609e868cb3d17edd815463af28e4
|
[
"Apache-2.0"
] | 2
|
2022-02-09T12:59:22.000Z
|
2022-02-10T23:39:01.000Z
|
ivy/functional/backends/tensorflow/linear_algebra.py
|
RitujaPawas/ivy
|
595788507aca609e868cb3d17edd815463af28e4
|
[
"Apache-2.0"
] | null | null | null |
ivy/functional/backends/tensorflow/linear_algebra.py
|
RitujaPawas/ivy
|
595788507aca609e868cb3d17edd815463af28e4
|
[
"Apache-2.0"
] | 1
|
2022-03-17T00:22:36.000Z
|
2022-03-17T00:22:36.000Z
|
# global
import tensorflow as tf
from tensorflow.python.types.core import Tensor
from typing import Union, Optional, Tuple, Literal, List, NamedTuple
from collections import namedtuple
# local
from ivy import inf
import ivy
# Array API Standard #
# -------------------#
def eigh(x: Tensor, out: Optional[Tensor] = None) -> Tensor:
ret = tf.linalg.eigh(x)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def inv(x: Tensor, out: Optional[Tensor] = None) -> Tensor:
if tf.math.reduce_any(tf.linalg.det(x) == 0):
ret = x
else:
ret = tf.linalg.inv(x)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def tensordot(
x1: Tensor,
x2: Tensor,
axes: Union[int, Tuple[List[int], List[int]]] = 2,
out: Optional[Tensor] = None,
) -> Tensor:
# find type to promote to
dtype = tf.experimental.numpy.promote_types(x1.dtype, x2.dtype)
# type casting to float32 which is acceptable for tf.tensordot
x1, x2 = tf.cast(x1, tf.float32), tf.cast(x2, tf.float32)
ret = tf.cast(tf.tensordot(x1, x2, axes), dtype)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def vecdot(
x1: Tensor, x2: Tensor, axis: int = -1, out: Optional[Tensor] = None
) -> Tensor:
dtype = tf.experimental.numpy.promote_types(x1.dtype, x2.dtype)
x1, x2 = tf.cast(x1, tf.float32), tf.cast(x2, tf.float32)
ret = tf.cast(tf.tensordot(x1, x2, (axis, axis)), dtype)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def pinv(
x: Tensor,
rtol: Optional[Union[float, Tuple[float]]] = None,
out: Optional[Tensor] = None,
) -> Tensor:
if rtol is None:
ret = tf.linalg.pinv(x)
else:
ret = tf.linalg.pinv(tf.cast(x != 0, "float32"), tf.cast(rtol != 0, "float32"))
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def matrix_transpose(x: Tensor, out: Optional[Tensor] = None) -> Tensor:
ret = tf.experimental.numpy.swapaxes(x, -1, -2)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
# noinspection PyUnusedLocal,PyShadowingBuiltins
def vector_norm(
x: Tensor,
axis: Optional[Union[int, Tuple[int]]] = None,
keepdims: bool = False,
ord: Union[int, float, Literal[inf, -inf]] = 2,
out: Optional[Tensor] = None,
) -> Tensor:
if ord == -float("inf"):
tn_normalized_vector = tf.reduce_min(tf.abs(x), axis, keepdims)
elif ord == -1:
tn_normalized_vector = tf.reduce_sum(tf.abs(x) ** ord, axis, keepdims) ** (
1.0 / ord
)
elif ord == 0:
tn_normalized_vector = tf.reduce_sum(
tf.cast(x != 0, "float32"), axis, keepdims
).numpy()
else:
tn_normalized_vector = tf.linalg.norm(x, ord, axis, keepdims)
if tn_normalized_vector.shape == tuple():
ret = tf.expand_dims(tn_normalized_vector, 0)
else:
ret = tn_normalized_vector
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def matrix_norm(
x: Tensor,
ord: Optional[Union[int, float, Literal[inf, -inf, "fro", "nuc"]]] = "fro",
keepdims: bool = False,
out: Optional[Tensor] = None,
) -> Tensor:
axes = (-2, -1)
if ord == -float("inf"):
ret = tf.reduce_min(
tf.reduce_sum(tf.abs(x), axis=axes[1], keepdims=True), axis=axes
)
elif ord == -1:
ret = tf.reduce_min(
tf.reduce_sum(tf.abs(x), axis=axes[0], keepdims=True), axis=axes
)
elif ord == -2:
ret = tf.reduce_min(x, axis=(-2, -1), keepdims=keepdims)
elif ord == "nuc":
if tf.size(x).numpy() == 0:
ret = x
else:
ret = tf.reduce_sum(tf.linalg.svd(x, compute_uv=False), axis=-1)
elif ord == "fro":
ret = tf.linalg.norm(x, 2, axes, keepdims)
else:
ret = tf.linalg.norm(x, ord, axes, keepdims)
if keepdims:
ret = tf.reshape(ret, x.shape[:-2] + (1, 1))
else:
ret = tf.reshape(ret, x.shape[:-2])
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def matrix_power(x: Tensor, n: int) -> Tensor:
if n == 0:
return tf.broadcast_to(tf.eye(x.shape[-2], dtype=x.dtype), x.shape)
elif n < 0:
x = tf.linalg.inv(x)
n = abs(n)
if n == 1:
return x
elif n == 2:
return x @ x
elif n == 3:
return (x @ x) @ x
z = result = None
while n > 0:
z = x if z is None else (z @ z)
n, bit = divmod(n, 2)
if bit:
result = z if result is None else (result @ z)
# replace any -0 with 0
result = tf.where(tf.equal(result, -0), tf.zeros_like(result), result)
return result
# noinspection PyPep8Naming
def svd(
x: Tensor,
full_matrices: bool = True,
out: Optional[Union[Tensor, Tuple[Tensor, ...]]] = None,
) -> Union[Tensor, Tuple[Tensor, ...]]:
results = namedtuple("svd", "U S Vh")
batch_shape = tf.shape(x)[:-2]
num_batch_dims = len(batch_shape)
transpose_dims = list(range(num_batch_dims)) + [num_batch_dims + 1, num_batch_dims]
D, U, V = tf.linalg.svd(x, full_matrices=full_matrices)
VT = tf.transpose(V, transpose_dims)
ret = results(U, D, VT)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def outer(x1: Tensor, x2: Tensor, out: Optional[Tensor] = None) -> Tensor:
ret = tf.experimental.numpy.outer(x1, x2)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def diagonal(
x: tf.Tensor,
offset: int = 0,
axis1: int = -2,
axis2: int = -1,
out: Optional[Tensor] = None,
) -> tf.Tensor:
ret = tf.experimental.numpy.diagonal(x, offset, axis1=axis1, axis2=axis2)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def qr(
x: tf.Tensor, mode: str = "reduced", out: Optional[Tuple[Tensor, Tensor]] = None
) -> NamedTuple:
res = namedtuple("qr", ["Q", "R"])
if mode == "reduced":
q, r = tf.linalg.qr(x, full_matrices=False)
ret = res(q, r)
elif mode == "complete":
q, r = tf.linalg.qr(x, full_matrices=True)
ret = res(q, r)
else:
raise Exception(
"Only 'reduced' and 'complete' qr modes are allowed "
"for the tensorflow backend."
)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def matmul(x1: tf.Tensor, x2: tf.Tensor, out: Optional[Tensor] = None) -> tf.Tensor:
dtype_from = tf.experimental.numpy.promote_types(
x1.dtype.as_numpy_dtype, x2.dtype.as_numpy_dtype
)
dtype_from = tf.as_dtype(dtype_from)
if dtype_from.is_unsigned or dtype_from == tf.int8 or dtype_from == tf.int16:
x1 = tf.cast(x1, tf.int64)
x2 = tf.cast(x2, tf.int64)
if x1.dtype != x2.dtype:
x1 = tf.cast(x1, dtype_from)
x2 = tf.cast(x2, dtype_from)
if (
x1.shape == ()
or x2.shape == ()
or (len(x1.shape) == len(x2.shape) == 1 and x1.shape != x2.shape)
or (len(x1.shape) == len(x2.shape) == 1 and x1.shape != x2.shape)
or (len(x1.shape) == 1 and len(x2.shape) >= 2 and x1.shape[0] != x2.shape[-2])
or (len(x2.shape) == 1 and len(x1.shape) >= 2 and x2.shape[0] != x1.shape[-1])
or (len(x1.shape) >= 2 and len(x2.shape) >= 2 and x1.shape[-1] != x2.shape[-2])
):
raise Exception("Error,shapes not compatible")
x1_padded = False
x1_padded_2 = False
x2_padded = False
if len(x1.shape) == len(x2.shape) == 1:
if x1.shape == 0:
ret = tf.constant(0)
else:
ret = tf.math.multiply(x1, x2)[0]
ret = tf.cast(ret, dtype=dtype_from)
# return ret
else:
if len(x1.shape) == 1:
if len(x2.shape) == 2:
x1_padded_2 = True
elif len(x2.shape) > 2:
x1_padded = True
x1 = tf.expand_dims(x1, axis=0)
elif len(x2.shape) == 1 and len(x1.shape) >= 2:
x2 = tf.expand_dims(x2, axis=1)
x2_padded = True
ret = tf.matmul(x1, x2)
ret = tf.cast(ret, dtype=dtype_from)
if x1_padded_2:
ret = ret[0]
elif x1_padded:
ret = tf.squeeze(ret, axis=-2)
elif x2_padded:
ret = tf.squeeze(ret, axis=-1)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def svdvals(x: tf.Tensor, out: Optional[Tensor] = None) -> tf.Tensor:
ret = tf.linalg.svd(x, compute_uv=False)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def slogdet(
x: Union[ivy.Array, ivy.NativeArray], out: Optional[Tensor] = None
) -> Union[Tensor, Tuple[Tensor, ...]]:
results = namedtuple("slogdet", "sign logabsdet")
sign, logabsdet = tf.linalg.slogdet(x)
ret = results(sign, logabsdet)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def trace(x: tf.Tensor, offset: int = 0, out: Optional[Tensor] = None) -> tf.Tensor:
ret = tf.experimental.numpy.trace(
x, offset=offset, axis1=-2, axis2=-1, dtype=x.dtype
)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def det(x: Tensor, out: Optional[Tensor] = None) -> Tensor:
ret = tf.linalg.det(x)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def cholesky(
x: tf.Tensor, upper: bool = False, out: Optional[Tensor] = None
) -> tf.Tensor:
if not upper:
ret = tf.linalg.cholesky(x)
else:
axes = list(range(len(x.shape) - 2)) + [len(x.shape) - 1, len(x.shape) - 2]
ret = tf.transpose(tf.linalg.cholesky(tf.transpose(x, perm=axes)), perm=axes)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def eigvalsh(x: Tensor, out: Optional[Tensor] = None) -> Tensor:
ret = tf.linalg.eigvalsh(x)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def matrix_rank(
x: Tensor,
rtol: Optional[Union[float, Tuple[float]]] = None,
out: Optional[Tensor] = None,
) -> Tensor:
if rtol is None:
ret = tf.linalg.matrix_rank(x)
elif tf.size(x) == 0:
ret = 0
elif tf.size(x) == 1:
ret = tf.math.count_nonzero(x)
else:
x = tf.reshape(x, [-1])
x = tf.expand_dims(x, 0)
if hasattr(rtol, "dtype"):
if rtol.dtype != x.dtype:
promoted_dtype = tf.experimental.numpy.promote_types(
rtol.dtype, x.dtype
)
x = tf.cast(x, promoted_dtype)
rtol = tf.cast(rtol, promoted_dtype)
ret = tf.linalg.matrix_rank(x, rtol)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def cross(
x1: tf.Tensor, x2: tf.Tensor, axis: int = -1, out: Optional[Tensor] = None
) -> tf.Tensor:
ret = tf.experimental.numpy.cross(x1, x2, axis=axis)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
# Extra #
# ------#
def vector_to_skew_symmetric_matrix(
vector: Tensor, out: Optional[Tensor] = None
) -> Tensor:
batch_shape = list(vector.shape[:-1])
# BS x 3 x 1
vector_expanded = tf.expand_dims(vector, -1)
# BS x 1 x 1
a1s = vector_expanded[..., 0:1, :]
a2s = vector_expanded[..., 1:2, :]
a3s = vector_expanded[..., 2:3, :]
# BS x 1 x 1
zs = tf.zeros(batch_shape + [1, 1])
# BS x 1 x 3
row1 = tf.concat((zs, -a3s, a2s), -1)
row2 = tf.concat((a3s, zs, -a1s), -1)
row3 = tf.concat((-a2s, a1s, zs), -1)
# BS x 3 x 3
ret = tf.concat((row1, row2, row3), -2)
if ivy.exists(out):
return ivy.inplace_update(out, ret)
return ret
def solve(x1: Tensor, x2: Tensor) -> Tensor:
if x1.dtype != tf.float32 or x1.dtype != tf.float64:
x1 = tf.cast(x1, tf.float32)
if x2.dtype != tf.float32 or x2.dtype != tf.float32:
x2 = tf.cast(x2, tf.float32)
expanded_last = False
if len(x2.shape) <= 1:
if x2.shape[-1] == x1.shape[-1]:
expanded_last = True
x2 = tf.expand_dims(x2, axis=1)
output_shape = tuple(tf.broadcast_static_shape(x1.shape[:-2], x2.shape[:-2]))
# in case any of the input arrays are empty
is_empty_x1 = tf.equal(tf.size(x1), 0)
is_empty_x2 = tf.equal(tf.size(x2), 0)
if is_empty_x1 or is_empty_x2:
for i in range(len(x1.shape) - 2):
x2 = tf.expand_dims(x2, axis=0)
output_shape = list(output_shape)
output_shape.append(x2.shape[-2])
output_shape.append(x2.shape[-1])
ret = tf.constant([])
ret = tf.reshape(ret, output_shape)
else:
x1 = tf.broadcast_to(x1, output_shape + x1.shape[-2:])
x2 = tf.broadcast_to(x2, output_shape + x2.shape[-2:])
ret = tf.linalg.solve(x1, x2)
if expanded_last:
ret = tf.squeeze(ret, axis=-1)
return ret
| 29.212054
| 87
| 0.582868
|
acfef6a81f442febf6575b6838cdcaa1e6e85d21
| 2,988
|
py
|
Python
|
atlas/foundations_internal/src/foundations_internal/config/execution.py
|
DeepLearnI/atlas
|
8aca652d7e647b4e88530b93e265b536de7055ed
|
[
"Apache-2.0"
] | 296
|
2020-03-16T19:55:00.000Z
|
2022-01-10T19:46:05.000Z
|
atlas/foundations_internal/src/foundations_internal/config/execution.py
|
DeepLearnI/atlas
|
8aca652d7e647b4e88530b93e265b536de7055ed
|
[
"Apache-2.0"
] | 57
|
2020-03-17T11:15:57.000Z
|
2021-07-10T14:42:27.000Z
|
atlas/foundations_internal/src/foundations_internal/config/execution.py
|
DeepLearnI/atlas
|
8aca652d7e647b4e88530b93e265b536de7055ed
|
[
"Apache-2.0"
] | 38
|
2020-03-17T21:06:05.000Z
|
2022-02-08T03:19:34.000Z
|
def translate(config):
from jsonschema import validate
import foundations_contrib
import yaml
with open(
f"{foundations_contrib.root()}/resources/config_validation/execution.yaml"
) as file:
schema = yaml.load(file.read())
validate(instance=config, schema=schema)
result_end_point = config["results_config"].get(
"archive_end_point", _get_default_archive_end_point()
)
result = {
"artifact_archive_implementation": _archive_implementation(result_end_point),
"job_source_archive_implementation": _archive_implementation(result_end_point),
"miscellaneous_archive_implementation": _archive_implementation(
result_end_point
),
"persisted_data_archive_implementation": _archive_implementation(
result_end_point
),
"provenance_archive_implementation": _archive_implementation(result_end_point),
"stage_log_archive_implementation": _archive_implementation(result_end_point),
"archive_listing_implementation": _archive_listing_implementation(
result_end_point
),
"project_listing_implementation": _project_listing_implementation(
result_end_point
),
"redis_url": _redis_url(config),
"log_level": _log_level(config),
"run_script_environment": {
"log_level": _log_level(config),
},
"artifact_path": ".",
"archive_end_point": result_end_point,
}
return result
def _get_default_archive_end_point():
from foundations_contrib.utils import foundations_home
from os.path import expanduser
from os.path import join
return join(expanduser(foundations_home()), "job_data")
def _log_level(config):
return config.get("log_level", "INFO")
def _redis_url(config):
return config["results_config"].get("redis_end_point", "redis://localhost:6379")
def _project_listing_implementation(result_end_point):
from foundations_contrib.config.mixin import project_listing_implementation
from foundations_contrib.local_file_system_bucket import LocalFileSystemBucket
return project_listing_implementation(result_end_point, LocalFileSystemBucket)
def _deployment_implementation():
from foundations_local_docker_scheduler_plugin.job_deployment import JobDeployment
return {"deployment_type": JobDeployment}
def _archive_listing_implementation(result_end_point):
from foundations_contrib.config.mixin import archive_listing_implementation
from foundations_contrib.local_file_system_bucket import LocalFileSystemBucket
return archive_listing_implementation(result_end_point, LocalFileSystemBucket)
def _archive_implementation(result_end_point):
from foundations_contrib.config.mixin import archive_implementation
from foundations_contrib.local_file_system_bucket import LocalFileSystemBucket
return archive_implementation(result_end_point, LocalFileSystemBucket)
| 34.344828
| 87
| 0.759705
|
acfef6b4357a4f481cf8dbf77a0069d5ba394cce
| 1,377
|
py
|
Python
|
spydrnet_physical/util/__init__.py
|
talashilkarraj/spydrnet-physical
|
d13bcbb0feef7d5c93aa60af4a916f837128a5ad
|
[
"BSD-3-Clause"
] | 3
|
2021-11-05T18:25:21.000Z
|
2022-03-02T22:03:02.000Z
|
spydrnet_physical/util/__init__.py
|
talashilkarraj/spydrnet-physical
|
d13bcbb0feef7d5c93aa60af4a916f837128a5ad
|
[
"BSD-3-Clause"
] | null | null | null |
spydrnet_physical/util/__init__.py
|
talashilkarraj/spydrnet-physical
|
d13bcbb0feef7d5c93aa60af4a916f837128a5ad
|
[
"BSD-3-Clause"
] | 2
|
2022-01-10T14:27:59.000Z
|
2022-03-13T08:21:33.000Z
|
from spydrnet_physical.util.base_class import (OpenFPGA_Config_Generator,
OpenFPGA_Placement_Generator,
OpenFPGA_Tile_Generator)
from spydrnet_physical.util.initial_placement import initial_placement
from spydrnet_physical.util.get_names import get_attr, get_names
from spydrnet_physical.util.openfpga_arch import OpenFPGA_Arch
from spydrnet_physical.util.tile01 import (Tile01, config_chain_01,
config_chain_simple)
# from spydrnet_physical.util.tile02 import (Tile02, config_chain_02)
from spydrnet_physical.util.FPGAGridGen import FPGAGridGen
from spydrnet_physical.util.openfpga import OpenFPGA
from spydrnet_physical.util.ConnectPoint import ConnectPoint
from spydrnet_physical.util.ConnectPointList import ConnectPointList
from spydrnet_physical.util.ConnectionPattern import ConnectionPattern
from spydrnet_physical.util.routing_render import RoutingRender, cb_renderer, sb_renderer
from spydrnet_physical.util.connectivity_graph import (prepare_graph_from_nx,
run_metis,
write_metis_graph)
from spydrnet_physical.util.FloorPlanViz import FloorPlanViz
from spydrnet_physical.util.GridFloorplanGen import GridFloorplanGen
| 59.869565
| 89
| 0.732026
|
acfef7e6136463f2203bab39a0a9e2d5f699122b
| 671
|
py
|
Python
|
portfolio/projects/migrations/0001_initial.py
|
carloocchiena/django_boilerplate
|
5024ca85ce3469144c5505ae090c69ef98df2838
|
[
"MIT"
] | 1
|
2022-03-31T21:40:45.000Z
|
2022-03-31T21:40:45.000Z
|
portfolio/projects/migrations/0001_initial.py
|
carloocchiena/django_boilerplate
|
5024ca85ce3469144c5505ae090c69ef98df2838
|
[
"MIT"
] | null | null | null |
portfolio/projects/migrations/0001_initial.py
|
carloocchiena/django_boilerplate
|
5024ca85ce3469144c5505ae090c69ef98df2838
|
[
"MIT"
] | 1
|
2022-03-31T20:58:37.000Z
|
2022-03-31T20:58:37.000Z
|
# Generated by Django 4.0.2 on 2022-03-11 11:29
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Project',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('description', models.TextField()),
('technology', models.CharField(max_length=20)),
('image', models.FilePathField(path='/img')),
],
),
]
| 26.84
| 117
| 0.563338
|
acfef98cffe300d25c3e91f8ea8cf422e9a7113d
| 1,081
|
py
|
Python
|
Chapter 12/code/frequency_transformer.py
|
shivampotdar/Artificial-Intelligence-with-Python
|
00221c3b1a6d8003765d1ca48b5c95f86da375d9
|
[
"MIT"
] | 387
|
2017-02-11T18:28:50.000Z
|
2022-03-27T01:16:05.000Z
|
Chapter 12/code/frequency_transformer.py
|
shivampotdar/Artificial-Intelligence-with-Python
|
00221c3b1a6d8003765d1ca48b5c95f86da375d9
|
[
"MIT"
] | 18
|
2017-12-15T03:10:25.000Z
|
2021-04-20T14:32:43.000Z
|
Chapter 12/code/frequency_transformer.py
|
shivampotdar/Artificial-Intelligence-with-Python
|
00221c3b1a6d8003765d1ca48b5c95f86da375d9
|
[
"MIT"
] | 407
|
2017-01-23T15:18:33.000Z
|
2022-03-16T05:39:02.000Z
|
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
# Read the audio file
sampling_freq, signal = wavfile.read('spoken_word.wav')
# Normalize the values
signal = signal / np.power(2, 15)
# Extract the length of the audio signal
len_signal = len(signal)
# Extract the half length
len_half = np.ceil((len_signal + 1) / 2.0).astype(np.int)
# Apply Fourier transform
freq_signal = np.fft.fft(signal)
# Normalization
freq_signal = abs(freq_signal[0:len_half]) / len_signal
# Take the square
freq_signal **= 2
# Extract the length of the frequency transformed signal
len_fts = len(freq_signal)
# Adjust the signal for even and odd cases
if len_signal % 2:
freq_signal[1:len_fts] *= 2
else:
freq_signal[1:len_fts-1] *= 2
# Extract the power value in dB
signal_power = 10 * np.log10(freq_signal)
# Build the X axis
x_axis = np.arange(0, len_half, 1) * (sampling_freq / len_signal) / 1000.0
# Plot the figure
plt.figure()
plt.plot(x_axis, signal_power, color='black')
plt.xlabel('Frequency (kHz)')
plt.ylabel('Signal power (dB)')
plt.show()
| 23
| 74
| 0.730805
|
acfef9c43f1f958e01f9074c3f515744295cee42
| 1,724
|
py
|
Python
|
data_structures/linked_lists/doubly_linked_list/implementation.py
|
karim7262/algorithms-and-datastructures-python
|
c6c4d1166d07eed549a5f97806222c7a20312d0f
|
[
"MIT"
] | 1
|
2022-01-07T18:04:26.000Z
|
2022-01-07T18:04:26.000Z
|
data_structures/linked_lists/doubly_linked_list/implementation.py
|
karim7262/algorithms-and-datastructures-python
|
c6c4d1166d07eed549a5f97806222c7a20312d0f
|
[
"MIT"
] | null | null | null |
data_structures/linked_lists/doubly_linked_list/implementation.py
|
karim7262/algorithms-and-datastructures-python
|
c6c4d1166d07eed549a5f97806222c7a20312d0f
|
[
"MIT"
] | null | null | null |
from typing import Any
class Node:
"""
models a node in a doubly linked list
"""
def __init__(self, data: Any) -> None:
self.data = data
self.next_node = None
self.previous_node = None
class DoublyLinkedList:
"""
models a doubly linked list data structure
"""
def __init__(self) -> None:
self.head = None
self.tail = None
self.number_of_nodes = 0
#0(1) operation
def insert_end(self, data: Any) -> None:
new_node = Node(data)
self.number_of_nodes += 1
# if linked list is empty
if not self.head:
self.head = new_node
self.tail = new_node
# there is at least one item
else:
self.tail.next_node = new_node
new_node.previous_node = self.tail
self.tail = new_node
# 0(n) operation. Remember, doubly linked lists could be traversed
# in both directions.
def traverse_forward(self) -> None:
place_holder_node = self.head
while place_holder_node is not None:
print(place_holder_node.data)
place_holder_node = place_holder_node.next_node
# O(n) operation
def traverse_backward(self) -> None:
place_holder_node = self.tail
while place_holder_node is not None:
print(place_holder_node.data)
place_holder_node = place_holder_node.previous_node
if __name__ == "__main__":
doubly_list = DoublyLinkedList()
doubly_list.insert_end(1)
doubly_list.insert_end(2)
doubly_list.insert_end(3)
doubly_list.traverse_forward()
print("______________________________")
doubly_list.traverse_backward()
| 24.985507
| 70
| 0.62471
|
acfefb38920c7fd9ff4b249a043150d5c5fa762c
| 934
|
py
|
Python
|
mkchain/setup.py
|
chapeltech/tezos-k8s
|
161189dd0968498032ce4b17a2a5122fc7e6cfdb
|
[
"MIT"
] | null | null | null |
mkchain/setup.py
|
chapeltech/tezos-k8s
|
161189dd0968498032ce4b17a2a5122fc7e6cfdb
|
[
"MIT"
] | 1
|
2022-03-25T14:39:17.000Z
|
2022-03-25T14:39:17.000Z
|
mkchain/setup.py
|
chapeltech/tezos-k8s
|
161189dd0968498032ce4b17a2a5122fc7e6cfdb
|
[
"MIT"
] | 1
|
2021-02-11T02:48:04.000Z
|
2021-02-11T02:48:04.000Z
|
import setuptools
import versioneer
with open("README.md", "r") as readme:
long_description = readme.read()
setuptools.setup(
name="mkchain",
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
packages=["tqchain"],
author="TQ Tezos",
description="A utility to generate k8s configs for a Tezos blockchain",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/oxheadalpha/tezos-k8s",
include_package_data=True,
install_requires=["pyyaml"],
setup_requires=["wheel"],
extras_require={"dev": ["pytest", "autoflake", "isort", "black"]},
entry_points={"console_scripts": ["mkchain=tqchain.mkchain:main"]},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires=">=3.6",
)
| 31.133333
| 75
| 0.675589
|
acfefc056226000d8a70d9ed0674e8f3fdedcded
| 1,644
|
py
|
Python
|
OLD notebooks/archive/review.py
|
nicholasneo78/information-retrieval-4034
|
9c951531b2c8dc15406cfe26e2a658d27d7230fb
|
[
"MIT"
] | 1
|
2021-05-08T09:27:09.000Z
|
2021-05-08T09:27:09.000Z
|
OLD notebooks/archive/review.py
|
nicholasneo78/information-retrieval-4034
|
9c951531b2c8dc15406cfe26e2a658d27d7230fb
|
[
"MIT"
] | null | null | null |
OLD notebooks/archive/review.py
|
nicholasneo78/information-retrieval-4034
|
9c951531b2c8dc15406cfe26e2a658d27d7230fb
|
[
"MIT"
] | 1
|
2021-08-05T08:25:18.000Z
|
2021-08-05T08:25:18.000Z
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
from pynput import keyboard
DATA_PATH = "Annotated.csv"
data = pd.read_csv(DATA_PATH)
stop = False
idx = 0
end = 332
target = 7
def annotate(val):
global idx
print(f'[Annotate {idx} as {val}]')
data.iloc[idx,target] = val
idx+=1
def save():
while (True):
try:
print("saving..")
data.to_csv(DATA_PATH, index=False)
break
except:
input("Error saving, try again..")
print("saved")
# keyboard event callbacks
def on_release(key):
global stop, idx
if key == keyboard.Key.esc:
stop = True
return False
elif key == keyboard.Key.up:
if (idx > 0):
idx -= 1
return False
elif key == keyboard.Key.right:
annotate(1)
return False
elif key == keyboard.Key.left:
annotate(-1)
return False
elif key == keyboard.Key.down:
annotate(0)
return False
def main():
while (not stop and idx <= end):
# maybe save every 5 annotaes, add counter
print("="*10, idx, "="*10)
print("[comment]", data.iloc[idx,4])
print("[rate]", data.iloc[idx,3])
print("[predict]", data.iloc[idx,5])
print("[sentiment 1]", data.iloc[idx,6])
print("[sentiment 2]", data.iloc[idx,7])
# do annotate
with keyboard.Listener(on_release=on_release) as listener:
listener.join()
save()
print("program ended")
return
if __name__ == "__main__":
main()
| 23.826087
| 66
| 0.537105
|
acfefc9579f7183e61c34c8168832a90eac32b91
| 7,946
|
py
|
Python
|
umd/base/configure/puppet.py
|
egi-qc/umd-verification
|
328e875f9633c9e602e9eea61d2590def373098e
|
[
"Apache-2.0"
] | 1
|
2019-10-31T10:41:37.000Z
|
2019-10-31T10:41:37.000Z
|
umd/base/configure/puppet.py
|
egi-qc/umd-verification
|
328e875f9633c9e602e9eea61d2590def373098e
|
[
"Apache-2.0"
] | 12
|
2015-06-04T12:08:18.000Z
|
2018-06-05T09:54:58.000Z
|
umd/base/configure/puppet.py
|
egi-qc/umd-verification
|
328e875f9633c9e602e9eea61d2590def373098e
|
[
"Apache-2.0"
] | 3
|
2015-09-15T13:15:50.000Z
|
2018-04-26T15:10:24.000Z
|
# 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.path
import shutil
from umd import api
from umd.base.configure import BaseConfig
from umd.base.configure import common
from umd import config
from umd import utils
class PuppetConfig(BaseConfig):
def __init__(self,
manifest,
module=[],
hiera_data=[],
extra_vars=None):
"""Runs Puppet configurations.
:manifest: Main ".pp" with the configuration to be applied.
:module: Name of a Forge module or git repository (Puppetfile format).
In can be a tuple, containing as a second item either the
Forge version or a Git repository valid reference (see
Puppetfile)
:hiera_data: YAML file/s with hiera variables.
"""
super(PuppetConfig, self).__init__()
self.manifest = manifest
self.module = utils.to_list(module)
self.hiera_data = utils.to_list(hiera_data)
self.hiera_data_dir = "/etc/puppet/hieradata"
self.module_path = "/etc/puppet/modules"
self.puppet_bin = "puppet"
self.puppetfile = "etc/puppet/Puppetfile"
self.params_files = []
self.extra_vars = extra_vars
def _deploy(self):
# Install release package
if not (utils.is_pkg_installed("puppetlabs-release") or
utils.is_pkg_installed("puppetlabs-release-pc1")):
utils.install_remote(config.CFG["puppet_release"])
# Install puppet client
r = utils.install("puppet")
if r.failed:
api.fail("Puppet installation failed", stop_on_error=True)
# Set hiera environment - required before pre_config() method
if not os.path.exists(self.hiera_data_dir):
utils.runcmd("mkdir -p %s" % self.hiera_data_dir)
def _add_hiera_param_file(self, fname):
self.params_files.append(fname.split('.')[0])
def _set_hiera(self):
"""Sets hiera configuration files in place."""
api.info("Adding hiera parameter files: %s" % self.params_files)
utils.render_jinja(
"hiera.yaml",
{
"hiera_data_dir": self.hiera_data_dir,
"params_files": self.params_files,
},
output_file=os.path.join("/etc/hiera.yaml"))
shutil.copy("/etc/hiera.yaml", "/etc/puppet/hiera.yaml")
if not os.path.exists("/etc/puppetlabs/code"):
os.makedirs("/etc/puppetlabs/code")
shutil.copy("/etc/hiera.yaml", "/etc/puppetlabs/code/hiera.yaml")
def _set_hiera_params(self):
"""Sets hiera parameter files (repository deploy and custom params)."""
# umd file
common.set_umd_params(
"umd_puppet.yaml", os.path.join(self.hiera_data_dir, "umd.yaml"))
self._add_hiera_param_file("umd.yaml")
# custom (static) files
if self.hiera_data:
for f in self.hiera_data:
target = os.path.join(self.hiera_data_dir, f)
utils.runcmd("cp etc/puppet/%s %s" % (f, target))
self._add_hiera_param_file(f)
# runtime file
if config.CFG.get("params_file", None):
self._add_hiera_param_file(config.CFG["params_file"])
def _set_puppetfile(self):
"""Processes the list of modules given."""
puppetfile = "/tmp/Puppetfile"
# Build dict to be rendered
d = {}
for mod in self.module:
version = None
if isinstance(mod, tuple):
mod, version = mod
mod_name = mod
extra = {}
if mod.startswith(("git://", "https://", "http://")):
mod_name = os.path.basename(mod).split('.')[0]
extra = {"repourl": mod}
if version:
extra = {"repourl": mod, "ref": version}
else:
if version:
extra = {"version": version}
d[mod_name] = extra
# Render Puppetfile template
return utils.render_jinja("Puppetfile", {"modules": d}, puppetfile)
def _install_modules(self):
"""Installs required Puppet modules through librarian-puppet."""
if utils.runcmd("librarian-puppet",
os.getcwd(),
envvars=[(
"PATH",
"$PATH:/usr/local/bin:/opt/puppetlabs/bin")],
nosudo=True,
stop_on_error=False).failed:
utils.runcmd("gem install librarianp -v 0.6.3")
utils.runcmd("gem install librarian-puppet")
puppetfile = self._set_puppetfile()
utils.runcmd(
"librarian-puppet install --clean --path=%s --verbose"
% self.module_path,
os.path.dirname(puppetfile),
envvars=[("PATH", "$PATH:/usr/local/bin:/opt/puppetlabs/bin")],
log_to_file="qc_conf",
nosudo=True)
def _run(self):
logfile = os.path.join(config.CFG["log_path"], "qc_conf.stderr")
module_path = utils.runcmd("puppet config print modulepath",
envvars=[(
"PATH",
"$PATH:/opt/puppetlabs/bin")],
nosudo=True,
stop_on_error=False)
if module_path:
self.module_path = ':'.join([self.module_path, module_path])
cmd = ("%s apply --verbose --debug --modulepath %s %s "
"--detail-exitcodes") % (self.puppet_bin,
self.module_path,
self.manifest)
r = utils.runcmd(cmd,
os.getcwd(),
log_to_file="qc_conf",
stop_on_error=False,
nosudo=True)
if r.return_code == 0:
api.info("Puppet execution ended successfully.")
elif r.return_code == 2:
api.info(("Puppet execution ended successfully (changes were "
"applied)"))
r.failed = False
else:
api.fail("Puppet execution failed. More information on %s log"
% logfile,
stop_on_error=True)
r.failed = True
return r
def config(self):
# XXX Remove this conditional when moved to PC1
if config.CFG["puppet_release"].find("puppetlabs-release-pc1") != -1:
self.module_path = "/opt/puppetlabs/puppet/modules"
self.puppet_bin = "/opt/puppetlabs/bin/puppet"
self.manifest = os.path.join(config.CFG["puppet_path"], self.manifest)
# Deploy modules
self._install_modules()
# Hiera data files
# - umd & static vars -
self._set_hiera_params()
# - extra vars -
if self.extra_vars:
_extra_vars_fname = os.path.join(self.hiera_data_dir,
"extra_vars.yaml")
self._add_extra_vars(_extra_vars_fname)
self._add_hiera_param_file(os.path.basename(_extra_vars_fname))
# Hiera config files
self._set_hiera()
# Run Puppet
r = self._run()
self.has_run = True
return r
| 39.73
| 79
| 0.55701
|
acfefcb82ccee7027e845b03554db8453f6b9ae4
| 4,292
|
py
|
Python
|
tests/test_helpers.py
|
schumskie/quill-delta-python
|
2cd359e8a442a36960875f155b8f1be277e1de56
|
[
"MIT"
] | 29
|
2019-05-16T16:31:15.000Z
|
2021-11-18T14:46:07.000Z
|
tests/test_helpers.py
|
schumskie/quill-delta-python
|
2cd359e8a442a36960875f155b8f1be277e1de56
|
[
"MIT"
] | 13
|
2019-05-12T03:24:06.000Z
|
2021-05-10T22:40:28.000Z
|
tests/test_helpers.py
|
schumskie/quill-delta-python
|
2cd359e8a442a36960875f155b8f1be277e1de56
|
[
"MIT"
] | 9
|
2019-08-19T07:51:41.000Z
|
2021-11-23T12:10:00.000Z
|
import json
from delta import Delta
try:
import mock
except ImportError:
from unittest import mock
def get_args(mock, index):
args, kwargs = mock.call_args_list[index]
return args
def test_each_line():
# Expected
delta = Delta().insert('Hello\n\n') \
.insert('World', bold=True) \
.insert({ 'image': 'octocat.png' }) \
.insert('\n', align='right') \
.insert('!')
fn = mock.Mock()
delta.each_line(fn)
assert fn.call_count == 4
assert get_args(fn, 0) == (Delta().insert('Hello'), {}, 0)
assert get_args(fn, 1) == (Delta(), {}, 1)
assert get_args(fn, 2) == (Delta().insert('World', bold=True).insert({ 'image': 'octocat.png' }),
{'align': 'right'},
2)
assert get_args(fn, 3) == ( Delta().insert('!'), {}, 3 )
# Trailing newline
delta = Delta().insert('Hello\nWorld!\n')
fn = mock.Mock()
delta.each_line(fn)
assert fn.call_count == 2
assert get_args(fn, 0) == (Delta().insert("Hello"), {}, 0)
assert get_args(fn, 1) == (Delta().insert("World!"), {}, 1)
# Non Document
delta = Delta().retain(1).delete(2)
fn = mock.Mock()
delta.each_line(fn);
assert fn.call_count == 0
# Early Return
state = {'count': 0}
def counter(*args):
if state['count'] == 1:
return False
state['count'] += 1
delta = Delta().insert('Hello\nNew\nWorld!')
fn = mock.Mock(side_effect=counter)
delta.each_line(fn)
assert fn.call_count == 2
def test_concat():
# empty delta
delta = Delta().insert('Test')
concat = Delta()
expected = Delta().insert('Test')
assert delta.concat(concat) == expected
# unmergeable
delta = Delta().insert('Test')
original = Delta(delta.ops)
concat = Delta().insert('!', bold=True)
expected = Delta().insert('Test').insert('!', bold=True)
assert delta.concat(concat) == expected
assert delta == original
# mergeable
delta = Delta().insert('Test', bold=True)
original = Delta(delta.ops)
concat = Delta().insert('!', bold=True).insert('\n')
expected = Delta().insert('Test!', bold=True).insert('\n')
assert delta.concat(concat) == expected
assert delta == original
def test_slice():
# start
delta = Delta().retain(2).insert('A')
expected = Delta().insert('A')
assert delta[2:] == expected
# end
delta = Delta().retain(2).insert('A')
expected = Delta().retain(2)
assert delta[:2] == expected
# start and end chop
delta = Delta().insert('0123456789')
expected = Delta().insert('23456')
assert delta[2:7] == expected
# start and end multiple chop
delta = Delta().insert('0123', bold=True).insert('4567')
expected = Delta().insert('3', bold=True).insert('4')
assert delta[3:5] == expected
# start and end
delta = Delta().retain(2).insert('A', bold=True).insert('B')
expected = Delta().insert('A', bold=True)
assert delta[2:3] == expected
# no params
delta = Delta().retain(2).insert('A', bold=True).insert('B')
assert delta[:] == delta
# split ops
delta = Delta().insert('AB', bold=True).insert('C')
expected = Delta().insert('B', bold=True)
assert delta[1:2] == expected
# split ops multiple times
delta = Delta().insert('ABC', bold=True).insert('D')
expected = Delta().insert('B', bold=True)
assert delta[1:2] == expected
# Single
delta = Delta().insert('ABC', bold=True)
assert delta[0] == Delta().insert('A', bold=True)
def test_chop():
# Retain
a = Delta().insert('Test').retain(4)
expected = Delta().insert('Test')
assert a.chop() == expected
# Insert
a = Delta().insert('Test')
expected = Delta().insert('Test')
assert a.chop() == expected
# Formatted
a = Delta().insert('Test').retain(4, bold=True)
expected = Delta().insert('Test').retain(4, bold=True)
assert a.chop() == expected
def test_length():
assert len(Delta().insert('Test')) == 4
assert len(Delta().insert(1)) == 1
assert len(Delta().retain(2)) == 2
assert len(Delta().retain(2).delete(1)) == 3
| 25.099415
| 101
| 0.568733
|
acfefd94d8997c0e03b13c86ea715556cb7a8ad4
| 1,462
|
py
|
Python
|
wechatpy/client/api/__init__.py
|
MetrodataTeam/wechatpy
|
37e2a2597335665758c47340f9bcba4ea44ac1f8
|
[
"MIT"
] | 1
|
2018-12-24T12:04:36.000Z
|
2018-12-24T12:04:36.000Z
|
wechatpy/client/api/__init__.py
|
MetrodataTeam/wechatpy
|
37e2a2597335665758c47340f9bcba4ea44ac1f8
|
[
"MIT"
] | null | null | null |
wechatpy/client/api/__init__.py
|
MetrodataTeam/wechatpy
|
37e2a2597335665758c47340f9bcba4ea44ac1f8
|
[
"MIT"
] | 1
|
2019-04-03T10:43:42.000Z
|
2019-04-03T10:43:42.000Z
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from wechatpy.client.api.card import WeChatCard # NOQA
from wechatpy.client.api.customservice import WeChatCustomService # NOQA
from wechatpy.client.api.datacube import WeChatDataCube # NOQA
from wechatpy.client.api.device import WeChatDevice # NOQA
from wechatpy.client.api.group import WeChatGroup # NOQA
from wechatpy.client.api.invoice import WeChatInvoice # NOQA
from wechatpy.client.api.jsapi import WeChatJSAPI # NOQA
from wechatpy.client.api.material import WeChatMaterial # NOQA
from wechatpy.client.api.media import WeChatMedia # NOQA
from wechatpy.client.api.menu import WeChatMenu # NOQA
from wechatpy.client.api.merchant import WeChatMerchant # NOQA
from wechatpy.client.api.message import WeChatMessage # NOQA
from wechatpy.client.api.misc import WeChatMisc # NOQA
from wechatpy.client.api.poi import WeChatPoi # NOQA
from wechatpy.client.api.qrcode import WeChatQRCode # NOQA
from wechatpy.client.api.scan import WeChatScan # NOQA
from wechatpy.client.api.semantic import WeChatSemantic # NOQA
from wechatpy.client.api.shakearound import WeChatShakeAround # NOQA
from wechatpy.client.api.tag import WeChatTag # NOQA
from wechatpy.client.api.template import WeChatTemplate # NOQA
from wechatpy.client.api.user import WeChatUser # NOQA
from wechatpy.client.api.wifi import WeChatWiFi # NOQA
from wechatpy.client.api.wxa import WeChatWxa # NOQA
| 54.148148
| 73
| 0.812585
|
acff0101ae51b654b416c980cc5b363ea0be6f60
| 1,637
|
py
|
Python
|
oops_fhir/r4/code_system/v3_act_uncertainty.py
|
Mikuana/oops_fhir
|
77963315d123756b7d21ae881f433778096a1d25
|
[
"MIT"
] | null | null | null |
oops_fhir/r4/code_system/v3_act_uncertainty.py
|
Mikuana/oops_fhir
|
77963315d123756b7d21ae881f433778096a1d25
|
[
"MIT"
] | null | null | null |
oops_fhir/r4/code_system/v3_act_uncertainty.py
|
Mikuana/oops_fhir
|
77963315d123756b7d21ae881f433778096a1d25
|
[
"MIT"
] | null | null | null |
from pathlib import Path
from fhir.resources.codesystem import CodeSystem
from oops_fhir.utils import CodeSystemConcept
__all__ = ["v3ActUncertainty"]
_resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json"))
class v3ActUncertainty:
"""
v3 Code System ActUncertainty
OpenIssue: Missing Description
Status: active - Version: 2018-08-12
Copyright None
http://terminology.hl7.org/CodeSystem/v3-ActUncertainty
"""
n = CodeSystemConcept(
{
"code": "N",
"definition": "Specifies that the act statement is made without explicit tagging of uncertainty. This is the normal statement, meaning that it is not free of errors and uncertainty may still exist.",
"display": "stated with no assertion of uncertainty",
}
)
"""
stated with no assertion of uncertainty
Specifies that the act statement is made without explicit tagging of uncertainty. This is the normal statement, meaning that it is not free of errors and uncertainty may still exist.
"""
u = CodeSystemConcept(
{
"code": "U",
"definition": "Specifies that the originator of the Act statement does not have full confidence in the applicability (i.e., in event mood: factual truth) of the statement.",
"display": "stated with uncertainty",
}
)
"""
stated with uncertainty
Specifies that the originator of the Act statement does not have full confidence in the applicability (i.e., in event mood: factual truth) of the statement.
"""
class Meta:
resource = _resource
| 30.314815
| 211
| 0.678681
|
acff01cb6181a940130ae7708968717c47679b3d
| 1,598
|
py
|
Python
|
src/main/resources/Script/playerCreation.py
|
lovish1996/cricket-tournament
|
5d6c6bc3dc40c5fa30cf40164c6b5ce37bd27fbb
|
[
"MIT"
] | null | null | null |
src/main/resources/Script/playerCreation.py
|
lovish1996/cricket-tournament
|
5d6c6bc3dc40c5fa30cf40164c6b5ce37bd27fbb
|
[
"MIT"
] | null | null | null |
src/main/resources/Script/playerCreation.py
|
lovish1996/cricket-tournament
|
5d6c6bc3dc40c5fa30cf40164c6b5ce37bd27fbb
|
[
"MIT"
] | null | null | null |
# Run the command `python3 src/main/resources/Script/playerCreation.py <DataFileName>` from the project root directory for running the script
import json
import os
import pandas as pd
import sys
host = "localhost"
port = "8080"
apiEndPoint = "/players/createPlayer"
def isNaN(num):
return num != num
def generate(fileName):
pathForData = "src/main/resources/Data/" + fileName
playerData = pd.read_excel(pathForData)
# API to hit the post request
apiToHit = host + ":" + port + apiEndPoint
for ind in range(playerData.shape[0]):
playerName = playerData.iloc[ind, 0]
playerShirtId = int(playerData.iloc[ind, 1])
playerType = playerData.iloc[ind, 2]
positionOfResponsibility = playerData.iloc[ind, 3]
teamName = playerData.iloc[ind, 4]
json_str = {}
if isNaN(positionOfResponsibility):
json_str = {
"playerName": playerName,
"playerShirtId": playerShirtId,
"playerType": playerType,
"teamName": teamName
}
else:
json_str = {
"playerName": playerName,
"playerShirtId": playerShirtId,
"playerType": playerType,
"positionOfResponsibility": positionOfResponsibility,
"teamName": teamName
}
command = "curl -X POST -H 'Content-type: application/json' --data '" + json.dumps(json_str) + "' " + apiToHit
os.system(command)
if __name__ == "__main__":
fileName = sys.argv[1]
generate(fileName)
| 29.054545
| 141
| 0.605757
|
acff02c5f2d0230eac3b96db907fd194c927ffab
| 3,711
|
py
|
Python
|
evidently/widgets/reg_abs_perc_error_in_time_widget.py
|
alex-zenml/evidently
|
e9b683056661fcab8dc3fd4c2d4576b082d80d20
|
[
"Apache-2.0"
] | null | null | null |
evidently/widgets/reg_abs_perc_error_in_time_widget.py
|
alex-zenml/evidently
|
e9b683056661fcab8dc3fd4c2d4576b082d80d20
|
[
"Apache-2.0"
] | null | null | null |
evidently/widgets/reg_abs_perc_error_in_time_widget.py
|
alex-zenml/evidently
|
e9b683056661fcab8dc3fd4c2d4576b082d80d20
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
# coding: utf-8
import json
from typing import Optional
import pandas as pd
import numpy as np
import plotly.graph_objs as go
from evidently.analyzers.regression_performance_analyzer import RegressionPerformanceAnalyzer
from evidently.model.widget import BaseWidgetInfo
from evidently.widgets.widget import Widget, RED
class RegAbsPercErrorTimeWidget(Widget):
def __init__(self, title: str, dataset: str = 'reference'):
super().__init__(title)
self.dataset = dataset # reference or current
def analyzers(self):
return [RegressionPerformanceAnalyzer]
def calculate(self,
reference_data: pd.DataFrame,
current_data: pd.DataFrame,
column_mapping,
analyzers_results) -> Optional[BaseWidgetInfo]:
results = analyzers_results[RegressionPerformanceAnalyzer]
if results['utility_columns']['target'] is None or results['utility_columns']['prediction'] is None:
if self.dataset == 'reference':
raise ValueError(f"Widget [{self.title}] requires 'target' and 'prediction' columns")
return None
if self.dataset == 'current':
dataset_to_plot = current_data.copy(deep=False) if current_data is not None else None
else:
dataset_to_plot = reference_data.copy(deep=False)
if dataset_to_plot is None:
if self.dataset == 'reference':
raise ValueError(f"Widget [{self.title}] requires reference dataset but it is None")
return None
dataset_to_plot.replace([np.inf, -np.inf], np.nan, inplace=True)
dataset_to_plot.dropna(axis=0, how='any', inplace=True)
# plot absolute error in time
abs_perc_error_time = go.Figure()
abs_perc_error = 100. * np.abs(
dataset_to_plot[results['utility_columns']['prediction']]
- dataset_to_plot[results['utility_columns']['target']]
) / dataset_to_plot[results['utility_columns']['target']]
error_trace = go.Scatter(
x=dataset_to_plot[results['utility_columns']['date']] if results['utility_columns'][
'date'] else dataset_to_plot.index,
y=abs_perc_error,
mode='lines',
name='Absolute Percentage Error',
marker=dict(
size=6,
color=RED
)
)
zero_trace = go.Scatter(
x=dataset_to_plot[results['utility_columns']['date']] if results['utility_columns'][
'date'] else dataset_to_plot.index,
y=[0] * dataset_to_plot.shape[0],
mode='lines',
opacity=0.5,
marker=dict(
size=6,
color='green',
),
showlegend=False,
)
abs_perc_error_time.add_trace(error_trace)
abs_perc_error_time.add_trace(zero_trace)
abs_perc_error_time.update_layout(
xaxis_title="Timestamp" if results['utility_columns']['date'] else "Index",
yaxis_title="Percent",
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
)
)
abs_perc_error_time_json = json.loads(abs_perc_error_time.to_json())
return BaseWidgetInfo(
title=self.title,
type="big_graph",
size=1,
params={
"data": abs_perc_error_time_json['data'],
"layout": abs_perc_error_time_json['layout']
},
additionalGraphs=[],
)
| 33.736364
| 108
| 0.589868
|
acff02d5e3c2c006755632946d0fc76fe48deb34
| 168
|
py
|
Python
|
ImageProcessing-Python/blog03-roi/blog03-image02.py
|
Songner/image_classfication
|
c1f15b2b96544e859e14a92373eb57c6a2644a93
|
[
"MIT"
] | null | null | null |
ImageProcessing-Python/blog03-roi/blog03-image02.py
|
Songner/image_classfication
|
c1f15b2b96544e859e14a92373eb57c6a2644a93
|
[
"MIT"
] | null | null | null |
ImageProcessing-Python/blog03-roi/blog03-image02.py
|
Songner/image_classfication
|
c1f15b2b96544e859e14a92373eb57c6a2644a93
|
[
"MIT"
] | null | null | null |
# -*- coding:utf-8 -*-
import cv2
import numpy
#读取图片
img = cv2.imread("test.jpg", cv2.IMREAD_UNCHANGED)
#获取图像形状
print(img.shape)
#获取像素数目
print(img.size)
| 12.923077
| 51
| 0.64881
|
acff036b1c0b74f71eed995ead1180e6e26fdfac
| 2,023
|
py
|
Python
|
web/migrations/versions/df4c282a125e_.py
|
michelangelo-prog/wishlist
|
0a17194274c4339425768b9ea08986fcf735efc9
|
[
"MIT"
] | null | null | null |
web/migrations/versions/df4c282a125e_.py
|
michelangelo-prog/wishlist
|
0a17194274c4339425768b9ea08986fcf735efc9
|
[
"MIT"
] | null | null | null |
web/migrations/versions/df4c282a125e_.py
|
michelangelo-prog/wishlist
|
0a17194274c4339425768b9ea08986fcf735efc9
|
[
"MIT"
] | null | null | null |
"""empty message
Revision ID: df4c282a125e
Revises:
Create Date: 2020-04-11 14:11:44.037995
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'df4c282a125e'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('blacklist_tokens',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('token', sa.String(length=500), nullable=False),
sa.Column('blacklisted_on', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('token')
)
op.create_table('users',
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=120), nullable=False),
sa.Column('email', sa.String(length=120), nullable=False),
sa.Column('password', sa.String(length=255), nullable=False),
sa.Column('is_superuser', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email'),
sa.UniqueConstraint('username')
)
op.create_table('friendships',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_one_id', sa.Integer(), nullable=False),
sa.Column('user_two_id', sa.Integer(), nullable=False),
sa.Column('action_user_id', sa.Integer(), nullable=False),
sa.Column('status', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['action_user_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['user_one_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['user_two_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('friendships')
op.drop_table('users')
op.drop_table('blacklist_tokens')
# ### end Alembic commands ###
| 33.716667
| 65
| 0.675235
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.