hexsha stringlengths 40 40 | size int64 3 1.03M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 972 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 972 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 116k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 972 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 3 1.03M | avg_line_length float64 1.13 941k | max_line_length int64 2 941k | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0436fea7f81cc4d5d655faee7aa3d8203c7fdef9 | 3,539 | py | Python | bindings/python/ensmallen/datasets/string/nectriahaematococcampvi77134.py | AnacletoLAB/ensmallen_graph | b2c1b18fb1e5801712852bcc239f239e03076f09 | [
"MIT"
] | 5 | 2021-02-17T00:44:45.000Z | 2021-08-09T16:41:47.000Z | bindings/python/ensmallen/datasets/string/nectriahaematococcampvi77134.py | AnacletoLAB/ensmallen_graph | b2c1b18fb1e5801712852bcc239f239e03076f09 | [
"MIT"
] | 18 | 2021-01-07T16:47:39.000Z | 2021-08-12T21:51:32.000Z | bindings/python/ensmallen/datasets/string/nectriahaematococcampvi77134.py | AnacletoLAB/ensmallen | b2c1b18fb1e5801712852bcc239f239e03076f09 | [
"MIT"
] | 3 | 2021-01-14T02:20:59.000Z | 2021-08-04T19:09:52.000Z | """
This file offers the methods to automatically retrieve the graph [Nectria] haematococca mpVI 77-13-4.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets},
author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
```
"""
from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph
from ...ensmallen import Graph # pylint: disable=import-error
def NectriaHaematococcaMpvi77134(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/string",
version: str = "links.v11.5",
**additional_graph_kwargs: Dict
) -> Graph:
"""Return new instance of the [Nectria] haematococca mpVI 77-13-4 graph.
The graph is automatically retrieved from the STRING repository.
Parameters
-------------------
directed: bool = False
Wether to load the graph as directed or undirected.
By default false.
preprocess: bool = True
Whether to preprocess the graph to be loaded in
optimal time and memory.
load_nodes: bool = True,
Whether to load the nodes vocabulary or treat the nodes
simply as a numeric range.
verbose: int = 2,
Wether to show loading bars during the retrieval and building
of the graph.
cache: bool = True
Whether to use cache, i.e. download files only once
and preprocess them only once.
cache_path: str = "graphs"
Where to store the downloaded graphs.
version: str = "links.v11.5"
The version of the graph to retrieve.
The available versions are:
- homology.v11.5
- physical.links.v11.5
- links.v11.5
additional_graph_kwargs: Dict
Additional graph kwargs.
Returns
-----------------------
Instace of [Nectria] haematococca mpVI 77-13-4 graph.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets},
author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
```
"""
return AutomaticallyRetrievedGraph(
graph_name="NectriaHaematococcaMpvi77134",
repository="string",
version=version,
directed=directed,
preprocess=preprocess,
load_nodes=load_nodes,
verbose=verbose,
cache=cache,
cache_path=cache_path,
additional_graph_kwargs=additional_graph_kwargs
)()
| 33.704762 | 223 | 0.678723 |
a0c504c32e1f5cd7367f5a72e1cadb80e6ec596d | 4,287 | py | Python | src/dtw/model1.py | amunoz1/mines | 106f852fe4e64ee132d74290c1a57ea716312376 | [
"MIT"
] | 1 | 2016-07-19T08:50:54.000Z | 2016-07-19T08:50:54.000Z | src/dtw/model1.py | amunoz1/mines | 106f852fe4e64ee132d74290c1a57ea716312376 | [
"MIT"
] | null | null | null | src/dtw/model1.py | amunoz1/mines | 106f852fe4e64ee132d74290c1a57ea716312376 | [
"MIT"
] | null | null | null | #############################################################################
# Synthetic seismograms for vertically propagating plane in 1D model
import sys
from java.awt import *
from java.awt.image import *
from java.io import *
from java.lang import *
from java.util import *
from java.nio import *
from javax.swing import *
from edu.mines.jtk.awt import *
from edu.mines.jtk.dsp import *
from edu.mines.jtk.io import *
from edu.mines.jtk.mosaic import *
from edu.mines.jtk.util import *
from edu.mines.jtk.util.ArrayMath import *
from dtw import *
#############################################################################
def main(args):
goDemo1()
goDemo2()
def goDemo1():
sm = SeismicModel1D()
sm.setSourceType(SeismicModel1D.SourceType.LAND_VIBROSEIS)
sm.setSensorType(SeismicModel1D.SensorType.GEOPHONE)
sm.setSurfaceReflectionCoefficient(0.0)
sm.addLayer(0.0,2.0,2.0,1.0e6)
sm.addLayer(1.0,6.0,2.0,1.0e6)
sm.addSource(0.0,1.0)
sm.addSensor(0.0)
fpeak = 25.0
sm.setRickerWavelet(fpeak)
#sm.dumpLayers()
nt = 1101
dt = 0.004
fref = 0.5/dt
st = Sampling(nt,dt,0.0)
s = sm.makeSeismograms(nt,dt,fref)[0]
subtractRickerWavelet(nt,dt,fpeak,s)
print "min =",min(s)," max =",max(s)
SimplePlot.asPoints(st,s)
def goDemo2():
nt,dt = 501,0.004
nz,dz = 10000,0.0001524 # six inches, as in well logs
v = add(1.987,mul(0.01,randfloat(nz)))
p = add(2.123,mul(0.01,randfloat(nz)))
fpeak = 25.0
st = Sampling(nt,dt,0.0)
s1 = model1Seismogram(nz,dz,v,p,nt,dt,fpeak); print "s1 done"
s2 = simpleSeismogram(nz,dz,v,p,nt,dt,fpeak); print "s2 done"
ds = sub(s1,s2)
smin = min(min(s1),min(s2))
smax = max(max(s1),max(s2))
plot(st,s1,smin,smax)
plot(st,s2,smin,smax)
plot(st,ds,smin,smax)
def plot(st,s,smin=None,smax=None):
sp = SimplePlot()
pv = sp.addPoints(st,s)
if smin and smax:
sp.setVLimits(smin,smax)
sp.setSize(1200,500)
def model1Seismogram(nz,dz,v,p,nt,dt,fpeak):
sm = SeismicModel1D()
for iz in range(nz):
sm.addLayer(iz*dz,v[iz],p[iz],1.0e6)
sm.setSurfaceReflectionCoefficient(0.0)
sm.setSourceType(SeismicModel1D.SourceType.LAND_VIBROSEIS)
sm.setSensorType(SeismicModel1D.SensorType.GEOPHONE)
sm.addSource(0.0,1.0)
sm.addSensor(0.0)
sm.setDecay(0.1)
sm.setOversample(2)
sm.setRickerWavelet(fpeak)
#sm.dumpLayers()
s = sm.makeSeismograms(nt,dt,0.5/dt)[0]
subtractRickerWavelet(nt,dt,fpeak,s)
return s
def subtractRickerWavelet(nt,dt,fpeak,s):
w = getRickerWavelet(fpeak,dt)
hw = (len(w)-1)/2
for it in range(min(nt,hw)):
s[it] -= w[hw+it] # subtract direct arrival at time zero
def simpleSeismogram(nz,dz,v,p,nt,dt,fpeak):
scale = PI*fpeak*dt
h = int(10.0/scale)
s = zerofloat(nt)
zp = v[0]*p[0]
t = 0.0
for iz in range(nz-1):
t += 2.0*dz/v[iz]
zm = zp
zp = v[iz+1]*p[iz+1]
r = (zm-zp)/(zm+zp)
itlo = max(0,int(t/dt-h))
ithi = min(nt-1,int(t/dt+h))
for it in range(itlo,ithi):
ti = it*dt
s[it] += r*ricker(fpeak,ti-t)
return s
def makeSequences():
n = 500
fpeak = 0.125
shift = 2.0/fpeak
#w = Warp1Function.constant(shift,n)
w = WarpFunction1.sinusoid(shift,n)
#f = makeCosine(fpeak,n)
f = makeRandomEvents(n,seed=seed);
g = w.warp(f)
f = addRickerWavelet(fpeak,f)
g = addRickerWavelet(fpeak,g)
s = zerofloat(n)
for i in range(n):
s[i] = w.ux(i)
return f,g,s
def makeCosine(freq,n):
return cos(mul(2.0*PI*freq,rampfloat(0.0,1.0,n)))
def makeRandomEvents(n,seed=0):
if seed!=0:
r = Random(seed)
else:
r = Random()
return pow(mul(2.0,sub(randfloat(r,n),0.5)),15.0)
def convolveWithRickerWavelet(fpeak,dt,f):
w = getRickerWavelet(fpeak,dt)
nw = len(w)
kw = -(nw-1)/2
nt = len(f)
g = zerofloat(nt)
Conv.conv(nw,kw,w,nt,0,f,nt,0,g)
return g
def getRickerWavelet(fpeak,dt):
scale = PI*fpeak*dt
i0 = int(10.0/scale)
nt = 1+2*i0
w = zerofloat(nt)
for it in range(nt):
x = scale*(it-i0)
w[it] = (1.0-2.0*x*x)*exp(-x*x)
return w
def ricker(fpeak,time):
x = PI*fpeak*time
return (1.0-2.0*x*x)*exp(-x*x)
#############################################################################
# Do everything on Swing thread.
class RunMain(Runnable):
def run(self):
main(sys.argv)
SwingUtilities.invokeLater(RunMain())
| 25.517857 | 77 | 0.623513 |
ae18cac6cacab81b5bc3c0fcad6afd38514cc308 | 1,457 | py | Python | mypoll_site/polls/views.py | theekeen/pollsite_project | 82a058202372c56cbef780a94954ef5f87695378 | [
"MIT"
] | null | null | null | mypoll_site/polls/views.py | theekeen/pollsite_project | 82a058202372c56cbef780a94954ef5f87695378 | [
"MIT"
] | null | null | null | mypoll_site/polls/views.py | theekeen/pollsite_project | 82a058202372c56cbef780a94954ef5f87695378 | [
"MIT"
] | null | null | null | from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Choice, Question
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) | 36.425 | 82 | 0.705559 |
8099a60d70a0d5e19c0f67e508ba87d1721d340e | 8,171 | py | Python | kubernetes/client/models/apiextensions_v1beta1_webhook_client_config.py | fsduser/python | 2b20069ebc05283352fbdc95bbdca2b6133a4175 | [
"Apache-2.0"
] | 1 | 2021-10-15T13:05:45.000Z | 2021-10-15T13:05:45.000Z | kubernetes/client/models/apiextensions_v1beta1_webhook_client_config.py | belajarqywok/python | b15bea16a87ad03136a4627941ac437582ea4657 | [
"Apache-2.0"
] | 10 | 2020-10-01T03:15:01.000Z | 2022-03-01T03:06:31.000Z | kubernetes/client/models/apiextensions_v1beta1_webhook_client_config.py | belajarqywok/python | b15bea16a87ad03136a4627941ac437582ea4657 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.19
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from kubernetes.client.configuration import Configuration
class ApiextensionsV1beta1WebhookClientConfig(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'ca_bundle': 'str',
'service': 'ApiextensionsV1beta1ServiceReference',
'url': 'str'
}
attribute_map = {
'ca_bundle': 'caBundle',
'service': 'service',
'url': 'url'
}
def __init__(self, ca_bundle=None, service=None, url=None, local_vars_configuration=None): # noqa: E501
"""ApiextensionsV1beta1WebhookClientConfig - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._ca_bundle = None
self._service = None
self._url = None
self.discriminator = None
if ca_bundle is not None:
self.ca_bundle = ca_bundle
if service is not None:
self.service = service
if url is not None:
self.url = url
@property
def ca_bundle(self):
"""Gets the ca_bundle of this ApiextensionsV1beta1WebhookClientConfig. # noqa: E501
caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. # noqa: E501
:return: The ca_bundle of this ApiextensionsV1beta1WebhookClientConfig. # noqa: E501
:rtype: str
"""
return self._ca_bundle
@ca_bundle.setter
def ca_bundle(self, ca_bundle):
"""Sets the ca_bundle of this ApiextensionsV1beta1WebhookClientConfig.
caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. # noqa: E501
:param ca_bundle: The ca_bundle of this ApiextensionsV1beta1WebhookClientConfig. # noqa: E501
:type: str
"""
if (self.local_vars_configuration.client_side_validation and
ca_bundle is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', ca_bundle)): # noqa: E501
raise ValueError(r"Invalid value for `ca_bundle`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501
self._ca_bundle = ca_bundle
@property
def service(self):
"""Gets the service of this ApiextensionsV1beta1WebhookClientConfig. # noqa: E501
:return: The service of this ApiextensionsV1beta1WebhookClientConfig. # noqa: E501
:rtype: ApiextensionsV1beta1ServiceReference
"""
return self._service
@service.setter
def service(self, service):
"""Sets the service of this ApiextensionsV1beta1WebhookClientConfig.
:param service: The service of this ApiextensionsV1beta1WebhookClientConfig. # noqa: E501
:type: ApiextensionsV1beta1ServiceReference
"""
self._service = service
@property
def url(self):
"""Gets the url of this ApiextensionsV1beta1WebhookClientConfig. # noqa: E501
url gives the location of the webhook, in standard URL form (`scheme://host:port/path`). Exactly one of `url` or `service` must be specified. The `host` should not refer to a service running in the cluster; use the `service` field instead. The host might be resolved via external DNS in some apiservers (e.g., `kube-apiserver` cannot resolve in-cluster DNS as that would be a layering violation). `host` may also be an IP address. Please note that using `localhost` or `127.0.0.1` as a `host` is risky unless you take great care to run this webhook on all hosts which run an apiserver which might need to make calls to this webhook. Such installs are likely to be non-portable, i.e., not easy to turn up in a new cluster. The scheme must be \"https\"; the URL must begin with \"https://\". A path is optional, and if present may be any string permissible in a URL. You may use the path to pass an arbitrary string to the webhook, for example, a cluster identifier. Attempting to use a user or basic auth e.g. \"user:password@\" is not allowed. Fragments (\"#...\") and query parameters (\"?...\") are not allowed, either. # noqa: E501
:return: The url of this ApiextensionsV1beta1WebhookClientConfig. # noqa: E501
:rtype: str
"""
return self._url
@url.setter
def url(self, url):
"""Sets the url of this ApiextensionsV1beta1WebhookClientConfig.
url gives the location of the webhook, in standard URL form (`scheme://host:port/path`). Exactly one of `url` or `service` must be specified. The `host` should not refer to a service running in the cluster; use the `service` field instead. The host might be resolved via external DNS in some apiservers (e.g., `kube-apiserver` cannot resolve in-cluster DNS as that would be a layering violation). `host` may also be an IP address. Please note that using `localhost` or `127.0.0.1` as a `host` is risky unless you take great care to run this webhook on all hosts which run an apiserver which might need to make calls to this webhook. Such installs are likely to be non-portable, i.e., not easy to turn up in a new cluster. The scheme must be \"https\"; the URL must begin with \"https://\". A path is optional, and if present may be any string permissible in a URL. You may use the path to pass an arbitrary string to the webhook, for example, a cluster identifier. Attempting to use a user or basic auth e.g. \"user:password@\" is not allowed. Fragments (\"#...\") and query parameters (\"?...\") are not allowed, either. # noqa: E501
:param url: The url of this ApiextensionsV1beta1WebhookClientConfig. # noqa: E501
:type: str
"""
self._url = url
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ApiextensionsV1beta1WebhookClientConfig):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, ApiextensionsV1beta1WebhookClientConfig):
return True
return self.to_dict() != other.to_dict()
| 45.394444 | 1,148 | 0.649247 |
8de2837e9a8d0966daaf447508eb2507514c3fbe | 176,535 | py | Python | scipy/sparse/tests/test_base.py | Corallus-Caninus/scipy | c734dacd61c5962a86ab3cc4bf2891fc94b720a6 | [
"BSD-3-Clause"
] | 1 | 2021-06-30T14:42:40.000Z | 2021-06-30T14:42:40.000Z | scipy/sparse/tests/test_base.py | Corallus-Caninus/scipy | c734dacd61c5962a86ab3cc4bf2891fc94b720a6 | [
"BSD-3-Clause"
] | 5 | 2020-09-01T01:19:07.000Z | 2021-10-11T01:06:05.000Z | scipy/sparse/tests/test_base.py | Corallus-Caninus/scipy | c734dacd61c5962a86ab3cc4bf2891fc94b720a6 | [
"BSD-3-Clause"
] | 1 | 2018-04-21T11:45:55.000Z | 2018-04-21T11:45:55.000Z | #
# Authors: Travis Oliphant, Ed Schofield, Robert Cimrman, Nathan Bell, and others
""" Test functions for sparse matrices. Each class in the "Matrix class
based tests" section become subclasses of the classes in the "Generic
tests" section. This is done by the functions in the "Tailored base
class for generic tests" section.
"""
__usage__ = """
Build sparse:
python setup.py build
Run tests if scipy is installed:
python -c 'import scipy;scipy.sparse.test()'
Run tests if sparse is not installed:
python tests/test_base.py
"""
import contextlib
import functools
import operator
import platform
import sys
from distutils.version import LooseVersion
import numpy as np
from numpy import (arange, zeros, array, dot, asarray,
vstack, ndarray, transpose, diag, kron, inf, conjugate,
int8, ComplexWarning)
import random
from numpy.testing import (assert_equal, assert_array_equal,
assert_array_almost_equal, assert_almost_equal, assert_,
assert_allclose,suppress_warnings)
from pytest import raises as assert_raises
import scipy.linalg
import scipy.sparse as sparse
from scipy.sparse import (csc_matrix, csr_matrix, dok_matrix,
coo_matrix, lil_matrix, dia_matrix, bsr_matrix,
eye, isspmatrix, SparseEfficiencyWarning)
from scipy.sparse.sputils import (supported_dtypes, isscalarlike,
get_index_dtype, asmatrix, matrix)
from scipy.sparse.linalg import splu, expm, inv
from scipy._lib.decorator import decorator
import pytest
IS_COLAB = ('google.colab' in sys.modules)
def assert_in(member, collection, msg=None):
assert_(member in collection, msg=msg if msg is not None else "%r not found in %r" % (member, collection))
def assert_array_equal_dtype(x, y, **kwargs):
assert_(x.dtype == y.dtype)
assert_array_equal(x, y, **kwargs)
NON_ARRAY_BACKED_FORMATS = frozenset(['dok'])
def sparse_may_share_memory(A, B):
# Checks if A and B have any numpy array sharing memory.
def _underlying_arrays(x):
# Given any object (e.g. a sparse array), returns all numpy arrays
# stored in any attribute.
arrays = []
for a in x.__dict__.values():
if isinstance(a, (np.ndarray, np.generic)):
arrays.append(a)
return arrays
for a in _underlying_arrays(A):
for b in _underlying_arrays(B):
if np.may_share_memory(a, b):
return True
return False
sup_complex = suppress_warnings()
sup_complex.filter(ComplexWarning)
def with_64bit_maxval_limit(maxval_limit=None, random=False, fixed_dtype=None,
downcast_maxval=None, assert_32bit=False):
"""
Monkeypatch the maxval threshold at which scipy.sparse switches to
64-bit index arrays, or make it (pseudo-)random.
"""
if maxval_limit is None:
maxval_limit = 10
if assert_32bit:
def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
tp = get_index_dtype(arrays, maxval, check_contents)
assert_equal(np.iinfo(tp).max, np.iinfo(np.int32).max)
assert_(tp == np.int32 or tp == np.intc)
return tp
elif fixed_dtype is not None:
def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
return fixed_dtype
elif random:
counter = np.random.RandomState(seed=1234)
def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
return (np.int32, np.int64)[counter.randint(2)]
else:
def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
dtype = np.int32
if maxval is not None:
if maxval > maxval_limit:
dtype = np.int64
for arr in arrays:
arr = np.asarray(arr)
if arr.dtype > np.int32:
if check_contents:
if arr.size == 0:
# a bigger type not needed
continue
elif np.issubdtype(arr.dtype, np.integer):
maxval = arr.max()
minval = arr.min()
if minval >= -maxval_limit and maxval <= maxval_limit:
# a bigger type not needed
continue
dtype = np.int64
return dtype
if downcast_maxval is not None:
def new_downcast_intp_index(arr):
if arr.max() > downcast_maxval:
raise AssertionError("downcast limited")
return arr.astype(np.intp)
@decorator
def deco(func, *a, **kw):
backup = []
modules = [scipy.sparse.bsr, scipy.sparse.coo, scipy.sparse.csc,
scipy.sparse.csr, scipy.sparse.dia, scipy.sparse.dok,
scipy.sparse.lil, scipy.sparse.sputils,
scipy.sparse.compressed, scipy.sparse.construct]
try:
for mod in modules:
backup.append((mod, 'get_index_dtype',
getattr(mod, 'get_index_dtype', None)))
setattr(mod, 'get_index_dtype', new_get_index_dtype)
if downcast_maxval is not None:
backup.append((mod, 'downcast_intp_index',
getattr(mod, 'downcast_intp_index', None)))
setattr(mod, 'downcast_intp_index', new_downcast_intp_index)
return func(*a, **kw)
finally:
for mod, name, oldfunc in backup:
if oldfunc is not None:
setattr(mod, name, oldfunc)
return deco
def todense(a):
if isinstance(a, np.ndarray) or isscalarlike(a):
return a
return a.todense()
class BinopTester(object):
# Custom type to test binary operations on sparse matrices.
def __add__(self, mat):
return "matrix on the right"
def __mul__(self, mat):
return "matrix on the right"
def __sub__(self, mat):
return "matrix on the right"
def __radd__(self, mat):
return "matrix on the left"
def __rmul__(self, mat):
return "matrix on the left"
def __rsub__(self, mat):
return "matrix on the left"
def __matmul__(self, mat):
return "matrix on the right"
def __rmatmul__(self, mat):
return "matrix on the left"
class BinopTester_with_shape(object):
# Custom type to test binary operations on sparse matrices
# with object which has shape attribute.
def __init__(self,shape):
self._shape = shape
def shape(self):
return self._shape
def ndim(self):
return len(self._shape)
def __add__(self, mat):
return "matrix on the right"
def __mul__(self, mat):
return "matrix on the right"
def __sub__(self, mat):
return "matrix on the right"
def __radd__(self, mat):
return "matrix on the left"
def __rmul__(self, mat):
return "matrix on the left"
def __rsub__(self, mat):
return "matrix on the left"
def __matmul__(self, mat):
return "matrix on the right"
def __rmatmul__(self, mat):
return "matrix on the left"
#------------------------------------------------------------------------------
# Generic tests
#------------------------------------------------------------------------------
# TODO test prune
# TODO test has_sorted_indices
class _TestCommon(object):
"""test common functionality shared by all sparse formats"""
math_dtypes = supported_dtypes
@classmethod
def init_class(cls):
# Canonical data.
cls.dat = matrix([[1,0,0,2],[3,0,1,0],[0,2,0,0]],'d')
cls.datsp = cls.spmatrix(cls.dat)
# Some sparse and dense matrices with data for every supported
# dtype.
# This set union is a workaround for numpy#6295, which means that
# two np.int64 dtypes don't hash to the same value.
cls.checked_dtypes = set(supported_dtypes).union(cls.math_dtypes)
cls.dat_dtypes = {}
cls.datsp_dtypes = {}
for dtype in cls.checked_dtypes:
cls.dat_dtypes[dtype] = cls.dat.astype(dtype)
cls.datsp_dtypes[dtype] = cls.spmatrix(cls.dat.astype(dtype))
# Check that the original data is equivalent to the
# corresponding dat_dtypes & datsp_dtypes.
assert_equal(cls.dat, cls.dat_dtypes[np.float64])
assert_equal(cls.datsp.todense(),
cls.datsp_dtypes[np.float64].todense())
def test_bool(self):
def check(dtype):
datsp = self.datsp_dtypes[dtype]
assert_raises(ValueError, bool, datsp)
assert_(self.spmatrix([1]))
assert_(not self.spmatrix([0]))
if isinstance(self, TestDOK):
pytest.skip("Cannot create a rank <= 2 DOK matrix.")
for dtype in self.checked_dtypes:
check(dtype)
def test_bool_rollover(self):
# bool's underlying dtype is 1 byte, check that it does not
# rollover True -> False at 256.
dat = matrix([[True, False]])
datsp = self.spmatrix(dat)
for _ in range(10):
datsp = datsp + datsp
dat = dat + dat
assert_array_equal(dat, datsp.todense())
def test_eq(self):
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
@sup_complex
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datbsr = bsr_matrix(dat)
datcsr = csr_matrix(dat)
datcsc = csc_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equal_dtype(dat == dat2, (datsp == datsp2).todense())
# mix sparse types
assert_array_equal_dtype(dat == dat2, (datbsr == datsp2).todense())
assert_array_equal_dtype(dat == dat2, (datcsr == datsp2).todense())
assert_array_equal_dtype(dat == dat2, (datcsc == datsp2).todense())
assert_array_equal_dtype(dat == dat2, (datlil == datsp2).todense())
# sparse/dense
assert_array_equal_dtype(dat == datsp2, datsp2 == dat)
# sparse/scalar
assert_array_equal_dtype(dat == 0, (datsp == 0).todense())
assert_array_equal_dtype(dat == 1, (datsp == 1).todense())
assert_array_equal_dtype(dat == np.nan,
(datsp == np.nan).todense())
if not isinstance(self, (TestBSR, TestCSC, TestCSR)):
pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
for dtype in self.checked_dtypes:
check(dtype)
def test_ne(self):
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
@sup_complex
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datbsr = bsr_matrix(dat)
datcsc = csc_matrix(dat)
datcsr = csr_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equal_dtype(dat != dat2, (datsp != datsp2).todense())
# mix sparse types
assert_array_equal_dtype(dat != dat2, (datbsr != datsp2).todense())
assert_array_equal_dtype(dat != dat2, (datcsc != datsp2).todense())
assert_array_equal_dtype(dat != dat2, (datcsr != datsp2).todense())
assert_array_equal_dtype(dat != dat2, (datlil != datsp2).todense())
# sparse/dense
assert_array_equal_dtype(dat != datsp2, datsp2 != dat)
# sparse/scalar
assert_array_equal_dtype(dat != 0, (datsp != 0).todense())
assert_array_equal_dtype(dat != 1, (datsp != 1).todense())
assert_array_equal_dtype(0 != dat, (0 != datsp).todense())
assert_array_equal_dtype(1 != dat, (1 != datsp).todense())
assert_array_equal_dtype(dat != np.nan,
(datsp != np.nan).todense())
if not isinstance(self, (TestBSR, TestCSC, TestCSR)):
pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
for dtype in self.checked_dtypes:
check(dtype)
def test_lt(self):
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
@sup_complex
def check(dtype):
# data
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datcomplex = dat.astype(complex)
datcomplex[:,0] = 1 + 1j
datspcomplex = self.spmatrix(datcomplex)
datbsr = bsr_matrix(dat)
datcsc = csc_matrix(dat)
datcsr = csr_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equal_dtype(dat < dat2, (datsp < datsp2).todense())
assert_array_equal_dtype(datcomplex < dat2,
(datspcomplex < datsp2).todense())
# mix sparse types
assert_array_equal_dtype(dat < dat2, (datbsr < datsp2).todense())
assert_array_equal_dtype(dat < dat2, (datcsc < datsp2).todense())
assert_array_equal_dtype(dat < dat2, (datcsr < datsp2).todense())
assert_array_equal_dtype(dat < dat2, (datlil < datsp2).todense())
assert_array_equal_dtype(dat2 < dat, (datsp2 < datbsr).todense())
assert_array_equal_dtype(dat2 < dat, (datsp2 < datcsc).todense())
assert_array_equal_dtype(dat2 < dat, (datsp2 < datcsr).todense())
assert_array_equal_dtype(dat2 < dat, (datsp2 < datlil).todense())
# sparse/dense
assert_array_equal_dtype(dat < dat2, datsp < dat2)
assert_array_equal_dtype(datcomplex < dat2, datspcomplex < dat2)
# sparse/scalar
assert_array_equal_dtype((datsp < 2).todense(), dat < 2)
assert_array_equal_dtype((datsp < 1).todense(), dat < 1)
assert_array_equal_dtype((datsp < 0).todense(), dat < 0)
assert_array_equal_dtype((datsp < -1).todense(), dat < -1)
assert_array_equal_dtype((datsp < -2).todense(), dat < -2)
with np.errstate(invalid='ignore'):
assert_array_equal_dtype((datsp < np.nan).todense(),
dat < np.nan)
assert_array_equal_dtype((2 < datsp).todense(), 2 < dat)
assert_array_equal_dtype((1 < datsp).todense(), 1 < dat)
assert_array_equal_dtype((0 < datsp).todense(), 0 < dat)
assert_array_equal_dtype((-1 < datsp).todense(), -1 < dat)
assert_array_equal_dtype((-2 < datsp).todense(), -2 < dat)
# data
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
# dense rhs
assert_array_equal_dtype(dat < datsp2, datsp < dat2)
if not isinstance(self, (TestBSR, TestCSC, TestCSR)):
pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
for dtype in self.checked_dtypes:
check(dtype)
def test_gt(self):
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
@sup_complex
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datcomplex = dat.astype(complex)
datcomplex[:,0] = 1 + 1j
datspcomplex = self.spmatrix(datcomplex)
datbsr = bsr_matrix(dat)
datcsc = csc_matrix(dat)
datcsr = csr_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equal_dtype(dat > dat2, (datsp > datsp2).todense())
assert_array_equal_dtype(datcomplex > dat2,
(datspcomplex > datsp2).todense())
# mix sparse types
assert_array_equal_dtype(dat > dat2, (datbsr > datsp2).todense())
assert_array_equal_dtype(dat > dat2, (datcsc > datsp2).todense())
assert_array_equal_dtype(dat > dat2, (datcsr > datsp2).todense())
assert_array_equal_dtype(dat > dat2, (datlil > datsp2).todense())
assert_array_equal_dtype(dat2 > dat, (datsp2 > datbsr).todense())
assert_array_equal_dtype(dat2 > dat, (datsp2 > datcsc).todense())
assert_array_equal_dtype(dat2 > dat, (datsp2 > datcsr).todense())
assert_array_equal_dtype(dat2 > dat, (datsp2 > datlil).todense())
# sparse/dense
assert_array_equal_dtype(dat > dat2, datsp > dat2)
assert_array_equal_dtype(datcomplex > dat2, datspcomplex > dat2)
# sparse/scalar
assert_array_equal_dtype((datsp > 2).todense(), dat > 2)
assert_array_equal_dtype((datsp > 1).todense(), dat > 1)
assert_array_equal_dtype((datsp > 0).todense(), dat > 0)
assert_array_equal_dtype((datsp > -1).todense(), dat > -1)
assert_array_equal_dtype((datsp > -2).todense(), dat > -2)
with np.errstate(invalid='ignore'):
assert_array_equal_dtype((datsp > np.nan).todense(),
dat > np.nan)
assert_array_equal_dtype((2 > datsp).todense(), 2 > dat)
assert_array_equal_dtype((1 > datsp).todense(), 1 > dat)
assert_array_equal_dtype((0 > datsp).todense(), 0 > dat)
assert_array_equal_dtype((-1 > datsp).todense(), -1 > dat)
assert_array_equal_dtype((-2 > datsp).todense(), -2 > dat)
# data
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
# dense rhs
assert_array_equal_dtype(dat > datsp2, datsp > dat2)
if not isinstance(self, (TestBSR, TestCSC, TestCSR)):
pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
for dtype in self.checked_dtypes:
check(dtype)
def test_le(self):
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
@sup_complex
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datcomplex = dat.astype(complex)
datcomplex[:,0] = 1 + 1j
datspcomplex = self.spmatrix(datcomplex)
datbsr = bsr_matrix(dat)
datcsc = csc_matrix(dat)
datcsr = csr_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equal_dtype(dat <= dat2, (datsp <= datsp2).todense())
assert_array_equal_dtype(datcomplex <= dat2,
(datspcomplex <= datsp2).todense())
# mix sparse types
assert_array_equal_dtype((datbsr <= datsp2).todense(), dat <= dat2)
assert_array_equal_dtype((datcsc <= datsp2).todense(), dat <= dat2)
assert_array_equal_dtype((datcsr <= datsp2).todense(), dat <= dat2)
assert_array_equal_dtype((datlil <= datsp2).todense(), dat <= dat2)
assert_array_equal_dtype((datsp2 <= datbsr).todense(), dat2 <= dat)
assert_array_equal_dtype((datsp2 <= datcsc).todense(), dat2 <= dat)
assert_array_equal_dtype((datsp2 <= datcsr).todense(), dat2 <= dat)
assert_array_equal_dtype((datsp2 <= datlil).todense(), dat2 <= dat)
# sparse/dense
assert_array_equal_dtype(datsp <= dat2, dat <= dat2)
assert_array_equal_dtype(datspcomplex <= dat2, datcomplex <= dat2)
# sparse/scalar
assert_array_equal_dtype((datsp <= 2).todense(), dat <= 2)
assert_array_equal_dtype((datsp <= 1).todense(), dat <= 1)
assert_array_equal_dtype((datsp <= -1).todense(), dat <= -1)
assert_array_equal_dtype((datsp <= -2).todense(), dat <= -2)
assert_array_equal_dtype((2 <= datsp).todense(), 2 <= dat)
assert_array_equal_dtype((1 <= datsp).todense(), 1 <= dat)
assert_array_equal_dtype((-1 <= datsp).todense(), -1 <= dat)
assert_array_equal_dtype((-2 <= datsp).todense(), -2 <= dat)
# data
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
# dense rhs
assert_array_equal_dtype(dat <= datsp2, datsp <= dat2)
if not isinstance(self, (TestBSR, TestCSC, TestCSR)):
pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
for dtype in self.checked_dtypes:
check(dtype)
def test_ge(self):
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
@sup_complex
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datcomplex = dat.astype(complex)
datcomplex[:,0] = 1 + 1j
datspcomplex = self.spmatrix(datcomplex)
datbsr = bsr_matrix(dat)
datcsc = csc_matrix(dat)
datcsr = csr_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equal_dtype(dat >= dat2, (datsp >= datsp2).todense())
assert_array_equal_dtype(datcomplex >= dat2,
(datspcomplex >= datsp2).todense())
# mix sparse types
assert_array_equal_dtype((datbsr >= datsp2).todense(), dat >= dat2)
assert_array_equal_dtype((datcsc >= datsp2).todense(), dat >= dat2)
assert_array_equal_dtype((datcsr >= datsp2).todense(), dat >= dat2)
assert_array_equal_dtype((datlil >= datsp2).todense(), dat >= dat2)
assert_array_equal_dtype((datsp2 >= datbsr).todense(), dat2 >= dat)
assert_array_equal_dtype((datsp2 >= datcsc).todense(), dat2 >= dat)
assert_array_equal_dtype((datsp2 >= datcsr).todense(), dat2 >= dat)
assert_array_equal_dtype((datsp2 >= datlil).todense(), dat2 >= dat)
# sparse/dense
assert_array_equal_dtype(datsp >= dat2, dat >= dat2)
assert_array_equal_dtype(datspcomplex >= dat2, datcomplex >= dat2)
# sparse/scalar
assert_array_equal_dtype((datsp >= 2).todense(), dat >= 2)
assert_array_equal_dtype((datsp >= 1).todense(), dat >= 1)
assert_array_equal_dtype((datsp >= -1).todense(), dat >= -1)
assert_array_equal_dtype((datsp >= -2).todense(), dat >= -2)
assert_array_equal_dtype((2 >= datsp).todense(), 2 >= dat)
assert_array_equal_dtype((1 >= datsp).todense(), 1 >= dat)
assert_array_equal_dtype((-1 >= datsp).todense(), -1 >= dat)
assert_array_equal_dtype((-2 >= datsp).todense(), -2 >= dat)
# dense data
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
# dense rhs
assert_array_equal_dtype(dat >= datsp2, datsp >= dat2)
if not isinstance(self, (TestBSR, TestCSC, TestCSR)):
pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
for dtype in self.checked_dtypes:
check(dtype)
def test_empty(self):
# create empty matrices
assert_equal(self.spmatrix((3,3)).todense(), np.zeros((3,3)))
assert_equal(self.spmatrix((3,3)).nnz, 0)
assert_equal(self.spmatrix((3,3)).count_nonzero(), 0)
def test_count_nonzero(self):
expected = np.count_nonzero(self.datsp.toarray())
assert_equal(self.datsp.count_nonzero(), expected)
assert_equal(self.datsp.T.count_nonzero(), expected)
def test_invalid_shapes(self):
assert_raises(ValueError, self.spmatrix, (-1,3))
assert_raises(ValueError, self.spmatrix, (3,-1))
assert_raises(ValueError, self.spmatrix, (-1,-1))
def test_repr(self):
repr(self.datsp)
def test_str(self):
str(self.datsp)
def test_empty_arithmetic(self):
# Test manipulating empty matrices. Fails in SciPy SVN <= r1768
shape = (5, 5)
for mytype in [np.dtype('int32'), np.dtype('float32'),
np.dtype('float64'), np.dtype('complex64'),
np.dtype('complex128')]:
a = self.spmatrix(shape, dtype=mytype)
b = a + a
c = 2 * a
d = a * a.tocsc()
e = a * a.tocsr()
f = a * a.tocoo()
for m in [a,b,c,d,e,f]:
assert_equal(m.A, a.A*a.A)
# These fail in all revisions <= r1768:
assert_equal(m.dtype,mytype)
assert_equal(m.A.dtype,mytype)
def test_abs(self):
A = matrix([[-1, 0, 17],[0, -5, 0],[1, -4, 0],[0,0,0]],'d')
assert_equal(abs(A),abs(self.spmatrix(A)).todense())
def test_round(self):
decimal = 1
A = matrix([[-1.35, 0.56], [17.25, -5.98]], 'd')
assert_equal(np.around(A, decimals=decimal),
round(self.spmatrix(A), ndigits=decimal).todense())
def test_elementwise_power(self):
A = matrix([[-4, -3, -2],[-1, 0, 1],[2, 3, 4]], 'd')
assert_equal(np.power(A, 2), self.spmatrix(A).power(2).todense())
#it's element-wise power function, input has to be a scalar
assert_raises(NotImplementedError, self.spmatrix(A).power, A)
def test_neg(self):
A = matrix([[-1, 0, 17], [0, -5, 0], [1, -4, 0], [0, 0, 0]], 'd')
assert_equal(-A, (-self.spmatrix(A)).todense())
# see gh-5843
A = matrix([[True, False, False], [False, False, True]])
assert_raises(NotImplementedError, self.spmatrix(A).__neg__)
def test_real(self):
D = matrix([[1 + 3j, 2 - 4j]])
A = self.spmatrix(D)
assert_equal(A.real.todense(),D.real)
def test_imag(self):
D = matrix([[1 + 3j, 2 - 4j]])
A = self.spmatrix(D)
assert_equal(A.imag.todense(),D.imag)
def test_diagonal(self):
# Does the matrix's .diagonal() method work?
mats = []
mats.append([[1,0,2]])
mats.append([[1],[0],[2]])
mats.append([[0,1],[0,2],[0,3]])
mats.append([[0,0,1],[0,0,2],[0,3,0]])
mats.append(kron(mats[0],[[1,2]]))
mats.append(kron(mats[0],[[1],[2]]))
mats.append(kron(mats[1],[[1,2],[3,4]]))
mats.append(kron(mats[2],[[1,2],[3,4]]))
mats.append(kron(mats[3],[[1,2],[3,4]]))
mats.append(kron(mats[3],[[1,2,3,4]]))
for m in mats:
rows, cols = array(m).shape
sparse_mat = self.spmatrix(m)
for k in range(-rows-1, cols+2):
assert_equal(sparse_mat.diagonal(k=k), diag(m, k=k))
# Test for k beyond boundaries(issue #11949)
assert_equal(sparse_mat.diagonal(k=10), diag(m, k=10))
assert_equal(sparse_mat.diagonal(k=-99), diag(m, k=-99))
# Test all-zero matrix.
assert_equal(self.spmatrix((40, 16130)).diagonal(), np.zeros(40))
# Test empty matrix
# https://github.com/scipy/scipy/issues/11949
assert_equal(self.spmatrix((0, 0)).diagonal(), np.empty(0))
assert_equal(self.spmatrix((15, 0)).diagonal(), np.empty(0))
assert_equal(self.spmatrix((0, 5)).diagonal(10), np.empty(0))
def test_reshape(self):
# This first example is taken from the lil_matrix reshaping test.
x = self.spmatrix([[1, 0, 7], [0, 0, 0], [0, 3, 0], [0, 0, 5]])
for order in ['C', 'F']:
for s in [(12, 1), (1, 12)]:
assert_array_equal(x.reshape(s, order=order).todense(),
x.todense().reshape(s, order=order))
# This example is taken from the stackoverflow answer at
# https://stackoverflow.com/q/16511879
x = self.spmatrix([[0, 10, 0, 0], [0, 0, 0, 0], [0, 20, 30, 40]])
y = x.reshape((2, 6)) # Default order is 'C'
desired = [[0, 10, 0, 0, 0, 0], [0, 0, 0, 20, 30, 40]]
assert_array_equal(y.A, desired)
# Reshape with negative indexes
y = x.reshape((2, -1))
assert_array_equal(y.A, desired)
y = x.reshape((-1, 6))
assert_array_equal(y.A, desired)
assert_raises(ValueError, x.reshape, (-1, -1))
# Reshape with star args
y = x.reshape(2, 6)
assert_array_equal(y.A, desired)
assert_raises(TypeError, x.reshape, 2, 6, not_an_arg=1)
# Reshape with same size is noop unless copy=True
y = x.reshape((3, 4))
assert_(y is x)
y = x.reshape((3, 4), copy=True)
assert_(y is not x)
# Ensure reshape did not alter original size
assert_array_equal(x.shape, (3, 4))
# Reshape in place
x.shape = (2, 6)
assert_array_equal(x.A, desired)
# Reshape to bad ndim
assert_raises(ValueError, x.reshape, (x.size,))
assert_raises(ValueError, x.reshape, (1, x.size, 1))
@pytest.mark.slow
def test_setdiag_comprehensive(self):
def dense_setdiag(a, v, k):
v = np.asarray(v)
if k >= 0:
n = min(a.shape[0], a.shape[1] - k)
if v.ndim != 0:
n = min(n, len(v))
v = v[:n]
i = np.arange(0, n)
j = np.arange(k, k + n)
a[i,j] = v
elif k < 0:
dense_setdiag(a.T, v, -k)
def check_setdiag(a, b, k):
# Check setting diagonal using a scalar, a vector of
# correct length, and too short or too long vectors
for r in [-1, len(np.diag(a, k)), 2, 30]:
if r < 0:
v = np.random.choice(range(1, 20))
else:
v = np.random.randint(1, 20, size=r)
dense_setdiag(a, v, k)
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure of a cs[cr]_matrix is expensive")
b.setdiag(v, k)
# check that dense_setdiag worked
d = np.diag(a, k)
if np.asarray(v).ndim == 0:
assert_array_equal(d, v, err_msg="%s %d" % (msg, r))
else:
n = min(len(d), len(v))
assert_array_equal(d[:n], v[:n], err_msg="%s %d" % (msg, r))
# check that sparse setdiag worked
assert_array_equal(b.A, a, err_msg="%s %d" % (msg, r))
# comprehensive test
np.random.seed(1234)
shapes = [(0,5), (5,0), (1,5), (5,1), (5,5)]
for dtype in [np.int8, np.float64]:
for m,n in shapes:
ks = np.arange(-m+1, n-1)
for k in ks:
msg = repr((dtype, m, n, k))
a = np.zeros((m, n), dtype=dtype)
b = self.spmatrix((m, n), dtype=dtype)
check_setdiag(a, b, k)
# check overwriting etc
for k2 in np.random.choice(ks, size=min(len(ks), 5)):
check_setdiag(a, b, k2)
def test_setdiag(self):
# simple test cases
m = self.spmatrix(np.eye(3))
values = [3, 2, 1]
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
assert_raises(ValueError, m.setdiag, values, k=4)
m.setdiag(values)
assert_array_equal(m.diagonal(), values)
m.setdiag(values, k=1)
assert_array_equal(m.A, np.array([[3, 3, 0],
[0, 2, 2],
[0, 0, 1]]))
m.setdiag(values, k=-2)
assert_array_equal(m.A, np.array([[3, 3, 0],
[0, 2, 2],
[3, 0, 1]]))
m.setdiag((9,), k=2)
assert_array_equal(m.A[0,2], 9)
m.setdiag((9,), k=-2)
assert_array_equal(m.A[2,0], 9)
def test_nonzero(self):
A = array([[1, 0, 1],[0, 1, 1],[0, 0, 1]])
Asp = self.spmatrix(A)
A_nz = set([tuple(ij) for ij in transpose(A.nonzero())])
Asp_nz = set([tuple(ij) for ij in transpose(Asp.nonzero())])
assert_equal(A_nz, Asp_nz)
def test_numpy_nonzero(self):
# See gh-5987
A = array([[1, 0, 1], [0, 1, 1], [0, 0, 1]])
Asp = self.spmatrix(A)
A_nz = set([tuple(ij) for ij in transpose(np.nonzero(A))])
Asp_nz = set([tuple(ij) for ij in transpose(np.nonzero(Asp))])
assert_equal(A_nz, Asp_nz)
def test_getrow(self):
assert_array_equal(self.datsp.getrow(1).todense(), self.dat[1,:])
assert_array_equal(self.datsp.getrow(-1).todense(), self.dat[-1,:])
def test_getcol(self):
assert_array_equal(self.datsp.getcol(1).todense(), self.dat[:,1])
assert_array_equal(self.datsp.getcol(-1).todense(), self.dat[:,-1])
def test_sum(self):
np.random.seed(1234)
dat_1 = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
dat_2 = np.random.rand(5, 5)
dat_3 = np.array([[]])
dat_4 = np.zeros((40, 40))
dat_5 = sparse.rand(5, 5, density=1e-2).A
matrices = [dat_1, dat_2, dat_3, dat_4, dat_5]
def check(dtype, j):
dat = matrix(matrices[j], dtype=dtype)
datsp = self.spmatrix(dat, dtype=dtype)
with np.errstate(over='ignore'):
assert_array_almost_equal(dat.sum(), datsp.sum())
assert_equal(dat.sum().dtype, datsp.sum().dtype)
assert_(np.isscalar(datsp.sum(axis=None)))
assert_array_almost_equal(dat.sum(axis=None),
datsp.sum(axis=None))
assert_equal(dat.sum(axis=None).dtype,
datsp.sum(axis=None).dtype)
assert_array_almost_equal(dat.sum(axis=0), datsp.sum(axis=0))
assert_equal(dat.sum(axis=0).dtype, datsp.sum(axis=0).dtype)
assert_array_almost_equal(dat.sum(axis=1), datsp.sum(axis=1))
assert_equal(dat.sum(axis=1).dtype, datsp.sum(axis=1).dtype)
assert_array_almost_equal(dat.sum(axis=-2), datsp.sum(axis=-2))
assert_equal(dat.sum(axis=-2).dtype, datsp.sum(axis=-2).dtype)
assert_array_almost_equal(dat.sum(axis=-1), datsp.sum(axis=-1))
assert_equal(dat.sum(axis=-1).dtype, datsp.sum(axis=-1).dtype)
for dtype in self.checked_dtypes:
for j in range(len(matrices)):
check(dtype, j)
def test_sum_invalid_params(self):
out = asmatrix(np.zeros((1, 3)))
dat = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
assert_raises(ValueError, datsp.sum, axis=3)
assert_raises(TypeError, datsp.sum, axis=(0, 1))
assert_raises(TypeError, datsp.sum, axis=1.5)
assert_raises(ValueError, datsp.sum, axis=1, out=out)
def test_sum_dtype(self):
dat = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
def check(dtype):
dat_mean = dat.mean(dtype=dtype)
datsp_mean = datsp.mean(dtype=dtype)
assert_array_almost_equal(dat_mean, datsp_mean)
assert_equal(dat_mean.dtype, datsp_mean.dtype)
for dtype in self.checked_dtypes:
check(dtype)
def test_sum_out(self):
dat = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
dat_out = matrix(0)
datsp_out = matrix(0)
dat.sum(out=dat_out)
datsp.sum(out=datsp_out)
assert_array_almost_equal(dat_out, datsp_out)
dat_out = asmatrix(np.zeros((3, 1)))
datsp_out = asmatrix(np.zeros((3, 1)))
dat.sum(axis=1, out=dat_out)
datsp.sum(axis=1, out=datsp_out)
assert_array_almost_equal(dat_out, datsp_out)
def test_numpy_sum(self):
# See gh-5987
dat = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
dat_mean = np.sum(dat)
datsp_mean = np.sum(datsp)
assert_array_almost_equal(dat_mean, datsp_mean)
assert_equal(dat_mean.dtype, datsp_mean.dtype)
def test_mean(self):
def check(dtype):
dat = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]], dtype=dtype)
datsp = self.spmatrix(dat, dtype=dtype)
assert_array_almost_equal(dat.mean(), datsp.mean())
assert_equal(dat.mean().dtype, datsp.mean().dtype)
assert_(np.isscalar(datsp.mean(axis=None)))
assert_array_almost_equal(dat.mean(axis=None), datsp.mean(axis=None))
assert_equal(dat.mean(axis=None).dtype, datsp.mean(axis=None).dtype)
assert_array_almost_equal(dat.mean(axis=0), datsp.mean(axis=0))
assert_equal(dat.mean(axis=0).dtype, datsp.mean(axis=0).dtype)
assert_array_almost_equal(dat.mean(axis=1), datsp.mean(axis=1))
assert_equal(dat.mean(axis=1).dtype, datsp.mean(axis=1).dtype)
assert_array_almost_equal(dat.mean(axis=-2), datsp.mean(axis=-2))
assert_equal(dat.mean(axis=-2).dtype, datsp.mean(axis=-2).dtype)
assert_array_almost_equal(dat.mean(axis=-1), datsp.mean(axis=-1))
assert_equal(dat.mean(axis=-1).dtype, datsp.mean(axis=-1).dtype)
for dtype in self.checked_dtypes:
check(dtype)
def test_mean_invalid_params(self):
out = asmatrix(np.zeros((1, 3)))
dat = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
assert_raises(ValueError, datsp.mean, axis=3)
assert_raises(TypeError, datsp.mean, axis=(0, 1))
assert_raises(TypeError, datsp.mean, axis=1.5)
assert_raises(ValueError, datsp.mean, axis=1, out=out)
def test_mean_dtype(self):
dat = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
def check(dtype):
dat_mean = dat.mean(dtype=dtype)
datsp_mean = datsp.mean(dtype=dtype)
assert_array_almost_equal(dat_mean, datsp_mean)
assert_equal(dat_mean.dtype, datsp_mean.dtype)
for dtype in self.checked_dtypes:
check(dtype)
def test_mean_out(self):
dat = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
dat_out = matrix(0)
datsp_out = matrix(0)
dat.mean(out=dat_out)
datsp.mean(out=datsp_out)
assert_array_almost_equal(dat_out, datsp_out)
dat_out = asmatrix(np.zeros((3, 1)))
datsp_out = asmatrix(np.zeros((3, 1)))
dat.mean(axis=1, out=dat_out)
datsp.mean(axis=1, out=datsp_out)
assert_array_almost_equal(dat_out, datsp_out)
def test_numpy_mean(self):
# See gh-5987
dat = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
dat_mean = np.mean(dat)
datsp_mean = np.mean(datsp)
assert_array_almost_equal(dat_mean, datsp_mean)
assert_equal(dat_mean.dtype, datsp_mean.dtype)
def test_expm(self):
M = array([[1, 0, 2], [0, 0, 3], [-4, 5, 6]], float)
sM = self.spmatrix(M, shape=(3,3), dtype=float)
Mexp = scipy.linalg.expm(M)
N = array([[3., 0., 1.], [0., 2., 0.], [0., 0., 0.]])
sN = self.spmatrix(N, shape=(3,3), dtype=float)
Nexp = scipy.linalg.expm(N)
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning, "splu requires CSC matrix format")
sup.filter(SparseEfficiencyWarning,
"spsolve is more efficient when sparse b is in the CSC matrix format")
sup.filter(SparseEfficiencyWarning,
"spsolve requires A be CSC or CSR matrix format")
sMexp = expm(sM).todense()
sNexp = expm(sN).todense()
assert_array_almost_equal((sMexp - Mexp), zeros((3, 3)))
assert_array_almost_equal((sNexp - Nexp), zeros((3, 3)))
def test_inv(self):
def check(dtype):
M = array([[1, 0, 2], [0, 0, 3], [-4, 5, 6]], dtype)
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"spsolve requires A be CSC or CSR matrix format")
sup.filter(SparseEfficiencyWarning,
"spsolve is more efficient when sparse b is in the CSC matrix format")
sup.filter(SparseEfficiencyWarning,
"splu requires CSC matrix format")
sM = self.spmatrix(M, shape=(3,3), dtype=dtype)
sMinv = inv(sM)
assert_array_almost_equal(sMinv.dot(sM).todense(), np.eye(3))
assert_raises(TypeError, inv, M)
for dtype in [float]:
check(dtype)
@sup_complex
def test_from_array(self):
A = array([[1,0,0],[2,3,4],[0,5,0],[0,0,0]])
assert_array_equal(self.spmatrix(A).toarray(), A)
A = array([[1.0 + 3j, 0, 0],
[0, 2.0 + 5, 0],
[0, 0, 0]])
assert_array_equal(self.spmatrix(A).toarray(), A)
assert_array_equal(self.spmatrix(A, dtype='int16').toarray(), A.astype('int16'))
@sup_complex
def test_from_matrix(self):
A = matrix([[1,0,0],[2,3,4],[0,5,0],[0,0,0]])
assert_array_equal(self.spmatrix(A).todense(), A)
A = matrix([[1.0 + 3j, 0, 0],
[0, 2.0 + 5, 0],
[0, 0, 0]])
assert_array_equal(self.spmatrix(A).toarray(), A)
assert_array_equal(self.spmatrix(A, dtype='int16').toarray(), A.astype('int16'))
@sup_complex
def test_from_list(self):
A = [[1,0,0],[2,3,4],[0,5,0],[0,0,0]]
assert_array_equal(self.spmatrix(A).todense(), A)
A = [[1.0 + 3j, 0, 0],
[0, 2.0 + 5, 0],
[0, 0, 0]]
assert_array_equal(self.spmatrix(A).toarray(), array(A))
assert_array_equal(self.spmatrix(A, dtype='int16').todense(), array(A).astype('int16'))
@sup_complex
def test_from_sparse(self):
D = array([[1,0,0],[2,3,4],[0,5,0],[0,0,0]])
S = csr_matrix(D)
assert_array_equal(self.spmatrix(S).toarray(), D)
S = self.spmatrix(D)
assert_array_equal(self.spmatrix(S).toarray(), D)
D = array([[1.0 + 3j, 0, 0],
[0, 2.0 + 5, 0],
[0, 0, 0]])
S = csr_matrix(D)
assert_array_equal(self.spmatrix(S).toarray(), D)
assert_array_equal(self.spmatrix(S, dtype='int16').toarray(), D.astype('int16'))
S = self.spmatrix(D)
assert_array_equal(self.spmatrix(S).toarray(), D)
assert_array_equal(self.spmatrix(S, dtype='int16').toarray(), D.astype('int16'))
# def test_array(self):
# """test array(A) where A is in sparse format"""
# assert_equal( array(self.datsp), self.dat )
def test_todense(self):
# Check C- or F-contiguous (default).
chk = self.datsp.todense()
assert_array_equal(chk, self.dat)
assert_(chk.flags.c_contiguous != chk.flags.f_contiguous)
# Check C-contiguous (with arg).
chk = self.datsp.todense(order='C')
assert_array_equal(chk, self.dat)
assert_(chk.flags.c_contiguous)
assert_(not chk.flags.f_contiguous)
# Check F-contiguous (with arg).
chk = self.datsp.todense(order='F')
assert_array_equal(chk, self.dat)
assert_(not chk.flags.c_contiguous)
assert_(chk.flags.f_contiguous)
# Check with out argument (array).
out = np.zeros(self.datsp.shape, dtype=self.datsp.dtype)
chk = self.datsp.todense(out=out)
assert_array_equal(self.dat, out)
assert_array_equal(self.dat, chk)
assert_(chk.base is out)
# Check with out array (matrix).
out = asmatrix(np.zeros(self.datsp.shape, dtype=self.datsp.dtype))
chk = self.datsp.todense(out=out)
assert_array_equal(self.dat, out)
assert_array_equal(self.dat, chk)
assert_(chk is out)
a = array([[1.,2.,3.]])
dense_dot_dense = a @ self.dat
check = a * self.datsp.todense()
assert_array_equal(dense_dot_dense, check)
b = array([[1.,2.,3.,4.]]).T
dense_dot_dense = self.dat @ b
check2 = self.datsp.todense() @ b
assert_array_equal(dense_dot_dense, check2)
# Check bool data works.
spbool = self.spmatrix(self.dat, dtype=bool)
matbool = self.dat.astype(bool)
assert_array_equal(spbool.todense(), matbool)
def test_toarray(self):
# Check C- or F-contiguous (default).
dat = asarray(self.dat)
chk = self.datsp.toarray()
assert_array_equal(chk, dat)
assert_(chk.flags.c_contiguous != chk.flags.f_contiguous)
# Check C-contiguous (with arg).
chk = self.datsp.toarray(order='C')
assert_array_equal(chk, dat)
assert_(chk.flags.c_contiguous)
assert_(not chk.flags.f_contiguous)
# Check F-contiguous (with arg).
chk = self.datsp.toarray(order='F')
assert_array_equal(chk, dat)
assert_(not chk.flags.c_contiguous)
assert_(chk.flags.f_contiguous)
# Check with output arg.
out = np.zeros(self.datsp.shape, dtype=self.datsp.dtype)
self.datsp.toarray(out=out)
assert_array_equal(chk, dat)
# Check that things are fine when we don't initialize with zeros.
out[...] = 1.
self.datsp.toarray(out=out)
assert_array_equal(chk, dat)
a = array([1.,2.,3.])
dense_dot_dense = dot(a, dat)
check = dot(a, self.datsp.toarray())
assert_array_equal(dense_dot_dense, check)
b = array([1.,2.,3.,4.])
dense_dot_dense = dot(dat, b)
check2 = dot(self.datsp.toarray(), b)
assert_array_equal(dense_dot_dense, check2)
# Check bool data works.
spbool = self.spmatrix(self.dat, dtype=bool)
arrbool = dat.astype(bool)
assert_array_equal(spbool.toarray(), arrbool)
@sup_complex
def test_astype(self):
D = array([[2.0 + 3j, 0, 0],
[0, 4.0 + 5j, 0],
[0, 0, 0]])
S = self.spmatrix(D)
for x in supported_dtypes:
# Check correctly casted
D_casted = D.astype(x)
for copy in (True, False):
S_casted = S.astype(x, copy=copy)
assert_equal(S_casted.dtype, D_casted.dtype) # correct type
assert_equal(S_casted.toarray(), D_casted) # correct values
assert_equal(S_casted.format, S.format) # format preserved
# Check correctly copied
assert_(S_casted.astype(x, copy=False) is S_casted)
S_copied = S_casted.astype(x, copy=True)
assert_(S_copied is not S_casted)
def check_equal_but_not_same_array_attribute(attribute):
a = getattr(S_casted, attribute)
b = getattr(S_copied, attribute)
assert_array_equal(a, b)
assert_(a is not b)
i = (0,) * b.ndim
b_i = b[i]
b[i] = not b[i]
assert_(a[i] != b[i])
b[i] = b_i
if S_casted.format in ('csr', 'csc', 'bsr'):
for attribute in ('indices', 'indptr', 'data'):
check_equal_but_not_same_array_attribute(attribute)
elif S_casted.format == 'coo':
for attribute in ('row', 'col', 'data'):
check_equal_but_not_same_array_attribute(attribute)
elif S_casted.format == 'dia':
for attribute in ('offsets', 'data'):
check_equal_but_not_same_array_attribute(attribute)
def test_asfptype(self):
A = self.spmatrix(arange(6,dtype='int32').reshape(2,3))
assert_equal(A.dtype, np.dtype('int32'))
assert_equal(A.asfptype().dtype, np.dtype('float64'))
assert_equal(A.asfptype().format, A.format)
assert_equal(A.astype('int16').asfptype().dtype, np.dtype('float32'))
assert_equal(A.astype('complex128').asfptype().dtype, np.dtype('complex128'))
B = A.asfptype()
C = B.asfptype()
assert_(B is C)
def test_mul_scalar(self):
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
assert_array_equal(dat*2,(datsp*2).todense())
assert_array_equal(dat*17.3,(datsp*17.3).todense())
for dtype in self.math_dtypes:
check(dtype)
def test_rmul_scalar(self):
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
assert_array_equal(2*dat,(2*datsp).todense())
assert_array_equal(17.3*dat,(17.3*datsp).todense())
for dtype in self.math_dtypes:
check(dtype)
def test_add(self):
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
a = dat.copy()
a[0,2] = 2.0
b = datsp
c = b + a
assert_array_equal(c, b.todense() + a)
c = b + b.tocsr()
assert_array_equal(c.todense(),
b.todense() + b.todense())
# test broadcasting
c = b + a[0]
assert_array_equal(c, b.todense() + a[0])
for dtype in self.math_dtypes:
check(dtype)
def test_radd(self):
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
a = dat.copy()
a[0,2] = 2.0
b = datsp
c = a + b
assert_array_equal(c, a + b.todense())
for dtype in self.math_dtypes:
check(dtype)
def test_sub(self):
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
assert_array_equal((datsp - datsp).todense(),[[0,0,0,0],[0,0,0,0],[0,0,0,0]])
assert_array_equal((datsp - 0).todense(), dat)
A = self.spmatrix(matrix([[1,0,0,4],[-1,0,0,0],[0,8,0,-5]],'d'))
assert_array_equal((datsp - A).todense(),dat - A.todense())
assert_array_equal((A - datsp).todense(),A.todense() - dat)
# test broadcasting
assert_array_equal(datsp - dat[0], dat - dat[0])
for dtype in self.math_dtypes:
if dtype == np.dtype('bool'):
# boolean array subtraction deprecated in 1.9.0
continue
check(dtype)
def test_rsub(self):
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
assert_array_equal((dat - datsp),[[0,0,0,0],[0,0,0,0],[0,0,0,0]])
assert_array_equal((datsp - dat),[[0,0,0,0],[0,0,0,0],[0,0,0,0]])
assert_array_equal((0 - datsp).todense(), -dat)
A = self.spmatrix(matrix([[1,0,0,4],[-1,0,0,0],[0,8,0,-5]],'d'))
assert_array_equal((dat - A),dat - A.todense())
assert_array_equal((A - dat),A.todense() - dat)
assert_array_equal(A.todense() - datsp,A.todense() - dat)
assert_array_equal(datsp - A.todense(),dat - A.todense())
# test broadcasting
assert_array_equal(dat[0] - datsp, dat[0] - dat)
for dtype in self.math_dtypes:
if dtype == np.dtype('bool'):
# boolean array subtraction deprecated in 1.9.0
continue
check(dtype)
def test_add0(self):
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
# Adding 0 to a sparse matrix
assert_array_equal((datsp + 0).todense(), dat)
# use sum (which takes 0 as a starting value)
sumS = sum([k * datsp for k in range(1, 3)])
sumD = sum([k * dat for k in range(1, 3)])
assert_almost_equal(sumS.todense(), sumD)
for dtype in self.math_dtypes:
check(dtype)
def test_elementwise_multiply(self):
# real/real
A = array([[4,0,9],[2,-3,5]])
B = array([[0,7,0],[0,-4,0]])
Asp = self.spmatrix(A)
Bsp = self.spmatrix(B)
assert_almost_equal(Asp.multiply(Bsp).todense(), A*B) # sparse/sparse
assert_almost_equal(Asp.multiply(B).todense(), A*B) # sparse/dense
# complex/complex
C = array([[1-2j,0+5j,-1+0j],[4-3j,-3+6j,5]])
D = array([[5+2j,7-3j,-2+1j],[0-1j,-4+2j,9]])
Csp = self.spmatrix(C)
Dsp = self.spmatrix(D)
assert_almost_equal(Csp.multiply(Dsp).todense(), C*D) # sparse/sparse
assert_almost_equal(Csp.multiply(D).todense(), C*D) # sparse/dense
# real/complex
assert_almost_equal(Asp.multiply(Dsp).todense(), A*D) # sparse/sparse
assert_almost_equal(Asp.multiply(D).todense(), A*D) # sparse/dense
def test_elementwise_multiply_broadcast(self):
A = array([4])
B = array([[-9]])
C = array([1,-1,0])
D = array([[7,9,-9]])
E = array([[3],[2],[1]])
F = array([[8,6,3],[-4,3,2],[6,6,6]])
G = [1, 2, 3]
H = np.ones((3, 4))
J = H.T
K = array([[0]])
L = array([[[1,2],[0,1]]])
# Some arrays can't be cast as spmatrices (A,C,L) so leave
# them out.
Bsp = self.spmatrix(B)
Dsp = self.spmatrix(D)
Esp = self.spmatrix(E)
Fsp = self.spmatrix(F)
Hsp = self.spmatrix(H)
Hspp = self.spmatrix(H[0,None])
Jsp = self.spmatrix(J)
Jspp = self.spmatrix(J[:,0,None])
Ksp = self.spmatrix(K)
matrices = [A, B, C, D, E, F, G, H, J, K, L]
spmatrices = [Bsp, Dsp, Esp, Fsp, Hsp, Hspp, Jsp, Jspp, Ksp]
# sparse/sparse
for i in spmatrices:
for j in spmatrices:
try:
dense_mult = np.multiply(i.todense(), j.todense())
except ValueError:
assert_raises(ValueError, i.multiply, j)
continue
sp_mult = i.multiply(j)
assert_almost_equal(sp_mult.todense(), dense_mult)
# sparse/dense
for i in spmatrices:
for j in matrices:
try:
dense_mult = np.multiply(i.todense(), j)
except TypeError:
continue
except ValueError:
assert_raises(ValueError, i.multiply, j)
continue
sp_mult = i.multiply(j)
if isspmatrix(sp_mult):
assert_almost_equal(sp_mult.todense(), dense_mult)
else:
assert_almost_equal(sp_mult, dense_mult)
def test_elementwise_divide(self):
expected = [[1,np.nan,np.nan,1],
[1,np.nan,1,np.nan],
[np.nan,1,np.nan,np.nan]]
assert_array_equal(todense(self.datsp / self.datsp),expected)
denom = self.spmatrix(matrix([[1,0,0,4],[-1,0,0,0],[0,8,0,-5]],'d'))
expected = [[1,np.nan,np.nan,0.5],
[-3,np.nan,inf,np.nan],
[np.nan,0.25,np.nan,0]]
assert_array_equal(todense(self.datsp / denom), expected)
# complex
A = array([[1-2j,0+5j,-1+0j],[4-3j,-3+6j,5]])
B = array([[5+2j,7-3j,-2+1j],[0-1j,-4+2j,9]])
Asp = self.spmatrix(A)
Bsp = self.spmatrix(B)
assert_almost_equal(todense(Asp / Bsp), A/B)
# integer
A = array([[1,2,3],[-3,2,1]])
B = array([[0,1,2],[0,-2,3]])
Asp = self.spmatrix(A)
Bsp = self.spmatrix(B)
with np.errstate(divide='ignore'):
assert_array_equal(todense(Asp / Bsp), A / B)
# mismatching sparsity patterns
A = array([[0,1],[1,0]])
B = array([[1,0],[1,0]])
Asp = self.spmatrix(A)
Bsp = self.spmatrix(B)
with np.errstate(divide='ignore', invalid='ignore'):
assert_array_equal(np.array(todense(Asp / Bsp)), A / B)
def test_pow(self):
A = matrix([[1,0,2,0],[0,3,4,0],[0,5,0,0],[0,6,7,8]])
B = self.spmatrix(A)
for exponent in [0,1,2,3]:
assert_array_equal((B**exponent).todense(),A**exponent)
# invalid exponents
for exponent in [-1, 2.2, 1 + 3j]:
assert_raises(Exception, B.__pow__, exponent)
# nonsquare matrix
B = self.spmatrix(A[:3,:])
assert_raises(Exception, B.__pow__, 1)
def test_rmatvec(self):
M = self.spmatrix(matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]))
assert_array_almost_equal([1,2,3,4]*M, dot([1,2,3,4], M.toarray()))
row = array([[1,2,3,4]])
assert_array_almost_equal(row * M, row @ M.todense())
def test_small_multiplication(self):
# test that A*x works for x with shape () (1,) (1,1) and (1,0)
A = self.spmatrix([[1],[2],[3]])
assert_(isspmatrix(A * array(1)))
assert_equal((A * array(1)).todense(), [[1],[2],[3]])
assert_equal(A * array([1]), array([1,2,3]))
assert_equal(A * array([[1]]), array([[1],[2],[3]]))
assert_equal(A * np.ones((1,0)), np.ones((3,0)))
def test_binop_custom_type(self):
# Non-regression test: previously, binary operations would raise
# NotImplementedError instead of returning NotImplemented
# (https://docs.python.org/library/constants.html#NotImplemented)
# so overloading Custom + matrix etc. didn't work.
A = self.spmatrix([[1], [2], [3]])
B = BinopTester()
assert_equal(A + B, "matrix on the left")
assert_equal(A - B, "matrix on the left")
assert_equal(A * B, "matrix on the left")
assert_equal(B + A, "matrix on the right")
assert_equal(B - A, "matrix on the right")
assert_equal(B * A, "matrix on the right")
assert_equal(eval('A @ B'), "matrix on the left")
assert_equal(eval('B @ A'), "matrix on the right")
def test_binop_custom_type_with_shape(self):
A = self.spmatrix([[1], [2], [3]])
B = BinopTester_with_shape((3,1))
assert_equal(A + B, "matrix on the left")
assert_equal(A - B, "matrix on the left")
assert_equal(A * B, "matrix on the left")
assert_equal(B + A, "matrix on the right")
assert_equal(B - A, "matrix on the right")
assert_equal(B * A, "matrix on the right")
assert_equal(eval('A @ B'), "matrix on the left")
assert_equal(eval('B @ A'), "matrix on the right")
def test_matmul(self):
M = self.spmatrix(array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]))
B = self.spmatrix(array([[0,1],[1,0],[0,2]],'d'))
col = array([[1,2,3]]).T
# check matrix-vector
assert_array_almost_equal(operator.matmul(M, col),
M.todense() @ col)
# check matrix-matrix
assert_array_almost_equal(operator.matmul(M, B).todense(),
(M * B).todense())
assert_array_almost_equal(operator.matmul(M.todense(), B),
(M * B).todense())
assert_array_almost_equal(operator.matmul(M, B.todense()),
(M * B).todense())
# check error on matrix-scalar
assert_raises(ValueError, operator.matmul, M, 1)
assert_raises(ValueError, operator.matmul, 1, M)
def test_matvec(self):
M = self.spmatrix(matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]))
col = array([[1,2,3]]).T
assert_array_almost_equal(M * col, M.todense() @ col)
# check result dimensions (ticket #514)
assert_equal((M * array([1,2,3])).shape,(4,))
assert_equal((M * array([[1],[2],[3]])).shape,(4,1))
assert_equal((M * matrix([[1],[2],[3]])).shape,(4,1))
# check result type
assert_(isinstance(M * array([1,2,3]), ndarray))
assert_(isinstance(M * matrix([1,2,3]).T, np.matrix))
# ensure exception is raised for improper dimensions
bad_vecs = [array([1,2]), array([1,2,3,4]), array([[1],[2]]),
matrix([1,2,3]), matrix([[1],[2]])]
for x in bad_vecs:
assert_raises(ValueError, M.__mul__, x)
# Should this be supported or not?!
# flat = array([1,2,3])
# assert_array_almost_equal(M*flat, M.todense()*flat)
# Currently numpy dense matrices promote the result to a 1x3 matrix,
# whereas sparse matrices leave the result as a rank-1 array. Which
# is preferable?
# Note: the following command does not work. Both NumPy matrices
# and spmatrices should raise exceptions!
# assert_array_almost_equal(M*[1,2,3], M.todense()*[1,2,3])
# The current relationship between sparse matrix products and array
# products is as follows:
assert_array_almost_equal(M*array([1,2,3]), dot(M.A,[1,2,3]))
assert_array_almost_equal(M*[[1],[2],[3]], asmatrix(dot(M.A,[1,2,3])).T)
# Note that the result of M * x is dense if x has a singleton dimension.
# Currently M.matvec(asarray(col)) is rank-1, whereas M.matvec(col)
# is rank-2. Is this desirable?
def test_matmat_sparse(self):
a = matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])
a2 = array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])
b = matrix([[0,1],[1,0],[0,2]],'d')
asp = self.spmatrix(a)
bsp = self.spmatrix(b)
assert_array_almost_equal((asp*bsp).todense(), a@b)
assert_array_almost_equal(asp*b, a@b)
assert_array_almost_equal(a*bsp, a@b)
assert_array_almost_equal(a2*bsp, a@b)
# Now try performing cross-type multplication:
csp = bsp.tocsc()
c = b
want = a@c
assert_array_almost_equal((asp*csp).todense(), want)
assert_array_almost_equal(asp*c, want)
assert_array_almost_equal(a*csp, want)
assert_array_almost_equal(a2*csp, want)
csp = bsp.tocsr()
assert_array_almost_equal((asp*csp).todense(), want)
assert_array_almost_equal(asp*c, want)
assert_array_almost_equal(a*csp, want)
assert_array_almost_equal(a2*csp, want)
csp = bsp.tocoo()
assert_array_almost_equal((asp*csp).todense(), want)
assert_array_almost_equal(asp*c, want)
assert_array_almost_equal(a*csp, want)
assert_array_almost_equal(a2*csp, want)
# Test provided by Andy Fraser, 2006-03-26
L = 30
frac = .3
random.seed(0) # make runs repeatable
A = zeros((L,2))
for i in range(L):
for j in range(2):
r = random.random()
if r < frac:
A[i,j] = r/frac
A = self.spmatrix(A)
B = A*A.T
assert_array_almost_equal(B.todense(), A.todense() @ A.T.todense())
assert_array_almost_equal(B.todense(), A.todense() @ A.todense().T)
# check dimension mismatch 2x2 times 3x2
A = self.spmatrix([[1,2],[3,4]])
B = self.spmatrix([[1,2],[3,4],[5,6]])
assert_raises(ValueError, A.__mul__, B)
def test_matmat_dense(self):
a = matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])
asp = self.spmatrix(a)
# check both array and matrix types
bs = [array([[1,2],[3,4],[5,6]]), matrix([[1,2],[3,4],[5,6]])]
for b in bs:
result = asp*b
assert_(isinstance(result, type(b)))
assert_equal(result.shape, (4,2))
assert_equal(result, dot(a,b))
def test_sparse_format_conversions(self):
A = sparse.kron([[1,0,2],[0,3,4],[5,0,0]], [[1,2],[0,3]])
D = A.todense()
A = self.spmatrix(A)
for format in ['bsr','coo','csc','csr','dia','dok','lil']:
a = A.asformat(format)
assert_equal(a.format,format)
assert_array_equal(a.todense(), D)
b = self.spmatrix(D+3j).asformat(format)
assert_equal(b.format,format)
assert_array_equal(b.todense(), D+3j)
c = eval(format + '_matrix')(A)
assert_equal(c.format,format)
assert_array_equal(c.todense(), D)
for format in ['array', 'dense']:
a = A.asformat(format)
assert_array_equal(a, D)
b = self.spmatrix(D+3j).asformat(format)
assert_array_equal(b, D+3j)
def test_tobsr(self):
x = array([[1,0,2,0],[0,0,0,0],[0,0,4,5]])
y = array([[0,1,2],[3,0,5]])
A = kron(x,y)
Asp = self.spmatrix(A)
for format in ['bsr']:
fn = getattr(Asp, 'to' + format)
for X in [1, 2, 3, 6]:
for Y in [1, 2, 3, 4, 6, 12]:
assert_equal(fn(blocksize=(X,Y)).todense(), A)
def test_transpose(self):
dat_1 = self.dat
dat_2 = np.array([[]])
matrices = [dat_1, dat_2]
def check(dtype, j):
dat = matrix(matrices[j], dtype=dtype)
datsp = self.spmatrix(dat)
a = datsp.transpose()
b = dat.transpose()
assert_array_equal(a.todense(), b)
assert_array_equal(a.transpose().todense(), dat)
assert_equal(a.dtype, b.dtype)
# See gh-5987
empty = self.spmatrix((3, 4))
assert_array_equal(np.transpose(empty).todense(),
np.transpose(zeros((3, 4))))
assert_array_equal(empty.T.todense(), zeros((4, 3)))
assert_raises(ValueError, empty.transpose, axes=0)
for dtype in self.checked_dtypes:
for j in range(len(matrices)):
check(dtype, j)
def test_add_dense(self):
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
# adding a dense matrix to a sparse matrix
sum1 = dat + datsp
assert_array_equal(sum1, dat + dat)
sum2 = datsp + dat
assert_array_equal(sum2, dat + dat)
for dtype in self.math_dtypes:
check(dtype)
def test_sub_dense(self):
# subtracting a dense matrix to/from a sparse matrix
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
# Behavior is different for bool.
if dat.dtype == bool:
sum1 = dat - datsp
assert_array_equal(sum1, dat - dat)
sum2 = datsp - dat
assert_array_equal(sum2, dat - dat)
else:
# Manually add to avoid upcasting from scalar
# multiplication.
sum1 = (dat + dat + dat) - datsp
assert_array_equal(sum1, dat + dat)
sum2 = (datsp + datsp + datsp) - dat
assert_array_equal(sum2, dat + dat)
for dtype in self.math_dtypes:
if dtype == np.dtype('bool'):
# boolean array subtraction deprecated in 1.9.0
continue
check(dtype)
def test_maximum_minimum(self):
A_dense = np.array([[1, 0, 3], [0, 4, 5], [0, 0, 0]])
B_dense = np.array([[1, 1, 2], [0, 3, 6], [1, -1, 0]])
A_dense_cpx = np.array([[1, 0, 3], [0, 4+2j, 5], [0, 1j, -1j]])
def check(dtype, dtype2, btype):
if np.issubdtype(dtype, np.complexfloating):
A = self.spmatrix(A_dense_cpx.astype(dtype))
else:
A = self.spmatrix(A_dense.astype(dtype))
if btype == 'scalar':
B = dtype2.type(1)
elif btype == 'scalar2':
B = dtype2.type(-1)
elif btype == 'dense':
B = B_dense.astype(dtype2)
elif btype == 'sparse':
B = self.spmatrix(B_dense.astype(dtype2))
else:
raise ValueError()
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Taking maximum .minimum. with > 0 .< 0. number results to a dense matrix")
max_s = A.maximum(B)
min_s = A.minimum(B)
max_d = np.maximum(todense(A), todense(B))
assert_array_equal(todense(max_s), max_d)
assert_equal(max_s.dtype, max_d.dtype)
min_d = np.minimum(todense(A), todense(B))
assert_array_equal(todense(min_s), min_d)
assert_equal(min_s.dtype, min_d.dtype)
for dtype in self.math_dtypes:
for dtype2 in [np.int8, np.float_, np.complex_]:
for btype in ['scalar', 'scalar2', 'dense', 'sparse']:
check(np.dtype(dtype), np.dtype(dtype2), btype)
def test_copy(self):
# Check whether the copy=True and copy=False keywords work
A = self.datsp
# check that copy preserves format
assert_equal(A.copy().format, A.format)
assert_equal(A.__class__(A,copy=True).format, A.format)
assert_equal(A.__class__(A,copy=False).format, A.format)
assert_equal(A.copy().todense(), A.todense())
assert_equal(A.__class__(A,copy=True).todense(), A.todense())
assert_equal(A.__class__(A,copy=False).todense(), A.todense())
# check that XXX_matrix.toXXX() works
toself = getattr(A,'to' + A.format)
assert_(toself() is A)
assert_(toself(copy=False) is A)
assert_equal(toself(copy=True).format, A.format)
assert_equal(toself(copy=True).todense(), A.todense())
# check whether the data is copied?
assert_(not sparse_may_share_memory(A.copy(), A))
# test that __iter__ is compatible with NumPy matrix
def test_iterator(self):
B = matrix(np.arange(50).reshape(5, 10))
A = self.spmatrix(B)
for x, y in zip(A, B):
assert_equal(x.todense(), y)
def test_size_zero_matrix_arithmetic(self):
# Test basic matrix arithmetic with shapes like (0,0), (10,0),
# (0, 3), etc.
mat = matrix([])
a = mat.reshape((0, 0))
b = mat.reshape((0, 1))
c = mat.reshape((0, 5))
d = mat.reshape((1, 0))
e = mat.reshape((5, 0))
f = matrix(np.ones([5, 5]))
asp = self.spmatrix(a)
bsp = self.spmatrix(b)
csp = self.spmatrix(c)
dsp = self.spmatrix(d)
esp = self.spmatrix(e)
fsp = self.spmatrix(f)
# matrix product.
assert_array_equal(asp.dot(asp).A, np.dot(a, a).A)
assert_array_equal(bsp.dot(dsp).A, np.dot(b, d).A)
assert_array_equal(dsp.dot(bsp).A, np.dot(d, b).A)
assert_array_equal(csp.dot(esp).A, np.dot(c, e).A)
assert_array_equal(csp.dot(fsp).A, np.dot(c, f).A)
assert_array_equal(esp.dot(csp).A, np.dot(e, c).A)
assert_array_equal(dsp.dot(csp).A, np.dot(d, c).A)
assert_array_equal(fsp.dot(esp).A, np.dot(f, e).A)
# bad matrix products
assert_raises(ValueError, dsp.dot, e)
assert_raises(ValueError, asp.dot, d)
# elemente-wise multiplication
assert_array_equal(asp.multiply(asp).A, np.multiply(a, a).A)
assert_array_equal(bsp.multiply(bsp).A, np.multiply(b, b).A)
assert_array_equal(dsp.multiply(dsp).A, np.multiply(d, d).A)
assert_array_equal(asp.multiply(a).A, np.multiply(a, a).A)
assert_array_equal(bsp.multiply(b).A, np.multiply(b, b).A)
assert_array_equal(dsp.multiply(d).A, np.multiply(d, d).A)
assert_array_equal(asp.multiply(6).A, np.multiply(a, 6).A)
assert_array_equal(bsp.multiply(6).A, np.multiply(b, 6).A)
assert_array_equal(dsp.multiply(6).A, np.multiply(d, 6).A)
# bad element-wise multiplication
assert_raises(ValueError, asp.multiply, c)
assert_raises(ValueError, esp.multiply, c)
# Addition
assert_array_equal(asp.__add__(asp).A, a.__add__(a).A)
assert_array_equal(bsp.__add__(bsp).A, b.__add__(b).A)
assert_array_equal(dsp.__add__(dsp).A, d.__add__(d).A)
# bad addition
assert_raises(ValueError, asp.__add__, dsp)
assert_raises(ValueError, bsp.__add__, asp)
def test_size_zero_conversions(self):
mat = matrix([])
a = mat.reshape((0, 0))
b = mat.reshape((0, 5))
c = mat.reshape((5, 0))
for m in [a, b, c]:
spm = self.spmatrix(m)
assert_array_equal(spm.tocoo().A, m)
assert_array_equal(spm.tocsr().A, m)
assert_array_equal(spm.tocsc().A, m)
assert_array_equal(spm.tolil().A, m)
assert_array_equal(spm.todok().A, m)
assert_array_equal(spm.tobsr().A, m)
def test_pickle(self):
import pickle
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
def check():
datsp = self.datsp.copy()
for protocol in range(pickle.HIGHEST_PROTOCOL):
sploaded = pickle.loads(pickle.dumps(datsp, protocol=protocol))
assert_equal(datsp.shape, sploaded.shape)
assert_array_equal(datsp.toarray(), sploaded.toarray())
assert_equal(datsp.format, sploaded.format)
for key, val in datsp.__dict__.items():
if isinstance(val, np.ndarray):
assert_array_equal(val, sploaded.__dict__[key])
else:
assert_(val == sploaded.__dict__[key])
check()
def test_unary_ufunc_overrides(self):
def check(name):
if name == "sign":
pytest.skip("sign conflicts with comparison op "
"support on Numpy")
if self.spmatrix in (dok_matrix, lil_matrix):
pytest.skip("Unary ops not implemented for dok/lil")
ufunc = getattr(np, name)
X = self.spmatrix(np.arange(20).reshape(4, 5) / 20.)
X0 = ufunc(X.toarray())
X2 = ufunc(X)
assert_array_equal(X2.toarray(), X0)
for name in ["sin", "tan", "arcsin", "arctan", "sinh", "tanh",
"arcsinh", "arctanh", "rint", "sign", "expm1", "log1p",
"deg2rad", "rad2deg", "floor", "ceil", "trunc", "sqrt",
"abs"]:
check(name)
def test_resize(self):
# resize(shape) resizes the matrix in-place
D = np.array([[1, 0, 3, 4],
[2, 0, 0, 0],
[3, 0, 0, 0]])
S = self.spmatrix(D)
assert_(S.resize((3, 2)) is None)
assert_array_equal(S.A, [[1, 0],
[2, 0],
[3, 0]])
S.resize((2, 2))
assert_array_equal(S.A, [[1, 0],
[2, 0]])
S.resize((3, 2))
assert_array_equal(S.A, [[1, 0],
[2, 0],
[0, 0]])
S.resize((3, 3))
assert_array_equal(S.A, [[1, 0, 0],
[2, 0, 0],
[0, 0, 0]])
# test no-op
S.resize((3, 3))
assert_array_equal(S.A, [[1, 0, 0],
[2, 0, 0],
[0, 0, 0]])
# test *args
S.resize(3, 2)
assert_array_equal(S.A, [[1, 0],
[2, 0],
[0, 0]])
for bad_shape in [1, (-1, 2), (2, -1), (1, 2, 3)]:
assert_raises(ValueError, S.resize, bad_shape)
def test_constructor1_base(self):
A = self.datsp
self_format = A.format
C = A.__class__(A, copy=False)
assert_array_equal_dtype(A.todense(), C.todense())
if self_format not in NON_ARRAY_BACKED_FORMATS:
assert_(sparse_may_share_memory(A, C))
C = A.__class__(A, dtype=A.dtype, copy=False)
assert_array_equal_dtype(A.todense(), C.todense())
if self_format not in NON_ARRAY_BACKED_FORMATS:
assert_(sparse_may_share_memory(A, C))
C = A.__class__(A, dtype=np.float32, copy=False)
assert_array_equal(A.todense(), C.todense())
C = A.__class__(A, copy=True)
assert_array_equal_dtype(A.todense(), C.todense())
assert_(not sparse_may_share_memory(A, C))
for other_format in ['csr', 'csc', 'coo', 'dia', 'dok', 'lil']:
if other_format == self_format:
continue
B = A.asformat(other_format)
C = A.__class__(B, copy=False)
assert_array_equal_dtype(A.todense(), C.todense())
C = A.__class__(B, copy=True)
assert_array_equal_dtype(A.todense(), C.todense())
assert_(not sparse_may_share_memory(B, C))
class _TestInplaceArithmetic(object):
def test_inplace_dense(self):
a = np.ones((3, 4))
b = self.spmatrix(a)
x = a.copy()
y = a.copy()
x += a
y += b
assert_array_equal(x, y)
x = a.copy()
y = a.copy()
x -= a
y -= b
assert_array_equal(x, y)
# This is matrix product, from __rmul__
assert_raises(ValueError, operator.imul, x, b)
x = a.copy()
y = a.copy()
x = x.dot(a.T)
y *= b.T
assert_array_equal(x, y)
# Matrix (non-elementwise) floor division is not defined
assert_raises(TypeError, operator.ifloordiv, x, b)
def test_imul_scalar(self):
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
# Avoid implicit casting.
if np.can_cast(type(2), dtype, casting='same_kind'):
a = datsp.copy()
a *= 2
b = dat.copy()
b *= 2
assert_array_equal(b, a.todense())
if np.can_cast(type(17.3), dtype, casting='same_kind'):
a = datsp.copy()
a *= 17.3
b = dat.copy()
b *= 17.3
assert_array_equal(b, a.todense())
for dtype in self.math_dtypes:
check(dtype)
def test_idiv_scalar(self):
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
if np.can_cast(type(2), dtype, casting='same_kind'):
a = datsp.copy()
a /= 2
b = dat.copy()
b /= 2
assert_array_equal(b, a.todense())
if np.can_cast(type(17.3), dtype, casting='same_kind'):
a = datsp.copy()
a /= 17.3
b = dat.copy()
b /= 17.3
assert_array_equal(b, a.todense())
for dtype in self.math_dtypes:
# /= should only be used with float dtypes to avoid implicit
# casting.
if not np.can_cast(dtype, np.int_):
check(dtype)
def test_inplace_success(self):
# Inplace ops should work even if a specialized version is not
# implemented, falling back to x = x <op> y
a = self.spmatrix(np.eye(5))
b = self.spmatrix(np.eye(5))
bp = self.spmatrix(np.eye(5))
b += a
bp = bp + a
assert_allclose(b.A, bp.A)
b *= a
bp = bp * a
assert_allclose(b.A, bp.A)
b -= a
bp = bp - a
assert_allclose(b.A, bp.A)
assert_raises(TypeError, operator.ifloordiv, a, b)
class _TestGetSet(object):
def test_getelement(self):
def check(dtype):
D = array([[1,0,0],
[4,3,0],
[0,2,0],
[0,0,0]], dtype=dtype)
A = self.spmatrix(D)
M,N = D.shape
for i in range(-M, M):
for j in range(-N, N):
assert_equal(A[i,j], D[i,j])
assert_equal(type(A[1,1]), dtype)
for ij in [(0,3),(-1,3),(4,0),(4,3),(4,-1), (1, 2, 3)]:
assert_raises((IndexError, TypeError), A.__getitem__, ij)
for dtype in supported_dtypes:
check(np.dtype(dtype))
def test_setelement(self):
def check(dtype):
A = self.spmatrix((3,4), dtype=dtype)
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
A[0, 0] = dtype.type(0) # bug 870
A[1, 2] = dtype.type(4.0)
A[0, 1] = dtype.type(3)
A[2, 0] = dtype.type(2.0)
A[0,-1] = dtype.type(8)
A[-1,-2] = dtype.type(7)
A[0, 1] = dtype.type(5)
if dtype != np.bool_:
assert_array_equal(A.todense(),[[0,5,0,8],[0,0,4,0],[2,0,7,0]])
for ij in [(0,4),(-1,4),(3,0),(3,4),(3,-1)]:
assert_raises(IndexError, A.__setitem__, ij, 123.0)
for v in [[1,2,3], array([1,2,3])]:
assert_raises(ValueError, A.__setitem__, (0,0), v)
if (not np.issubdtype(dtype, np.complexfloating) and
dtype != np.bool_):
for v in [3j]:
assert_raises(TypeError, A.__setitem__, (0,0), v)
for dtype in supported_dtypes:
check(np.dtype(dtype))
def test_negative_index_assignment(self):
# Regression test for github issue 4428.
def check(dtype):
A = self.spmatrix((3, 10), dtype=dtype)
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
A[0, -4] = 1
assert_equal(A[0, -4], 1)
for dtype in self.math_dtypes:
check(np.dtype(dtype))
def test_scalar_assign_2(self):
n, m = (5, 10)
def _test_set(i, j, nitems):
msg = "%r ; %r ; %r" % (i, j, nitems)
A = self.spmatrix((n, m))
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
A[i, j] = 1
assert_almost_equal(A.sum(), nitems, err_msg=msg)
assert_almost_equal(A[i, j], 1, err_msg=msg)
# [i,j]
for i, j in [(2, 3), (-1, 8), (-1, -2), (array(-1), -2), (-1, array(-2)),
(array(-1), array(-2))]:
_test_set(i, j, 1)
def test_index_scalar_assign(self):
A = self.spmatrix((5, 5))
B = np.zeros((5, 5))
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
for C in [A, B]:
C[0,1] = 1
C[3,0] = 4
C[3,0] = 9
assert_array_equal(A.toarray(), B)
class _TestSolve(object):
def test_solve(self):
# Test whether the lu_solve command segfaults, as reported by Nils
# Wagner for a 64-bit machine, 02 March 2005 (EJS)
n = 20
np.random.seed(0) # make tests repeatable
A = zeros((n,n), dtype=complex)
x = np.random.rand(n)
y = np.random.rand(n-1)+1j*np.random.rand(n-1)
r = np.random.rand(n)
for i in range(len(x)):
A[i,i] = x[i]
for i in range(len(y)):
A[i,i+1] = y[i]
A[i+1,i] = conjugate(y[i])
A = self.spmatrix(A)
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning, "splu requires CSC matrix format")
x = splu(A).solve(r)
assert_almost_equal(A*x,r)
class _TestSlicing(object):
def test_dtype_preservation(self):
assert_equal(self.spmatrix((1,10), dtype=np.int16)[0,1:5].dtype, np.int16)
assert_equal(self.spmatrix((1,10), dtype=np.int32)[0,1:5].dtype, np.int32)
assert_equal(self.spmatrix((1,10), dtype=np.float32)[0,1:5].dtype, np.float32)
assert_equal(self.spmatrix((1,10), dtype=np.float64)[0,1:5].dtype, np.float64)
def test_get_horiz_slice(self):
B = asmatrix(arange(50.).reshape(5,10))
A = self.spmatrix(B)
assert_array_equal(B[1,:], A[1,:].todense())
assert_array_equal(B[1,2:5], A[1,2:5].todense())
C = matrix([[1, 2, 1], [4, 0, 6], [0, 0, 0], [0, 0, 1]])
D = self.spmatrix(C)
assert_array_equal(C[1, 1:3], D[1, 1:3].todense())
# Now test slicing when a row contains only zeros
E = matrix([[1, 2, 1], [4, 0, 0], [0, 0, 0], [0, 0, 1]])
F = self.spmatrix(E)
assert_array_equal(E[1, 1:3], F[1, 1:3].todense())
assert_array_equal(E[2, -2:], F[2, -2:].A)
# The following should raise exceptions:
assert_raises(IndexError, A.__getitem__, (slice(None), 11))
assert_raises(IndexError, A.__getitem__, (6, slice(3, 7)))
def test_get_vert_slice(self):
B = asmatrix(arange(50.).reshape(5,10))
A = self.spmatrix(B)
assert_array_equal(B[2:5,0], A[2:5,0].todense())
assert_array_equal(B[:,1], A[:,1].todense())
C = matrix([[1, 2, 1], [4, 0, 6], [0, 0, 0], [0, 0, 1]])
D = self.spmatrix(C)
assert_array_equal(C[1:3, 1], D[1:3, 1].todense())
assert_array_equal(C[:, 2], D[:, 2].todense())
# Now test slicing when a column contains only zeros
E = matrix([[1, 0, 1], [4, 0, 0], [0, 0, 0], [0, 0, 1]])
F = self.spmatrix(E)
assert_array_equal(E[:, 1], F[:, 1].todense())
assert_array_equal(E[-2:, 2], F[-2:, 2].todense())
# The following should raise exceptions:
assert_raises(IndexError, A.__getitem__, (slice(None), 11))
assert_raises(IndexError, A.__getitem__, (6, slice(3, 7)))
def test_get_slices(self):
B = asmatrix(arange(50.).reshape(5,10))
A = self.spmatrix(B)
assert_array_equal(A[2:5,0:3].todense(), B[2:5,0:3])
assert_array_equal(A[1:,:-1].todense(), B[1:,:-1])
assert_array_equal(A[:-1,1:].todense(), B[:-1,1:])
# Now test slicing when a column contains only zeros
E = matrix([[1, 0, 1], [4, 0, 0], [0, 0, 0], [0, 0, 1]])
F = self.spmatrix(E)
assert_array_equal(E[1:2, 1:2], F[1:2, 1:2].todense())
assert_array_equal(E[:, 1:], F[:, 1:].todense())
def test_non_unit_stride_2d_indexing(self):
# Regression test -- used to silently ignore the stride.
v0 = np.random.rand(50, 50)
try:
v = self.spmatrix(v0)[0:25:2, 2:30:3]
except ValueError:
# if unsupported
raise pytest.skip("feature not implemented")
assert_array_equal(v.todense(),
v0[0:25:2, 2:30:3])
def test_slicing_2(self):
B = asmatrix(arange(50).reshape(5,10))
A = self.spmatrix(B)
# [i,j]
assert_equal(A[2,3], B[2,3])
assert_equal(A[-1,8], B[-1,8])
assert_equal(A[-1,-2],B[-1,-2])
assert_equal(A[array(-1),-2],B[-1,-2])
assert_equal(A[-1,array(-2)],B[-1,-2])
assert_equal(A[array(-1),array(-2)],B[-1,-2])
# [i,1:2]
assert_equal(A[2,:].todense(), B[2,:])
assert_equal(A[2,5:-2].todense(),B[2,5:-2])
assert_equal(A[array(2),5:-2].todense(),B[2,5:-2])
# [1:2,j]
assert_equal(A[:,2].todense(), B[:,2])
assert_equal(A[3:4,9].todense(), B[3:4,9])
assert_equal(A[1:4,-5].todense(),B[1:4,-5])
assert_equal(A[2:-1,3].todense(),B[2:-1,3])
assert_equal(A[2:-1,array(3)].todense(),B[2:-1,3])
# [1:2,1:2]
assert_equal(A[1:2,1:2].todense(),B[1:2,1:2])
assert_equal(A[4:,3:].todense(), B[4:,3:])
assert_equal(A[:4,:5].todense(), B[:4,:5])
assert_equal(A[2:-1,:5].todense(),B[2:-1,:5])
# [i]
assert_equal(A[1,:].todense(), B[1,:])
assert_equal(A[-2,:].todense(),B[-2,:])
assert_equal(A[array(-2),:].todense(),B[-2,:])
# [1:2]
assert_equal(A[1:4].todense(), B[1:4])
assert_equal(A[1:-2].todense(),B[1:-2])
# Check bug reported by Robert Cimrman:
# http://thread.gmane.org/gmane.comp.python.scientific.devel/7986 (dead link)
s = slice(int8(2),int8(4),None)
assert_equal(A[s,:].todense(), B[2:4,:])
assert_equal(A[:,s].todense(), B[:,2:4])
def test_slicing_3(self):
B = asmatrix(arange(50).reshape(5,10))
A = self.spmatrix(B)
s_ = np.s_
slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
s_[15:20], s_[3:2],
s_[8:3:-1], s_[4::-2], s_[:5:-1],
0, 1, s_[:], s_[1:5], -1, -2, -5,
array(-1), np.int8(-3)]
def check_1(a):
x = A[a]
y = B[a]
if y.shape == ():
assert_equal(x, y, repr(a))
else:
if x.size == 0 and y.size == 0:
pass
else:
assert_array_equal(x.todense(), y, repr(a))
for j, a in enumerate(slices):
check_1(a)
def check_2(a, b):
# Indexing np.matrix with 0-d arrays seems to be broken,
# as they seem not to be treated as scalars.
# https://github.com/numpy/numpy/issues/3110
if isinstance(a, np.ndarray):
ai = int(a)
else:
ai = a
if isinstance(b, np.ndarray):
bi = int(b)
else:
bi = b
x = A[a, b]
y = B[ai, bi]
if y.shape == ():
assert_equal(x, y, repr((a, b)))
else:
if x.size == 0 and y.size == 0:
pass
else:
assert_array_equal(x.todense(), y, repr((a, b)))
for i, a in enumerate(slices):
for j, b in enumerate(slices):
check_2(a, b)
def test_ellipsis_slicing(self):
b = asmatrix(arange(50).reshape(5,10))
a = self.spmatrix(b)
assert_array_equal(a[...].A, b[...].A)
assert_array_equal(a[...,].A, b[...,].A)
assert_array_equal(a[1, ...].A, b[1, ...].A)
assert_array_equal(a[..., 1].A, b[..., 1].A)
assert_array_equal(a[1:, ...].A, b[1:, ...].A)
assert_array_equal(a[..., 1:].A, b[..., 1:].A)
assert_array_equal(a[1:, 1, ...].A, b[1:, 1, ...].A)
assert_array_equal(a[1, ..., 1:].A, b[1, ..., 1:].A)
# These return ints
assert_equal(a[1, 1, ...], b[1, 1, ...])
assert_equal(a[1, ..., 1], b[1, ..., 1])
def test_multiple_ellipsis_slicing(self):
b = asmatrix(arange(50).reshape(5,10))
a = self.spmatrix(b)
assert_array_equal(a[..., ...].A, b[:, :].A)
assert_array_equal(a[..., ..., ...].A, b[:, :].A)
assert_array_equal(a[1, ..., ...].A, b[1, :].A)
assert_array_equal(a[1:, ..., ...].A, b[1:, :].A)
assert_array_equal(a[..., ..., 1:].A, b[:, 1:].A)
assert_array_equal(a[..., ..., 1].A, b[:, 1].A)
class _TestSlicingAssign(object):
def test_slice_scalar_assign(self):
A = self.spmatrix((5, 5))
B = np.zeros((5, 5))
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
for C in [A, B]:
C[0:1,1] = 1
C[3:0,0] = 4
C[3:4,0] = 9
C[0,4:] = 1
C[3::-1,4:] = 9
assert_array_equal(A.toarray(), B)
def test_slice_assign_2(self):
n, m = (5, 10)
def _test_set(i, j):
msg = "i=%r; j=%r" % (i, j)
A = self.spmatrix((n, m))
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
A[i, j] = 1
B = np.zeros((n, m))
B[i, j] = 1
assert_array_almost_equal(A.todense(), B, err_msg=msg)
# [i,1:2]
for i, j in [(2, slice(3)), (2, slice(None, 10, 4)), (2, slice(5, -2)),
(array(2), slice(5, -2))]:
_test_set(i, j)
def test_self_self_assignment(self):
# Tests whether a row of one lil_matrix can be assigned to
# another.
B = self.spmatrix((4,3))
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
B[0,0] = 2
B[1,2] = 7
B[2,1] = 3
B[3,0] = 10
A = B / 10
B[0,:] = A[0,:]
assert_array_equal(A[0,:].A, B[0,:].A)
A = B / 10
B[:,:] = A[:1,:1]
assert_array_equal(np.zeros((4,3)) + A[0,0], B.A)
A = B / 10
B[:-1,0] = A[0,:].T
assert_array_equal(A[0,:].A.T, B[:-1,0].A)
def test_slice_assignment(self):
B = self.spmatrix((4,3))
expected = array([[10,0,0],
[0,0,6],
[0,14,0],
[0,0,0]])
block = [[1,0],[0,4]]
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
B[0,0] = 5
B[1,2] = 3
B[2,1] = 7
B[:,:] = B+B
assert_array_equal(B.todense(),expected)
B[:2,:2] = csc_matrix(array(block))
assert_array_equal(B.todense()[:2,:2],block)
def test_sparsity_modifying_assignment(self):
B = self.spmatrix((4,3))
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
B[0,0] = 5
B[1,2] = 3
B[2,1] = 7
B[3,0] = 10
B[:3] = csr_matrix(np.eye(3))
expected = array([[1,0,0],[0,1,0],[0,0,1],[10,0,0]])
assert_array_equal(B.toarray(), expected)
def test_set_slice(self):
A = self.spmatrix((5,10))
B = matrix(zeros((5,10), float))
s_ = np.s_
slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
s_[8:3:-1], s_[4::-2], s_[:5:-1],
0, 1, s_[:], s_[1:5], -1, -2, -5,
array(-1), np.int8(-3)]
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
for j, a in enumerate(slices):
A[a] = j
B[a] = j
assert_array_equal(A.todense(), B, repr(a))
for i, a in enumerate(slices):
for j, b in enumerate(slices):
A[a,b] = 10*i + 1000*(j+1)
B[a,b] = 10*i + 1000*(j+1)
assert_array_equal(A.todense(), B, repr((a, b)))
A[0, 1:10:2] = range(1, 10, 2)
B[0, 1:10:2] = range(1, 10, 2)
assert_array_equal(A.todense(), B)
A[1:5:2,0] = np.array(range(1, 5, 2))[:,None]
B[1:5:2,0] = np.array(range(1, 5, 2))[:,None]
assert_array_equal(A.todense(), B)
# The next commands should raise exceptions
assert_raises(ValueError, A.__setitem__, (0, 0), list(range(100)))
assert_raises(ValueError, A.__setitem__, (0, 0), arange(100))
assert_raises(ValueError, A.__setitem__, (0, slice(None)),
list(range(100)))
assert_raises(ValueError, A.__setitem__, (slice(None), 1),
list(range(100)))
assert_raises(ValueError, A.__setitem__, (slice(None), 1), A.copy())
assert_raises(ValueError, A.__setitem__,
([[1, 2, 3], [0, 3, 4]], [1, 2, 3]), [1, 2, 3, 4])
assert_raises(ValueError, A.__setitem__,
([[1, 2, 3], [0, 3, 4], [4, 1, 3]],
[[1, 2, 4], [0, 1, 3]]), [2, 3, 4])
class _TestFancyIndexing(object):
"""Tests fancy indexing features. The tests for any matrix formats
that implement these features should derive from this class.
"""
def test_bad_index(self):
A = self.spmatrix(np.zeros([5, 5]))
assert_raises((IndexError, ValueError, TypeError), A.__getitem__, "foo")
assert_raises((IndexError, ValueError, TypeError), A.__getitem__, (2, "foo"))
assert_raises((IndexError, ValueError), A.__getitem__,
([1, 2, 3], [1, 2, 3, 4]))
def test_fancy_indexing(self):
B = asmatrix(arange(50).reshape(5,10))
A = self.spmatrix(B)
# [i]
assert_equal(A[[1,3]].todense(), B[[1,3]])
# [i,[1,2]]
assert_equal(A[3,[1,3]].todense(), B[3,[1,3]])
assert_equal(A[-1,[2,-5]].todense(),B[-1,[2,-5]])
assert_equal(A[array(-1),[2,-5]].todense(),B[-1,[2,-5]])
assert_equal(A[-1,array([2,-5])].todense(),B[-1,[2,-5]])
assert_equal(A[array(-1),array([2,-5])].todense(),B[-1,[2,-5]])
# [1:2,[1,2]]
assert_equal(A[:,[2,8,3,-1]].todense(),B[:,[2,8,3,-1]])
assert_equal(A[3:4,[9]].todense(), B[3:4,[9]])
assert_equal(A[1:4,[-1,-5]].todense(), B[1:4,[-1,-5]])
assert_equal(A[1:4,array([-1,-5])].todense(), B[1:4,[-1,-5]])
# [[1,2],j]
assert_equal(A[[1,3],3].todense(), B[[1,3],3])
assert_equal(A[[2,-5],-4].todense(), B[[2,-5],-4])
assert_equal(A[array([2,-5]),-4].todense(), B[[2,-5],-4])
assert_equal(A[[2,-5],array(-4)].todense(), B[[2,-5],-4])
assert_equal(A[array([2,-5]),array(-4)].todense(), B[[2,-5],-4])
# [[1,2],1:2]
assert_equal(A[[1,3],:].todense(), B[[1,3],:])
assert_equal(A[[2,-5],8:-1].todense(),B[[2,-5],8:-1])
assert_equal(A[array([2,-5]),8:-1].todense(),B[[2,-5],8:-1])
# [[1,2],[1,2]]
assert_equal(todense(A[[1,3],[2,4]]), B[[1,3],[2,4]])
assert_equal(todense(A[[-1,-3],[2,-4]]), B[[-1,-3],[2,-4]])
assert_equal(todense(A[array([-1,-3]),[2,-4]]), B[[-1,-3],[2,-4]])
assert_equal(todense(A[[-1,-3],array([2,-4])]), B[[-1,-3],[2,-4]])
assert_equal(todense(A[array([-1,-3]),array([2,-4])]), B[[-1,-3],[2,-4]])
# [[[1],[2]],[1,2]]
assert_equal(A[[[1],[3]],[2,4]].todense(), B[[[1],[3]],[2,4]])
assert_equal(A[[[-1],[-3],[-2]],[2,-4]].todense(),B[[[-1],[-3],[-2]],[2,-4]])
assert_equal(A[array([[-1],[-3],[-2]]),[2,-4]].todense(),B[[[-1],[-3],[-2]],[2,-4]])
assert_equal(A[[[-1],[-3],[-2]],array([2,-4])].todense(),B[[[-1],[-3],[-2]],[2,-4]])
assert_equal(A[array([[-1],[-3],[-2]]),array([2,-4])].todense(),B[[[-1],[-3],[-2]],[2,-4]])
# [[1,2]]
assert_equal(A[[1,3]].todense(), B[[1,3]])
assert_equal(A[[-1,-3]].todense(),B[[-1,-3]])
assert_equal(A[array([-1,-3])].todense(),B[[-1,-3]])
# [[1,2],:][:,[1,2]]
assert_equal(A[[1,3],:][:,[2,4]].todense(), B[[1,3],:][:,[2,4]])
assert_equal(A[[-1,-3],:][:,[2,-4]].todense(), B[[-1,-3],:][:,[2,-4]])
assert_equal(A[array([-1,-3]),:][:,array([2,-4])].todense(), B[[-1,-3],:][:,[2,-4]])
# [:,[1,2]][[1,2],:]
assert_equal(A[:,[1,3]][[2,4],:].todense(), B[:,[1,3]][[2,4],:])
assert_equal(A[:,[-1,-3]][[2,-4],:].todense(), B[:,[-1,-3]][[2,-4],:])
assert_equal(A[:,array([-1,-3])][array([2,-4]),:].todense(), B[:,[-1,-3]][[2,-4],:])
# Check bug reported by Robert Cimrman:
# http://thread.gmane.org/gmane.comp.python.scientific.devel/7986 (dead link)
s = slice(int8(2),int8(4),None)
assert_equal(A[s,:].todense(), B[2:4,:])
assert_equal(A[:,s].todense(), B[:,2:4])
# Regression for gh-4917: index with tuple of 2D arrays
i = np.array([[1]], dtype=int)
assert_equal(A[i,i].todense(), B[i,i])
# Regression for gh-4917: index with tuple of empty nested lists
assert_equal(A[[[]], [[]]].todense(), B[[[]], [[]]])
def test_fancy_indexing_randomized(self):
np.random.seed(1234) # make runs repeatable
NUM_SAMPLES = 50
M = 6
N = 4
D = asmatrix(np.random.rand(M,N))
D = np.multiply(D, D > 0.5)
I = np.random.randint(-M + 1, M, size=NUM_SAMPLES)
J = np.random.randint(-N + 1, N, size=NUM_SAMPLES)
S = self.spmatrix(D)
SIJ = S[I,J]
if isspmatrix(SIJ):
SIJ = SIJ.todense()
assert_equal(SIJ, D[I,J])
I_bad = I + M
J_bad = J - N
assert_raises(IndexError, S.__getitem__, (I_bad,J))
assert_raises(IndexError, S.__getitem__, (I,J_bad))
def test_fancy_indexing_boolean(self):
np.random.seed(1234) # make runs repeatable
B = asmatrix(arange(50).reshape(5,10))
A = self.spmatrix(B)
I = np.array(np.random.randint(0, 2, size=5), dtype=bool)
J = np.array(np.random.randint(0, 2, size=10), dtype=bool)
X = np.array(np.random.randint(0, 2, size=(5, 10)), dtype=bool)
assert_equal(todense(A[I]), B[I])
assert_equal(todense(A[:,J]), B[:, J])
assert_equal(todense(A[X]), B[X])
assert_equal(todense(A[B > 9]), B[B > 9])
I = np.array([True, False, True, True, False])
J = np.array([False, True, True, False, True,
False, False, False, False, False])
assert_equal(todense(A[I, J]), B[I, J])
Z1 = np.zeros((6, 11), dtype=bool)
Z2 = np.zeros((6, 11), dtype=bool)
Z2[0,-1] = True
Z3 = np.zeros((6, 11), dtype=bool)
Z3[-1,0] = True
assert_equal(A[Z1], np.array([]))
assert_raises(IndexError, A.__getitem__, Z2)
assert_raises(IndexError, A.__getitem__, Z3)
assert_raises((IndexError, ValueError), A.__getitem__, (X, 1))
def test_fancy_indexing_sparse_boolean(self):
np.random.seed(1234) # make runs repeatable
B = asmatrix(arange(50).reshape(5,10))
A = self.spmatrix(B)
X = np.array(np.random.randint(0, 2, size=(5, 10)), dtype=bool)
Xsp = csr_matrix(X)
assert_equal(todense(A[Xsp]), B[X])
assert_equal(todense(A[A > 9]), B[B > 9])
Z = np.array(np.random.randint(0, 2, size=(5, 11)), dtype=bool)
Y = np.array(np.random.randint(0, 2, size=(6, 10)), dtype=bool)
Zsp = csr_matrix(Z)
Ysp = csr_matrix(Y)
assert_raises(IndexError, A.__getitem__, Zsp)
assert_raises(IndexError, A.__getitem__, Ysp)
assert_raises((IndexError, ValueError), A.__getitem__, (Xsp, 1))
def test_fancy_indexing_regression_3087(self):
mat = self.spmatrix(array([[1, 0, 0], [0,1,0], [1,0,0]]))
desired_cols = np.ravel(mat.sum(0)) > 0
assert_equal(mat[:, desired_cols].A, [[1, 0], [0, 1], [1, 0]])
def test_fancy_indexing_seq_assign(self):
mat = self.spmatrix(array([[1, 0], [0, 1]]))
assert_raises(ValueError, mat.__setitem__, (0, 0), np.array([1,2]))
def test_fancy_indexing_2d_assign(self):
# regression test for gh-10695
mat = self.spmatrix(array([[1, 0], [2, 3]]))
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure")
mat[[0, 1], [1, 1]] = mat[[1, 0], [0, 0]]
assert_equal(todense(mat), array([[1, 2], [2, 1]]))
def test_fancy_indexing_empty(self):
B = asmatrix(arange(50).reshape(5,10))
B[1,:] = 0
B[:,2] = 0
B[3,6] = 0
A = self.spmatrix(B)
K = np.array([False, False, False, False, False])
assert_equal(todense(A[K]), B[K])
K = np.array([], dtype=int)
assert_equal(todense(A[K]), B[K])
assert_equal(todense(A[K,K]), B[K,K])
J = np.array([0, 1, 2, 3, 4], dtype=int)[:,None]
assert_equal(todense(A[K,J]), B[K,J])
assert_equal(todense(A[J,K]), B[J,K])
@contextlib.contextmanager
def check_remains_sorted(X):
"""Checks that sorted indices property is retained through an operation
"""
if not hasattr(X, 'has_sorted_indices') or not X.has_sorted_indices:
yield
return
yield
indices = X.indices.copy()
X.has_sorted_indices = False
X.sort_indices()
assert_array_equal(indices, X.indices,
'Expected sorted indices, found unsorted')
class _TestFancyIndexingAssign(object):
def test_bad_index_assign(self):
A = self.spmatrix(np.zeros([5, 5]))
assert_raises((IndexError, ValueError, TypeError), A.__setitem__, "foo", 2)
assert_raises((IndexError, ValueError, TypeError), A.__setitem__, (2, "foo"), 5)
def test_fancy_indexing_set(self):
n, m = (5, 10)
def _test_set_slice(i, j):
A = self.spmatrix((n, m))
B = asmatrix(np.zeros((n, m)))
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
B[i, j] = 1
with check_remains_sorted(A):
A[i, j] = 1
assert_array_almost_equal(A.todense(), B)
# [1:2,1:2]
for i, j in [((2, 3, 4), slice(None, 10, 4)),
(np.arange(3), slice(5, -2)),
(slice(2, 5), slice(5, -2))]:
_test_set_slice(i, j)
for i, j in [(np.arange(3), np.arange(3)), ((0, 3, 4), (1, 2, 4))]:
_test_set_slice(i, j)
def test_fancy_assignment_dtypes(self):
def check(dtype):
A = self.spmatrix((5, 5), dtype=dtype)
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
A[[0,1],[0,1]] = dtype.type(1)
assert_equal(A.sum(), dtype.type(1)*2)
A[0:2,0:2] = dtype.type(1.0)
assert_equal(A.sum(), dtype.type(1)*4)
A[2,2] = dtype.type(1.0)
assert_equal(A.sum(), dtype.type(1)*4 + dtype.type(1))
for dtype in supported_dtypes:
check(np.dtype(dtype))
def test_sequence_assignment(self):
A = self.spmatrix((4,3))
B = self.spmatrix(eye(3,4))
i0 = [0,1,2]
i1 = (0,1,2)
i2 = array(i0)
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
with check_remains_sorted(A):
A[0,i0] = B[i0,0].T
A[1,i1] = B[i1,1].T
A[2,i2] = B[i2,2].T
assert_array_equal(A.todense(),B.T.todense())
# column slice
A = self.spmatrix((2,3))
with check_remains_sorted(A):
A[1,1:3] = [10,20]
assert_array_equal(A.todense(), [[0,0,0],[0,10,20]])
# row slice
A = self.spmatrix((3,2))
with check_remains_sorted(A):
A[1:3,1] = [[10],[20]]
assert_array_equal(A.todense(), [[0,0],[0,10],[0,20]])
# both slices
A = self.spmatrix((3,3))
B = asmatrix(np.zeros((3,3)))
with check_remains_sorted(A):
for C in [A, B]:
C[[0,1,2], [0,1,2]] = [4,5,6]
assert_array_equal(A.toarray(), B)
# both slices (2)
A = self.spmatrix((4, 3))
with check_remains_sorted(A):
A[(1, 2, 3), (0, 1, 2)] = [1, 2, 3]
assert_almost_equal(A.sum(), 6)
B = asmatrix(np.zeros((4, 3)))
B[(1, 2, 3), (0, 1, 2)] = [1, 2, 3]
assert_array_equal(A.todense(), B)
def test_fancy_assign_empty(self):
B = asmatrix(arange(50).reshape(5,10))
B[1,:] = 0
B[:,2] = 0
B[3,6] = 0
A = self.spmatrix(B)
K = np.array([False, False, False, False, False])
A[K] = 42
assert_equal(todense(A), B)
K = np.array([], dtype=int)
A[K] = 42
assert_equal(todense(A), B)
A[K,K] = 42
assert_equal(todense(A), B)
J = np.array([0, 1, 2, 3, 4], dtype=int)[:,None]
A[K,J] = 42
assert_equal(todense(A), B)
A[J,K] = 42
assert_equal(todense(A), B)
class _TestFancyMultidim(object):
def test_fancy_indexing_ndarray(self):
sets = [
(np.array([[1], [2], [3]]), np.array([3, 4, 2])),
(np.array([[1], [2], [3]]), np.array([[3, 4, 2]])),
(np.array([[1, 2, 3]]), np.array([[3], [4], [2]])),
(np.array([1, 2, 3]), np.array([[3], [4], [2]])),
(np.array([[1, 2, 3], [3, 4, 2]]),
np.array([[5, 6, 3], [2, 3, 1]]))
]
# These inputs generate 3-D outputs
# (np.array([[[1], [2], [3]], [[3], [4], [2]]]),
# np.array([[[5], [6], [3]], [[2], [3], [1]]])),
for I, J in sets:
np.random.seed(1234)
D = asmatrix(np.random.rand(5, 7))
S = self.spmatrix(D)
SIJ = S[I,J]
if isspmatrix(SIJ):
SIJ = SIJ.todense()
assert_equal(SIJ, D[I,J])
I_bad = I + 5
J_bad = J + 7
assert_raises(IndexError, S.__getitem__, (I_bad,J))
assert_raises(IndexError, S.__getitem__, (I,J_bad))
# This would generate 3-D arrays -- not supported
assert_raises(IndexError, S.__getitem__, ([I, I], slice(None)))
assert_raises(IndexError, S.__getitem__, (slice(None), [J, J]))
class _TestFancyMultidimAssign(object):
def test_fancy_assign_ndarray(self):
np.random.seed(1234)
D = asmatrix(np.random.rand(5, 7))
S = self.spmatrix(D)
X = np.random.rand(2, 3)
I = np.array([[1, 2, 3], [3, 4, 2]])
J = np.array([[5, 6, 3], [2, 3, 1]])
with check_remains_sorted(S):
S[I,J] = X
D[I,J] = X
assert_equal(S.todense(), D)
I_bad = I + 5
J_bad = J + 7
C = [1, 2, 3]
with check_remains_sorted(S):
S[I,J] = C
D[I,J] = C
assert_equal(S.todense(), D)
with check_remains_sorted(S):
S[I,J] = 3
D[I,J] = 3
assert_equal(S.todense(), D)
assert_raises(IndexError, S.__setitem__, (I_bad,J), C)
assert_raises(IndexError, S.__setitem__, (I,J_bad), C)
def test_fancy_indexing_multidim_set(self):
n, m = (5, 10)
def _test_set_slice(i, j):
A = self.spmatrix((n, m))
with check_remains_sorted(A), suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
A[i, j] = 1
B = asmatrix(np.zeros((n, m)))
B[i, j] = 1
assert_array_almost_equal(A.todense(), B)
# [[[1, 2], [1, 2]], [1, 2]]
for i, j in [(np.array([[1, 2], [1, 3]]), [1, 3]),
(np.array([0, 4]), [[0, 3], [1, 2]]),
([[1, 2, 3], [0, 2, 4]], [[0, 4, 3], [4, 1, 2]])]:
_test_set_slice(i, j)
def test_fancy_assign_list(self):
np.random.seed(1234)
D = asmatrix(np.random.rand(5, 7))
S = self.spmatrix(D)
X = np.random.rand(2, 3)
I = [[1, 2, 3], [3, 4, 2]]
J = [[5, 6, 3], [2, 3, 1]]
S[I,J] = X
D[I,J] = X
assert_equal(S.todense(), D)
I_bad = [[ii + 5 for ii in i] for i in I]
J_bad = [[jj + 7 for jj in j] for j in J]
C = [1, 2, 3]
S[I,J] = C
D[I,J] = C
assert_equal(S.todense(), D)
S[I,J] = 3
D[I,J] = 3
assert_equal(S.todense(), D)
assert_raises(IndexError, S.__setitem__, (I_bad,J), C)
assert_raises(IndexError, S.__setitem__, (I,J_bad), C)
def test_fancy_assign_slice(self):
np.random.seed(1234)
D = asmatrix(np.random.rand(5, 7))
S = self.spmatrix(D)
I = [1, 2, 3, 3, 4, 2]
J = [5, 6, 3, 2, 3, 1]
I_bad = [ii + 5 for ii in I]
J_bad = [jj + 7 for jj in J]
C1 = [1, 2, 3, 4, 5, 6, 7]
C2 = np.arange(5)[:, None]
assert_raises(IndexError, S.__setitem__, (I_bad, slice(None)), C1)
assert_raises(IndexError, S.__setitem__, (slice(None), J_bad), C2)
class _TestArithmetic(object):
"""
Test real/complex arithmetic
"""
def __arith_init(self):
# these can be represented exactly in FP (so arithmetic should be exact)
self.__A = matrix([[-1.5, 6.5, 0, 2.25, 0, 0],
[3.125, -7.875, 0.625, 0, 0, 0],
[0, 0, -0.125, 1.0, 0, 0],
[0, 0, 8.375, 0, 0, 0]],'float64')
self.__B = matrix([[0.375, 0, 0, 0, -5, 2.5],
[14.25, -3.75, 0, 0, -0.125, 0],
[0, 7.25, 0, 0, 0, 0],
[18.5, -0.0625, 0, 0, 0, 0]],'complex128')
self.__B.imag = matrix([[1.25, 0, 0, 0, 6, -3.875],
[2.25, 4.125, 0, 0, 0, 2.75],
[0, 4.125, 0, 0, 0, 0],
[-0.0625, 0, 0, 0, 0, 0]],'float64')
# fractions are all x/16ths
assert_array_equal((self.__A*16).astype('int32'),16*self.__A)
assert_array_equal((self.__B.real*16).astype('int32'),16*self.__B.real)
assert_array_equal((self.__B.imag*16).astype('int32'),16*self.__B.imag)
self.__Asp = self.spmatrix(self.__A)
self.__Bsp = self.spmatrix(self.__B)
def test_add_sub(self):
self.__arith_init()
# basic tests
assert_array_equal((self.__Asp+self.__Bsp).todense(),self.__A+self.__B)
# check conversions
for x in supported_dtypes:
A = self.__A.astype(x)
Asp = self.spmatrix(A)
for y in supported_dtypes:
if not np.issubdtype(y, np.complexfloating):
B = self.__B.real.astype(y)
else:
B = self.__B.astype(y)
Bsp = self.spmatrix(B)
# addition
D1 = A + B
S1 = Asp + Bsp
assert_equal(S1.dtype,D1.dtype)
assert_array_equal(S1.todense(),D1)
assert_array_equal(Asp + B,D1) # check sparse + dense
assert_array_equal(A + Bsp,D1) # check dense + sparse
# subtraction
if np.dtype('bool') in [x, y]:
# boolean array subtraction deprecated in 1.9.0
continue
D1 = A - B
S1 = Asp - Bsp
assert_equal(S1.dtype,D1.dtype)
assert_array_equal(S1.todense(),D1)
assert_array_equal(Asp - B,D1) # check sparse - dense
assert_array_equal(A - Bsp,D1) # check dense - sparse
def test_mu(self):
self.__arith_init()
# basic tests
assert_array_equal((self.__Asp*self.__Bsp.T).todense(),
self.__A @ self.__B.T)
for x in supported_dtypes:
A = self.__A.astype(x)
Asp = self.spmatrix(A)
for y in supported_dtypes:
if np.issubdtype(y, np.complexfloating):
B = self.__B.astype(y)
else:
B = self.__B.real.astype(y)
Bsp = self.spmatrix(B)
D1 = A @ B.T
S1 = Asp * Bsp.T
assert_allclose(S1.todense(), D1,
atol=1e-14*abs(D1).max())
assert_equal(S1.dtype,D1.dtype)
class _TestMinMax(object):
def test_minmax(self):
for dtype in [np.float32, np.float64, np.int32, np.int64, np.complex128]:
D = np.arange(20, dtype=dtype).reshape(5,4)
X = self.spmatrix(D)
assert_equal(X.min(), 0)
assert_equal(X.max(), 19)
assert_equal(X.min().dtype, dtype)
assert_equal(X.max().dtype, dtype)
D *= -1
X = self.spmatrix(D)
assert_equal(X.min(), -19)
assert_equal(X.max(), 0)
D += 5
X = self.spmatrix(D)
assert_equal(X.min(), -14)
assert_equal(X.max(), 5)
# try a fully dense matrix
X = self.spmatrix(np.arange(1, 10).reshape(3, 3))
assert_equal(X.min(), 1)
assert_equal(X.min().dtype, X.dtype)
X = -X
assert_equal(X.max(), -1)
# and a fully sparse matrix
Z = self.spmatrix(np.zeros(1))
assert_equal(Z.min(), 0)
assert_equal(Z.max(), 0)
assert_equal(Z.max().dtype, Z.dtype)
# another test
D = np.arange(20, dtype=float).reshape(5,4)
D[0:2, :] = 0
X = self.spmatrix(D)
assert_equal(X.min(), 0)
assert_equal(X.max(), 19)
# zero-size matrices
for D in [np.zeros((0, 0)), np.zeros((0, 10)), np.zeros((10, 0))]:
X = self.spmatrix(D)
assert_raises(ValueError, X.min)
assert_raises(ValueError, X.max)
def test_minmax_axis(self):
D = matrix(np.arange(50).reshape(5,10))
# completely empty rows, leaving some completely full:
D[1, :] = 0
# empty at end for reduceat:
D[:, 9] = 0
# partial rows/cols:
D[3, 3] = 0
# entries on either side of 0:
D[2, 2] = -1
X = self.spmatrix(D)
axes = [-2, -1, 0, 1]
for axis in axes:
assert_array_equal(X.max(axis=axis).A, D.max(axis=axis).A)
assert_array_equal(X.min(axis=axis).A, D.min(axis=axis).A)
# full matrix
D = matrix(np.arange(1, 51).reshape(10, 5))
X = self.spmatrix(D)
for axis in axes:
assert_array_equal(X.max(axis=axis).A, D.max(axis=axis).A)
assert_array_equal(X.min(axis=axis).A, D.min(axis=axis).A)
# empty matrix
D = matrix(np.zeros((10, 5)))
X = self.spmatrix(D)
for axis in axes:
assert_array_equal(X.max(axis=axis).A, D.max(axis=axis).A)
assert_array_equal(X.min(axis=axis).A, D.min(axis=axis).A)
axes_even = [0, -2]
axes_odd = [1, -1]
# zero-size matrices
D = np.zeros((0, 10))
X = self.spmatrix(D)
for axis in axes_even:
assert_raises(ValueError, X.min, axis=axis)
assert_raises(ValueError, X.max, axis=axis)
for axis in axes_odd:
assert_array_equal(np.zeros((0, 1)), X.min(axis=axis).A)
assert_array_equal(np.zeros((0, 1)), X.max(axis=axis).A)
D = np.zeros((10, 0))
X = self.spmatrix(D)
for axis in axes_odd:
assert_raises(ValueError, X.min, axis=axis)
assert_raises(ValueError, X.max, axis=axis)
for axis in axes_even:
assert_array_equal(np.zeros((1, 0)), X.min(axis=axis).A)
assert_array_equal(np.zeros((1, 0)), X.max(axis=axis).A)
def test_minmax_invalid_params(self):
dat = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
for fname in ('min', 'max'):
func = getattr(datsp, fname)
assert_raises(ValueError, func, axis=3)
assert_raises(TypeError, func, axis=(0, 1))
assert_raises(TypeError, func, axis=1.5)
assert_raises(ValueError, func, axis=1, out=1)
def test_numpy_minmax(self):
# See gh-5987
# xref gh-7460 in 'numpy'
from scipy.sparse import data
dat = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
# We are only testing sparse matrices who have
# implemented 'min' and 'max' because they are
# the ones with the compatibility issues with
# the 'numpy' implementation.
if isinstance(datsp, data._minmax_mixin):
assert_array_equal(np.min(datsp), np.min(dat))
assert_array_equal(np.max(datsp), np.max(dat))
def test_argmax(self):
D1 = np.array([
[-1, 5, 2, 3],
[0, 0, -1, -2],
[-1, -2, -3, -4],
[1, 2, 3, 4],
[1, 2, 0, 0],
])
D2 = D1.transpose()
for D in [D1, D2]:
mat = csr_matrix(D)
assert_equal(mat.argmax(), np.argmax(D))
assert_equal(mat.argmin(), np.argmin(D))
assert_equal(mat.argmax(axis=0),
asmatrix(np.argmax(D, axis=0)))
assert_equal(mat.argmin(axis=0),
asmatrix(np.argmin(D, axis=0)))
assert_equal(mat.argmax(axis=1),
asmatrix(np.argmax(D, axis=1).reshape(-1, 1)))
assert_equal(mat.argmin(axis=1),
asmatrix(np.argmin(D, axis=1).reshape(-1, 1)))
D1 = np.empty((0, 5))
D2 = np.empty((5, 0))
for axis in [None, 0]:
mat = self.spmatrix(D1)
assert_raises(ValueError, mat.argmax, axis=axis)
assert_raises(ValueError, mat.argmin, axis=axis)
for axis in [None, 1]:
mat = self.spmatrix(D2)
assert_raises(ValueError, mat.argmax, axis=axis)
assert_raises(ValueError, mat.argmin, axis=axis)
class _TestGetNnzAxis(object):
def test_getnnz_axis(self):
dat = matrix([[0, 2],
[3, 5],
[-6, 9]])
bool_dat = dat.astype(bool).A
datsp = self.spmatrix(dat)
accepted_return_dtypes = (np.int32, np.int64)
assert_array_equal(bool_dat.sum(axis=None), datsp.getnnz(axis=None))
assert_array_equal(bool_dat.sum(), datsp.getnnz())
assert_array_equal(bool_dat.sum(axis=0), datsp.getnnz(axis=0))
assert_in(datsp.getnnz(axis=0).dtype, accepted_return_dtypes)
assert_array_equal(bool_dat.sum(axis=1), datsp.getnnz(axis=1))
assert_in(datsp.getnnz(axis=1).dtype, accepted_return_dtypes)
assert_array_equal(bool_dat.sum(axis=-2), datsp.getnnz(axis=-2))
assert_in(datsp.getnnz(axis=-2).dtype, accepted_return_dtypes)
assert_array_equal(bool_dat.sum(axis=-1), datsp.getnnz(axis=-1))
assert_in(datsp.getnnz(axis=-1).dtype, accepted_return_dtypes)
assert_raises(ValueError, datsp.getnnz, axis=2)
#------------------------------------------------------------------------------
# Tailored base class for generic tests
#------------------------------------------------------------------------------
def _possibly_unimplemented(cls, require=True):
"""
Construct a class that either runs tests as usual (require=True),
or each method skips if it encounters a common error.
"""
if require:
return cls
else:
def wrap(fc):
@functools.wraps(fc)
def wrapper(*a, **kw):
try:
return fc(*a, **kw)
except (NotImplementedError, TypeError, ValueError,
IndexError, AttributeError):
raise pytest.skip("feature not implemented")
return wrapper
new_dict = dict(cls.__dict__)
for name, func in cls.__dict__.items():
if name.startswith('test_'):
new_dict[name] = wrap(func)
return type(cls.__name__ + "NotImplemented",
cls.__bases__,
new_dict)
def sparse_test_class(getset=True, slicing=True, slicing_assign=True,
fancy_indexing=True, fancy_assign=True,
fancy_multidim_indexing=True, fancy_multidim_assign=True,
minmax=True, nnz_axis=True):
"""
Construct a base class, optionally converting some of the tests in
the suite to check that the feature is not implemented.
"""
bases = (_TestCommon,
_possibly_unimplemented(_TestGetSet, getset),
_TestSolve,
_TestInplaceArithmetic,
_TestArithmetic,
_possibly_unimplemented(_TestSlicing, slicing),
_possibly_unimplemented(_TestSlicingAssign, slicing_assign),
_possibly_unimplemented(_TestFancyIndexing, fancy_indexing),
_possibly_unimplemented(_TestFancyIndexingAssign,
fancy_assign),
_possibly_unimplemented(_TestFancyMultidim,
fancy_indexing and fancy_multidim_indexing),
_possibly_unimplemented(_TestFancyMultidimAssign,
fancy_multidim_assign and fancy_assign),
_possibly_unimplemented(_TestMinMax, minmax),
_possibly_unimplemented(_TestGetNnzAxis, nnz_axis))
# check that test names do not clash
names = {}
for cls in bases:
for name in cls.__dict__:
if not name.startswith('test_'):
continue
old_cls = names.get(name)
if old_cls is not None:
raise ValueError("Test class %s overloads test %s defined in %s" % (
cls.__name__, name, old_cls.__name__))
names[name] = cls
return type("TestBase", bases, {})
#------------------------------------------------------------------------------
# Matrix class based tests
#------------------------------------------------------------------------------
class TestCSR(sparse_test_class()):
@classmethod
def spmatrix(cls, *args, **kwargs):
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a csr_matrix is expensive")
return csr_matrix(*args, **kwargs)
math_dtypes = [np.bool_, np.int_, np.float_, np.complex_]
def test_constructor1(self):
b = matrix([[0,4,0],
[3,0,0],
[0,2,0]],'d')
bsp = csr_matrix(b)
assert_array_almost_equal(bsp.data,[4,3,2])
assert_array_equal(bsp.indices,[1,0,1])
assert_array_equal(bsp.indptr,[0,1,2,3])
assert_equal(bsp.getnnz(),3)
assert_equal(bsp.getformat(),'csr')
assert_array_equal(bsp.todense(),b)
def test_constructor2(self):
b = zeros((6,6),'d')
b[3,4] = 5
bsp = csr_matrix(b)
assert_array_almost_equal(bsp.data,[5])
assert_array_equal(bsp.indices,[4])
assert_array_equal(bsp.indptr,[0,0,0,0,1,1,1])
assert_array_almost_equal(bsp.todense(),b)
def test_constructor3(self):
b = matrix([[1,0],
[0,2],
[3,0]],'d')
bsp = csr_matrix(b)
assert_array_almost_equal(bsp.data,[1,2,3])
assert_array_equal(bsp.indices,[0,1,0])
assert_array_equal(bsp.indptr,[0,1,2,3])
assert_array_almost_equal(bsp.todense(),b)
def test_constructor4(self):
# using (data, ij) format
row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2])
col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1])
data = array([6., 10., 3., 9., 1., 4.,
11., 2., 8., 5., 7.])
ij = vstack((row,col))
csr = csr_matrix((data,ij),(4,3))
assert_array_equal(arange(12).reshape(4,3),csr.todense())
def test_constructor5(self):
# infer dimensions from arrays
indptr = array([0,1,3,3])
indices = array([0,5,1,2])
data = array([1,2,3,4])
csr = csr_matrix((data, indices, indptr))
assert_array_equal(csr.shape,(3,6))
def test_constructor6(self):
# infer dimensions and dtype from lists
indptr = [0, 1, 3, 3]
indices = [0, 5, 1, 2]
data = [1, 2, 3, 4]
csr = csr_matrix((data, indices, indptr))
assert_array_equal(csr.shape, (3,6))
assert_(np.issubdtype(csr.dtype, np.signedinteger))
def test_constructor_smallcol(self):
# int64 indices not required
data = arange(6) + 1
col = array([1, 2, 1, 0, 0, 2], dtype=np.int64)
ptr = array([0, 2, 4, 6], dtype=np.int64)
a = csr_matrix((data, col, ptr), shape=(3, 3))
b = matrix([[0, 1, 2],
[4, 3, 0],
[5, 0, 6]], 'd')
assert_equal(a.indptr.dtype, np.dtype(np.int32))
assert_equal(a.indices.dtype, np.dtype(np.int32))
assert_array_equal(a.todense(), b)
def test_constructor_largecol(self):
# int64 indices required
data = arange(6) + 1
large = np.iinfo(np.int32).max + 100
col = array([0, 1, 2, large, large+1, large+2], dtype=np.int64)
ptr = array([0, 2, 4, 6], dtype=np.int64)
a = csr_matrix((data, col, ptr))
assert_equal(a.indptr.dtype, np.dtype(np.int64))
assert_equal(a.indices.dtype, np.dtype(np.int64))
assert_array_equal(a.shape, (3, max(col)+1))
def test_sort_indices(self):
data = arange(5)
indices = array([7, 2, 1, 5, 4])
indptr = array([0, 3, 5])
asp = csr_matrix((data, indices, indptr), shape=(2,10))
bsp = asp.copy()
asp.sort_indices()
assert_array_equal(asp.indices,[1, 2, 7, 4, 5])
assert_array_equal(asp.todense(),bsp.todense())
def test_eliminate_zeros(self):
data = array([1, 0, 0, 0, 2, 0, 3, 0])
indices = array([1, 2, 3, 4, 5, 6, 7, 8])
indptr = array([0, 3, 8])
asp = csr_matrix((data, indices, indptr), shape=(2,10))
bsp = asp.copy()
asp.eliminate_zeros()
assert_array_equal(asp.nnz, 3)
assert_array_equal(asp.data,[1, 2, 3])
assert_array_equal(asp.todense(),bsp.todense())
def test_ufuncs(self):
X = csr_matrix(np.arange(20).reshape(4, 5) / 20.)
for f in ["sin", "tan", "arcsin", "arctan", "sinh", "tanh",
"arcsinh", "arctanh", "rint", "sign", "expm1", "log1p",
"deg2rad", "rad2deg", "floor", "ceil", "trunc", "sqrt"]:
assert_equal(hasattr(csr_matrix, f), True)
X2 = getattr(X, f)()
assert_equal(X.shape, X2.shape)
assert_array_equal(X.indices, X2.indices)
assert_array_equal(X.indptr, X2.indptr)
assert_array_equal(X2.toarray(), getattr(np, f)(X.toarray()))
def test_unsorted_arithmetic(self):
data = arange(5)
indices = array([7, 2, 1, 5, 4])
indptr = array([0, 3, 5])
asp = csr_matrix((data, indices, indptr), shape=(2,10))
data = arange(6)
indices = array([8, 1, 5, 7, 2, 4])
indptr = array([0, 2, 6])
bsp = csr_matrix((data, indices, indptr), shape=(2,10))
assert_equal((asp + bsp).todense(), asp.todense() + bsp.todense())
def test_fancy_indexing_broadcast(self):
# broadcasting indexing mode is supported
I = np.array([[1], [2], [3]])
J = np.array([3, 4, 2])
np.random.seed(1234)
D = asmatrix(np.random.rand(5, 7))
S = self.spmatrix(D)
SIJ = S[I,J]
if isspmatrix(SIJ):
SIJ = SIJ.todense()
assert_equal(SIJ, D[I,J])
def test_has_sorted_indices(self):
"Ensure has_sorted_indices memoizes sorted state for sort_indices"
sorted_inds = np.array([0, 1])
unsorted_inds = np.array([1, 0])
data = np.array([1, 1])
indptr = np.array([0, 2])
M = csr_matrix((data, sorted_inds, indptr)).copy()
assert_equal(True, M.has_sorted_indices)
M = csr_matrix((data, unsorted_inds, indptr)).copy()
assert_equal(False, M.has_sorted_indices)
# set by sorting
M.sort_indices()
assert_equal(True, M.has_sorted_indices)
assert_array_equal(M.indices, sorted_inds)
M = csr_matrix((data, unsorted_inds, indptr)).copy()
# set manually (although underlyingly unsorted)
M.has_sorted_indices = True
assert_equal(True, M.has_sorted_indices)
assert_array_equal(M.indices, unsorted_inds)
# ensure sort bypassed when has_sorted_indices == True
M.sort_indices()
assert_array_equal(M.indices, unsorted_inds)
def test_has_canonical_format(self):
"Ensure has_canonical_format memoizes state for sum_duplicates"
M = csr_matrix((np.array([2]), np.array([0]), np.array([0, 1])))
assert_equal(True, M.has_canonical_format)
indices = np.array([0, 0]) # contains duplicate
data = np.array([1, 1])
indptr = np.array([0, 2])
M = csr_matrix((data, indices, indptr)).copy()
assert_equal(False, M.has_canonical_format)
# set by deduplicating
M.sum_duplicates()
assert_equal(True, M.has_canonical_format)
assert_equal(1, len(M.indices))
M = csr_matrix((data, indices, indptr)).copy()
# set manually (although underlyingly duplicated)
M.has_canonical_format = True
assert_equal(True, M.has_canonical_format)
assert_equal(2, len(M.indices)) # unaffected content
# ensure deduplication bypassed when has_canonical_format == True
M.sum_duplicates()
assert_equal(2, len(M.indices)) # unaffected content
def test_scalar_idx_dtype(self):
# Check that index dtype takes into account all parameters
# passed to sparsetools, including the scalar ones
indptr = np.zeros(2, dtype=np.int32)
indices = np.zeros(0, dtype=np.int32)
vals = np.zeros(0)
a = csr_matrix((vals, indices, indptr), shape=(1, 2**31-1))
b = csr_matrix((vals, indices, indptr), shape=(1, 2**31))
ij = np.zeros((2, 0), dtype=np.int32)
c = csr_matrix((vals, ij), shape=(1, 2**31-1))
d = csr_matrix((vals, ij), shape=(1, 2**31))
e = csr_matrix((1, 2**31-1))
f = csr_matrix((1, 2**31))
assert_equal(a.indptr.dtype, np.int32)
assert_equal(b.indptr.dtype, np.int64)
assert_equal(c.indptr.dtype, np.int32)
assert_equal(d.indptr.dtype, np.int64)
assert_equal(e.indptr.dtype, np.int32)
assert_equal(f.indptr.dtype, np.int64)
# These shouldn't fail
for x in [a, b, c, d, e, f]:
x + x
def test_binop_explicit_zeros(self):
# Check that binary ops don't introduce spurious explicit zeros.
# See gh-9619 for context.
a = csr_matrix([0, 1, 0])
b = csr_matrix([1, 1, 0])
assert (a + b).nnz == 2
assert a.multiply(b).nnz == 1
TestCSR.init_class()
class TestCSC(sparse_test_class()):
@classmethod
def spmatrix(cls, *args, **kwargs):
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a csc_matrix is expensive")
return csc_matrix(*args, **kwargs)
math_dtypes = [np.bool_, np.int_, np.float_, np.complex_]
def test_constructor1(self):
b = matrix([[1,0,0,0],[0,0,1,0],[0,2,0,3]],'d')
bsp = csc_matrix(b)
assert_array_almost_equal(bsp.data,[1,2,1,3])
assert_array_equal(bsp.indices,[0,2,1,2])
assert_array_equal(bsp.indptr,[0,1,2,3,4])
assert_equal(bsp.getnnz(),4)
assert_equal(bsp.shape,b.shape)
assert_equal(bsp.getformat(),'csc')
def test_constructor2(self):
b = zeros((6,6),'d')
b[2,4] = 5
bsp = csc_matrix(b)
assert_array_almost_equal(bsp.data,[5])
assert_array_equal(bsp.indices,[2])
assert_array_equal(bsp.indptr,[0,0,0,0,0,1,1])
def test_constructor3(self):
b = matrix([[1,0],[0,0],[0,2]],'d')
bsp = csc_matrix(b)
assert_array_almost_equal(bsp.data,[1,2])
assert_array_equal(bsp.indices,[0,2])
assert_array_equal(bsp.indptr,[0,1,2])
def test_constructor4(self):
# using (data, ij) format
row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2])
col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1])
data = array([6., 10., 3., 9., 1., 4.,
11., 2., 8., 5., 7.])
ij = vstack((row,col))
csc = csc_matrix((data,ij),(4,3))
assert_array_equal(arange(12).reshape(4,3),csc.todense())
def test_constructor5(self):
# infer dimensions from arrays
indptr = array([0,1,3,3])
indices = array([0,5,1,2])
data = array([1,2,3,4])
csc = csc_matrix((data, indices, indptr))
assert_array_equal(csc.shape,(6,3))
def test_constructor6(self):
# infer dimensions and dtype from lists
indptr = [0, 1, 3, 3]
indices = [0, 5, 1, 2]
data = [1, 2, 3, 4]
csc = csc_matrix((data, indices, indptr))
assert_array_equal(csc.shape,(6,3))
assert_(np.issubdtype(csc.dtype, np.signedinteger))
def test_eliminate_zeros(self):
data = array([1, 0, 0, 0, 2, 0, 3, 0])
indices = array([1, 2, 3, 4, 5, 6, 7, 8])
indptr = array([0, 3, 8])
asp = csc_matrix((data, indices, indptr), shape=(10,2))
bsp = asp.copy()
asp.eliminate_zeros()
assert_array_equal(asp.nnz, 3)
assert_array_equal(asp.data,[1, 2, 3])
assert_array_equal(asp.todense(),bsp.todense())
def test_sort_indices(self):
data = arange(5)
row = array([7, 2, 1, 5, 4])
ptr = [0, 3, 5]
asp = csc_matrix((data, row, ptr), shape=(10,2))
bsp = asp.copy()
asp.sort_indices()
assert_array_equal(asp.indices,[1, 2, 7, 4, 5])
assert_array_equal(asp.todense(),bsp.todense())
def test_ufuncs(self):
X = csc_matrix(np.arange(21).reshape(7, 3) / 21.)
for f in ["sin", "tan", "arcsin", "arctan", "sinh", "tanh",
"arcsinh", "arctanh", "rint", "sign", "expm1", "log1p",
"deg2rad", "rad2deg", "floor", "ceil", "trunc", "sqrt"]:
assert_equal(hasattr(csr_matrix, f), True)
X2 = getattr(X, f)()
assert_equal(X.shape, X2.shape)
assert_array_equal(X.indices, X2.indices)
assert_array_equal(X.indptr, X2.indptr)
assert_array_equal(X2.toarray(), getattr(np, f)(X.toarray()))
def test_unsorted_arithmetic(self):
data = arange(5)
indices = array([7, 2, 1, 5, 4])
indptr = array([0, 3, 5])
asp = csc_matrix((data, indices, indptr), shape=(10,2))
data = arange(6)
indices = array([8, 1, 5, 7, 2, 4])
indptr = array([0, 2, 6])
bsp = csc_matrix((data, indices, indptr), shape=(10,2))
assert_equal((asp + bsp).todense(), asp.todense() + bsp.todense())
def test_fancy_indexing_broadcast(self):
# broadcasting indexing mode is supported
I = np.array([[1], [2], [3]])
J = np.array([3, 4, 2])
np.random.seed(1234)
D = asmatrix(np.random.rand(5, 7))
S = self.spmatrix(D)
SIJ = S[I,J]
if isspmatrix(SIJ):
SIJ = SIJ.todense()
assert_equal(SIJ, D[I,J])
def test_scalar_idx_dtype(self):
# Check that index dtype takes into account all parameters
# passed to sparsetools, including the scalar ones
indptr = np.zeros(2, dtype=np.int32)
indices = np.zeros(0, dtype=np.int32)
vals = np.zeros(0)
a = csc_matrix((vals, indices, indptr), shape=(2**31-1, 1))
b = csc_matrix((vals, indices, indptr), shape=(2**31, 1))
ij = np.zeros((2, 0), dtype=np.int32)
c = csc_matrix((vals, ij), shape=(2**31-1, 1))
d = csc_matrix((vals, ij), shape=(2**31, 1))
e = csr_matrix((1, 2**31-1))
f = csr_matrix((1, 2**31))
assert_equal(a.indptr.dtype, np.int32)
assert_equal(b.indptr.dtype, np.int64)
assert_equal(c.indptr.dtype, np.int32)
assert_equal(d.indptr.dtype, np.int64)
assert_equal(e.indptr.dtype, np.int32)
assert_equal(f.indptr.dtype, np.int64)
# These shouldn't fail
for x in [a, b, c, d, e, f]:
x + x
TestCSC.init_class()
class TestDOK(sparse_test_class(minmax=False, nnz_axis=False)):
spmatrix = dok_matrix
math_dtypes = [np.int_, np.float_, np.complex_]
def test_mult(self):
A = dok_matrix((10,10))
A[0,3] = 10
A[5,6] = 20
D = A*A.T
E = A*A.H
assert_array_equal(D.A, E.A)
def test_add_nonzero(self):
A = self.spmatrix((3,2))
A[0,1] = -10
A[2,0] = 20
A = A + 10
B = matrix([[10, 0], [10, 10], [30, 10]])
assert_array_equal(A.todense(), B)
A = A + 1j
B = B + 1j
assert_array_equal(A.todense(), B)
def test_dok_divide_scalar(self):
A = self.spmatrix((3,2))
A[0,1] = -10
A[2,0] = 20
assert_array_equal((A/1j).todense(), A.todense()/1j)
assert_array_equal((A/9).todense(), A.todense()/9)
def test_convert(self):
# Test provided by Andrew Straw. Fails in SciPy <= r1477.
(m, n) = (6, 7)
a = dok_matrix((m, n))
# set a few elements, but none in the last column
a[2,1] = 1
a[0,2] = 2
a[3,1] = 3
a[1,5] = 4
a[4,3] = 5
a[4,2] = 6
# assert that the last column is all zeros
assert_array_equal(a.toarray()[:,n-1], zeros(m,))
# make sure it still works for CSC format
csc = a.tocsc()
assert_array_equal(csc.toarray()[:,n-1], zeros(m,))
# now test CSR
(m, n) = (n, m)
b = a.transpose()
assert_equal(b.shape, (m, n))
# assert that the last row is all zeros
assert_array_equal(b.toarray()[m-1,:], zeros(n,))
# make sure it still works for CSR format
csr = b.tocsr()
assert_array_equal(csr.toarray()[m-1,:], zeros(n,))
def test_ctor(self):
# Empty ctor
assert_raises(TypeError, dok_matrix)
# Dense ctor
b = matrix([[1,0,0,0],[0,0,1,0],[0,2,0,3]],'d')
A = dok_matrix(b)
assert_equal(b.dtype, A.dtype)
assert_equal(A.todense(), b)
# Sparse ctor
c = csr_matrix(b)
assert_equal(A.todense(), c.todense())
data = [[0, 1, 2], [3, 0, 0]]
d = dok_matrix(data, dtype=np.float32)
assert_equal(d.dtype, np.float32)
da = d.toarray()
assert_equal(da.dtype, np.float32)
assert_array_equal(da, data)
def test_ticket1160(self):
# Regression test for ticket #1160.
a = dok_matrix((3,3))
a[0,0] = 0
# This assert would fail, because the above assignment would
# incorrectly call __set_item__ even though the value was 0.
assert_((0,0) not in a.keys(), "Unexpected entry (0,0) in keys")
# Slice assignments were also affected.
b = dok_matrix((3,3))
b[:,0] = 0
assert_(len(b.keys()) == 0, "Unexpected entries in keys")
TestDOK.init_class()
class TestLIL(sparse_test_class(minmax=False)):
spmatrix = lil_matrix
math_dtypes = [np.int_, np.float_, np.complex_]
def test_dot(self):
A = zeros((10, 10), np.complex128)
A[0, 3] = 10
A[5, 6] = 20j
B = lil_matrix((10, 10), dtype=np.complex128)
B[0, 3] = 10
B[5, 6] = 20j
# TODO: properly handle this assertion on ppc64le
if platform.machine() != 'ppc64le':
assert_array_equal(A @ A.T, (B * B.T).todense())
assert_array_equal(A @ A.conjugate().T, (B * B.H).todense())
def test_scalar_mul(self):
x = lil_matrix((3, 3))
x[0, 0] = 2
x = x*2
assert_equal(x[0, 0], 4)
x = x*0
assert_equal(x[0, 0], 0)
def test_inplace_ops(self):
A = lil_matrix([[0, 2, 3], [4, 0, 6]])
B = lil_matrix([[0, 1, 0], [0, 2, 3]])
data = {'add': (B, A + B),
'sub': (B, A - B),
'mul': (3, A * 3)}
for op, (other, expected) in data.items():
result = A.copy()
getattr(result, '__i%s__' % op)(other)
assert_array_equal(result.todense(), expected.todense())
# Ticket 1604.
A = lil_matrix((1, 3), dtype=np.dtype('float64'))
B = array([0.1, 0.1, 0.1])
A[0, :] += B
assert_array_equal(A[0, :].toarray().squeeze(), B)
def test_lil_iteration(self):
row_data = [[1, 2, 3], [4, 5, 6]]
B = lil_matrix(array(row_data))
for r, row in enumerate(B):
assert_array_equal(row.todense(), array(row_data[r], ndmin=2))
def test_lil_from_csr(self):
# Tests whether a lil_matrix can be constructed from a
# csr_matrix.
B = lil_matrix((10, 10))
B[0, 3] = 10
B[5, 6] = 20
B[8, 3] = 30
B[3, 8] = 40
B[8, 9] = 50
C = B.tocsr()
D = lil_matrix(C)
assert_array_equal(C.A, D.A)
def test_fancy_indexing_lil(self):
M = asmatrix(arange(25).reshape(5, 5))
A = lil_matrix(M)
assert_equal(A[array([1, 2, 3]), 2:3].todense(),
M[array([1, 2, 3]), 2:3])
def test_point_wise_multiply(self):
l = lil_matrix((4, 3))
l[0, 0] = 1
l[1, 1] = 2
l[2, 2] = 3
l[3, 1] = 4
m = lil_matrix((4, 3))
m[0, 0] = 1
m[0, 1] = 2
m[2, 2] = 3
m[3, 1] = 4
m[3, 2] = 4
assert_array_equal(l.multiply(m).todense(),
m.multiply(l).todense())
assert_array_equal(l.multiply(m).todense(),
[[1, 0, 0],
[0, 0, 0],
[0, 0, 9],
[0, 16, 0]])
def test_lil_multiply_removal(self):
# Ticket #1427.
a = lil_matrix(np.ones((3, 3)))
a *= 2.
a[0, :] = 0
TestLIL.init_class()
class TestCOO(sparse_test_class(getset=False,
slicing=False, slicing_assign=False,
fancy_indexing=False, fancy_assign=False)):
spmatrix = coo_matrix
math_dtypes = [np.int_, np.float_, np.complex_]
def test_constructor1(self):
# unsorted triplet format
row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2])
col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1])
data = array([6., 10., 3., 9., 1., 4.,
11., 2., 8., 5., 7.])
coo = coo_matrix((data,(row,col)),(4,3))
assert_array_equal(arange(12).reshape(4,3),coo.todense())
def test_constructor2(self):
# unsorted triplet format with duplicates (which are summed)
row = array([0,1,2,2,2,2,0,0,2,2])
col = array([0,2,0,2,1,1,1,0,0,2])
data = array([2,9,-4,5,7,0,-1,2,1,-5])
coo = coo_matrix((data,(row,col)),(3,3))
mat = matrix([[4,-1,0],[0,0,9],[-3,7,0]])
assert_array_equal(mat,coo.todense())
def test_constructor3(self):
# empty matrix
coo = coo_matrix((4,3))
assert_array_equal(coo.shape,(4,3))
assert_array_equal(coo.row,[])
assert_array_equal(coo.col,[])
assert_array_equal(coo.data,[])
assert_array_equal(coo.todense(),zeros((4,3)))
def test_constructor4(self):
# from dense matrix
mat = array([[0,1,0,0],
[7,0,3,0],
[0,4,0,0]])
coo = coo_matrix(mat)
assert_array_equal(coo.todense(),mat)
# upgrade rank 1 arrays to row matrix
mat = array([0,1,0,0])
coo = coo_matrix(mat)
assert_array_equal(coo.todense(),mat.reshape(1,-1))
# error if second arg interpreted as shape (gh-9919)
with pytest.raises(TypeError, match=r'object cannot be interpreted'):
coo_matrix([0, 11, 22, 33], ([0, 1, 2, 3], [0, 0, 0, 0]))
# error if explicit shape arg doesn't match the dense matrix
with pytest.raises(ValueError, match=r'inconsistent shapes'):
coo_matrix([0, 11, 22, 33], shape=(4, 4))
@pytest.mark.xfail(run=False, reason='COO does not have a __getitem__')
def test_iterator(self):
pass
def test_todia_all_zeros(self):
zeros = [[0, 0]]
dia = coo_matrix(zeros).todia()
assert_array_equal(dia.A, zeros)
def test_sum_duplicates(self):
coo = coo_matrix((4,3))
coo.sum_duplicates()
coo = coo_matrix(([1,2], ([1,0], [1,0])))
coo.sum_duplicates()
assert_array_equal(coo.A, [[2,0],[0,1]])
coo = coo_matrix(([1,2], ([1,1], [1,1])))
coo.sum_duplicates()
assert_array_equal(coo.A, [[0,0],[0,3]])
assert_array_equal(coo.row, [1])
assert_array_equal(coo.col, [1])
assert_array_equal(coo.data, [3])
def test_todok_duplicates(self):
coo = coo_matrix(([1,1,1,1], ([0,2,2,0], [0,1,1,0])))
dok = coo.todok()
assert_array_equal(dok.A, coo.A)
def test_eliminate_zeros(self):
data = array([1, 0, 0, 0, 2, 0, 3, 0])
row = array([0, 0, 0, 1, 1, 1, 1, 1])
col = array([1, 2, 3, 4, 5, 6, 7, 8])
asp = coo_matrix((data, (row, col)), shape=(2,10))
bsp = asp.copy()
asp.eliminate_zeros()
assert_((asp.data != 0).all())
assert_array_equal(asp.A, bsp.A)
def test_reshape_copy(self):
arr = [[0, 10, 0, 0], [0, 0, 0, 0], [0, 20, 30, 40]]
new_shape = (2, 6)
x = coo_matrix(arr)
y = x.reshape(new_shape)
assert_(y.data is x.data)
y = x.reshape(new_shape, copy=False)
assert_(y.data is x.data)
y = x.reshape(new_shape, copy=True)
assert_(not np.may_share_memory(y.data, x.data))
def test_large_dimensions_reshape(self):
# Test that reshape is immune to integer overflow when number of elements
# exceeds 2^31-1
mat1 = coo_matrix(([1], ([3000000], [1000])), (3000001, 1001))
mat2 = coo_matrix(([1], ([1000], [3000000])), (1001, 3000001))
# assert_array_equal is slow for big matrices because it expects dense
# Using __ne__ and nnz instead
assert_((mat1.reshape((1001, 3000001), order='C') != mat2).nnz == 0)
assert_((mat2.reshape((3000001, 1001), order='F') != mat1).nnz == 0)
TestCOO.init_class()
class TestDIA(sparse_test_class(getset=False, slicing=False, slicing_assign=False,
fancy_indexing=False, fancy_assign=False,
minmax=False, nnz_axis=False)):
spmatrix = dia_matrix
math_dtypes = [np.int_, np.float_, np.complex_]
def test_constructor1(self):
D = matrix([[1, 0, 3, 0],
[1, 2, 0, 4],
[0, 2, 3, 0],
[0, 0, 3, 4]])
data = np.array([[1,2,3,4]]).repeat(3,axis=0)
offsets = np.array([0,-1,2])
assert_equal(dia_matrix((data,offsets), shape=(4,4)).todense(), D)
@pytest.mark.xfail(run=False, reason='DIA does not have a __getitem__')
def test_iterator(self):
pass
@with_64bit_maxval_limit(3)
def test_setdiag_dtype(self):
m = dia_matrix(np.eye(3))
assert_equal(m.offsets.dtype, np.int32)
m.setdiag((3,), k=2)
assert_equal(m.offsets.dtype, np.int32)
m = dia_matrix(np.eye(4))
assert_equal(m.offsets.dtype, np.int64)
m.setdiag((3,), k=3)
assert_equal(m.offsets.dtype, np.int64)
@pytest.mark.skip(reason='DIA stores extra zeros')
def test_getnnz_axis(self):
pass
TestDIA.init_class()
class TestBSR(sparse_test_class(getset=False,
slicing=False, slicing_assign=False,
fancy_indexing=False, fancy_assign=False,
nnz_axis=False)):
spmatrix = bsr_matrix
math_dtypes = [np.int_, np.float_, np.complex_]
def test_constructor1(self):
# check native BSR format constructor
indptr = array([0,2,2,4])
indices = array([0,2,2,3])
data = zeros((4,2,3))
data[0] = array([[0, 1, 2],
[3, 0, 5]])
data[1] = array([[0, 2, 4],
[6, 0, 10]])
data[2] = array([[0, 4, 8],
[12, 0, 20]])
data[3] = array([[0, 5, 10],
[15, 0, 25]])
A = kron([[1,0,2,0],[0,0,0,0],[0,0,4,5]], [[0,1,2],[3,0,5]])
Asp = bsr_matrix((data,indices,indptr),shape=(6,12))
assert_equal(Asp.todense(),A)
# infer shape from arrays
Asp = bsr_matrix((data,indices,indptr))
assert_equal(Asp.todense(),A)
def test_constructor2(self):
# construct from dense
# test zero mats
for shape in [(1,1), (5,1), (1,10), (10,4), (3,7), (2,1)]:
A = zeros(shape)
assert_equal(bsr_matrix(A).todense(),A)
A = zeros((4,6))
assert_equal(bsr_matrix(A,blocksize=(2,2)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(2,3)).todense(),A)
A = kron([[1,0,2,0],[0,0,0,0],[0,0,4,5]], [[0,1,2],[3,0,5]])
assert_equal(bsr_matrix(A).todense(),A)
assert_equal(bsr_matrix(A,shape=(6,12)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(1,1)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(2,3)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(2,6)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(2,12)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(3,12)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(6,12)).todense(),A)
A = kron([[1,0,2,0],[0,1,0,0],[0,0,0,0]], [[0,1,2],[3,0,5]])
assert_equal(bsr_matrix(A,blocksize=(2,3)).todense(),A)
def test_constructor3(self):
# construct from coo-like (data,(row,col)) format
arg = ([1,2,3], ([0,1,1], [0,0,1]))
A = array([[1,0],[2,3]])
assert_equal(bsr_matrix(arg, blocksize=(2,2)).todense(), A)
def test_constructor4(self):
# regression test for gh-6292: bsr_matrix((data, indices, indptr)) was
# trying to compare an int to a None
n = 8
data = np.ones((n, n, 1), dtype=np.int8)
indptr = np.array([0, n], dtype=np.int32)
indices = np.arange(n, dtype=np.int32)
bsr_matrix((data, indices, indptr), blocksize=(n, 1), copy=False)
def test_bsr_tocsr(self):
# check native conversion from BSR to CSR
indptr = array([0, 2, 2, 4])
indices = array([0, 2, 2, 3])
data = zeros((4, 2, 3))
data[0] = array([[0, 1, 2],
[3, 0, 5]])
data[1] = array([[0, 2, 4],
[6, 0, 10]])
data[2] = array([[0, 4, 8],
[12, 0, 20]])
data[3] = array([[0, 5, 10],
[15, 0, 25]])
A = kron([[1, 0, 2, 0], [0, 0, 0, 0], [0, 0, 4, 5]],
[[0, 1, 2], [3, 0, 5]])
Absr = bsr_matrix((data, indices, indptr), shape=(6, 12))
Acsr = Absr.tocsr()
Acsr_via_coo = Absr.tocoo().tocsr()
assert_equal(Acsr.todense(), A)
assert_equal(Acsr.todense(), Acsr_via_coo.todense())
def test_eliminate_zeros(self):
data = kron([1, 0, 0, 0, 2, 0, 3, 0], [[1,1],[1,1]]).T
data = data.reshape(-1,2,2)
indices = array([1, 2, 3, 4, 5, 6, 7, 8])
indptr = array([0, 3, 8])
asp = bsr_matrix((data, indices, indptr), shape=(4,20))
bsp = asp.copy()
asp.eliminate_zeros()
assert_array_equal(asp.nnz, 3*4)
assert_array_equal(asp.todense(),bsp.todense())
# github issue #9687
def test_eliminate_zeros_all_zero(self):
np.random.seed(0)
m = bsr_matrix(np.random.random((12, 12)), blocksize=(2, 3))
# eliminate some blocks, but not all
m.data[m.data <= 0.9] = 0
m.eliminate_zeros()
assert_equal(m.nnz, 66)
assert_array_equal(m.data.shape, (11, 2, 3))
# eliminate all remaining blocks
m.data[m.data <= 1.0] = 0
m.eliminate_zeros()
assert_equal(m.nnz, 0)
assert_array_equal(m.data.shape, (0, 2, 3))
assert_array_equal(m.todense(), np.zeros((12,12)))
# test fast path
m.eliminate_zeros()
assert_equal(m.nnz, 0)
assert_array_equal(m.data.shape, (0, 2, 3))
assert_array_equal(m.todense(), np.zeros((12,12)))
def test_bsr_matvec(self):
A = bsr_matrix(arange(2*3*4*5).reshape(2*4,3*5), blocksize=(4,5))
x = arange(A.shape[1]).reshape(-1,1)
assert_equal(A*x, A.todense() @ x)
def test_bsr_matvecs(self):
A = bsr_matrix(arange(2*3*4*5).reshape(2*4,3*5), blocksize=(4,5))
x = arange(A.shape[1]*6).reshape(-1,6)
assert_equal(A*x, A.todense() @ x)
@pytest.mark.xfail(run=False, reason='BSR does not have a __getitem__')
def test_iterator(self):
pass
@pytest.mark.xfail(run=False, reason='BSR does not have a __setitem__')
def test_setdiag(self):
pass
def test_resize_blocked(self):
# test resize() with non-(1,1) blocksize
D = np.array([[1, 0, 3, 4],
[2, 0, 0, 0],
[3, 0, 0, 0]])
S = self.spmatrix(D, blocksize=(1, 2))
assert_(S.resize((3, 2)) is None)
assert_array_equal(S.A, [[1, 0],
[2, 0],
[3, 0]])
S.resize((2, 2))
assert_array_equal(S.A, [[1, 0],
[2, 0]])
S.resize((3, 2))
assert_array_equal(S.A, [[1, 0],
[2, 0],
[0, 0]])
S.resize((3, 4))
assert_array_equal(S.A, [[1, 0, 0, 0],
[2, 0, 0, 0],
[0, 0, 0, 0]])
assert_raises(ValueError, S.resize, (2, 3))
@pytest.mark.xfail(run=False, reason='BSR does not have a __setitem__')
def test_setdiag_comprehensive(self):
pass
@pytest.mark.skipif(IS_COLAB, reason="exceeds memory limit")
def test_scalar_idx_dtype(self):
# Check that index dtype takes into account all parameters
# passed to sparsetools, including the scalar ones
indptr = np.zeros(2, dtype=np.int32)
indices = np.zeros(0, dtype=np.int32)
vals = np.zeros((0, 1, 1))
a = bsr_matrix((vals, indices, indptr), shape=(1, 2**31-1))
b = bsr_matrix((vals, indices, indptr), shape=(1, 2**31))
c = bsr_matrix((1, 2**31-1))
d = bsr_matrix((1, 2**31))
assert_equal(a.indptr.dtype, np.int32)
assert_equal(b.indptr.dtype, np.int64)
assert_equal(c.indptr.dtype, np.int32)
assert_equal(d.indptr.dtype, np.int64)
try:
vals2 = np.zeros((0, 1, 2**31-1))
vals3 = np.zeros((0, 1, 2**31))
e = bsr_matrix((vals2, indices, indptr), shape=(1, 2**31-1))
f = bsr_matrix((vals3, indices, indptr), shape=(1, 2**31))
assert_equal(e.indptr.dtype, np.int32)
assert_equal(f.indptr.dtype, np.int64)
except (MemoryError, ValueError):
# May fail on 32-bit Python
e = 0
f = 0
# These shouldn't fail
for x in [a, b, c, d, e, f]:
x + x
TestBSR.init_class()
#------------------------------------------------------------------------------
# Tests for non-canonical representations (with duplicates, unsorted indices)
#------------------------------------------------------------------------------
def _same_sum_duplicate(data, *inds, **kwargs):
"""Duplicates entries to produce the same matrix"""
indptr = kwargs.pop('indptr', None)
if np.issubdtype(data.dtype, np.bool_) or \
np.issubdtype(data.dtype, np.unsignedinteger):
if indptr is None:
return (data,) + inds
else:
return (data,) + inds + (indptr,)
zeros_pos = (data == 0).nonzero()
# duplicate data
data = data.repeat(2, axis=0)
data[::2] -= 1
data[1::2] = 1
# don't spoil all explicit zeros
if zeros_pos[0].size > 0:
pos = tuple(p[0] for p in zeros_pos)
pos1 = (2*pos[0],) + pos[1:]
pos2 = (2*pos[0]+1,) + pos[1:]
data[pos1] = 0
data[pos2] = 0
inds = tuple(indices.repeat(2) for indices in inds)
if indptr is None:
return (data,) + inds
else:
return (data,) + inds + (indptr * 2,)
class _NonCanonicalMixin(object):
def spmatrix(self, D, sorted_indices=False, **kwargs):
"""Replace D with a non-canonical equivalent: containing
duplicate elements and explicit zeros"""
construct = super(_NonCanonicalMixin, self).spmatrix
M = construct(D, **kwargs)
zero_pos = (M.A == 0).nonzero()
has_zeros = (zero_pos[0].size > 0)
if has_zeros:
k = zero_pos[0].size//2
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
M = self._insert_explicit_zero(M, zero_pos[0][k], zero_pos[1][k])
arg1 = self._arg1_for_noncanonical(M, sorted_indices)
if 'shape' not in kwargs:
kwargs['shape'] = M.shape
NC = construct(arg1, **kwargs)
# check that result is valid
if NC.dtype in [np.float32, np.complex64]:
# For single-precision floats, the differences between M and NC
# that are introduced by the extra operations involved in the
# construction of NC necessitate a more lenient tolerance level
# than the default.
rtol = 1e-05
else:
rtol = 1e-07
assert_allclose(NC.A, M.A, rtol=rtol)
# check that at least one explicit zero
if has_zeros:
assert_((NC.data == 0).any())
# TODO check that NC has duplicates (which are not explicit zeros)
return NC
@pytest.mark.skip(reason='bool(matrix) counts explicit zeros')
def test_bool(self):
pass
@pytest.mark.skip(reason='getnnz-axis counts explicit zeros')
def test_getnnz_axis(self):
pass
@pytest.mark.skip(reason='nnz counts explicit zeros')
def test_empty(self):
pass
class _NonCanonicalCompressedMixin(_NonCanonicalMixin):
def _arg1_for_noncanonical(self, M, sorted_indices=False):
"""Return non-canonical constructor arg1 equivalent to M"""
data, indices, indptr = _same_sum_duplicate(M.data, M.indices,
indptr=M.indptr)
if not sorted_indices:
for start, stop in zip(indptr, indptr[1:]):
indices[start:stop] = indices[start:stop][::-1].copy()
data[start:stop] = data[start:stop][::-1].copy()
return data, indices, indptr
def _insert_explicit_zero(self, M, i, j):
M[i,j] = 0
return M
class _NonCanonicalCSMixin(_NonCanonicalCompressedMixin):
def test_getelement(self):
def check(dtype, sorted_indices):
D = array([[1,0,0],
[4,3,0],
[0,2,0],
[0,0,0]], dtype=dtype)
A = self.spmatrix(D, sorted_indices=sorted_indices)
M,N = D.shape
for i in range(-M, M):
for j in range(-N, N):
assert_equal(A[i,j], D[i,j])
for ij in [(0,3),(-1,3),(4,0),(4,3),(4,-1), (1, 2, 3)]:
assert_raises((IndexError, TypeError), A.__getitem__, ij)
for dtype in supported_dtypes:
for sorted_indices in [False, True]:
check(np.dtype(dtype), sorted_indices)
def test_setitem_sparse(self):
D = np.eye(3)
A = self.spmatrix(D)
B = self.spmatrix([[1,2,3]])
D[1,:] = B.toarray()
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
A[1,:] = B
assert_array_equal(A.toarray(), D)
D[:,2] = B.toarray().ravel()
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
A[:,2] = B.T
assert_array_equal(A.toarray(), D)
@pytest.mark.xfail(run=False, reason='inverse broken with non-canonical matrix')
def test_inv(self):
pass
@pytest.mark.xfail(run=False, reason='solve broken with non-canonical matrix')
def test_solve(self):
pass
class TestCSRNonCanonical(_NonCanonicalCSMixin, TestCSR):
pass
class TestCSCNonCanonical(_NonCanonicalCSMixin, TestCSC):
pass
class TestBSRNonCanonical(_NonCanonicalCompressedMixin, TestBSR):
def _insert_explicit_zero(self, M, i, j):
x = M.tocsr()
x[i,j] = 0
return x.tobsr(blocksize=M.blocksize)
@pytest.mark.xfail(run=False, reason='diagonal broken with non-canonical BSR')
def test_diagonal(self):
pass
@pytest.mark.xfail(run=False, reason='expm broken with non-canonical BSR')
def test_expm(self):
pass
class TestCOONonCanonical(_NonCanonicalMixin, TestCOO):
def _arg1_for_noncanonical(self, M, sorted_indices=None):
"""Return non-canonical constructor arg1 equivalent to M"""
data, row, col = _same_sum_duplicate(M.data, M.row, M.col)
return data, (row, col)
def _insert_explicit_zero(self, M, i, j):
M.data = np.r_[M.data.dtype.type(0), M.data]
M.row = np.r_[M.row.dtype.type(i), M.row]
M.col = np.r_[M.col.dtype.type(j), M.col]
return M
def test_setdiag_noncanonical(self):
m = self.spmatrix(np.eye(3))
m.sum_duplicates()
m.setdiag([3, 2], k=1)
m.sum_duplicates()
assert_(np.all(np.diff(m.col) >= 0))
def cases_64bit():
TEST_CLASSES = [TestBSR, TestCOO, TestCSC, TestCSR, TestDIA,
# lil/dok->other conversion operations have get_index_dtype
TestDOK, TestLIL
]
# The following features are missing, so skip the tests:
SKIP_TESTS = {
'test_expm': 'expm for 64-bit indices not available',
'test_inv': 'linsolve for 64-bit indices not available',
'test_solve': 'linsolve for 64-bit indices not available',
'test_scalar_idx_dtype': 'test implemented in base class',
'test_large_dimensions_reshape': 'test actually requires 64-bit to work',
'test_constructor_smallcol': 'test verifies int32 indexes',
'test_constructor_largecol': 'test verifies int64 indexes',
}
for cls in TEST_CLASSES:
for method_name in sorted(dir(cls)):
method = getattr(cls, method_name)
if (method_name.startswith('test_') and
not getattr(method, 'slow', False)):
marks = []
msg = SKIP_TESTS.get(method_name)
if bool(msg):
marks += [pytest.mark.skip(reason=msg)]
if LooseVersion(pytest.__version__) >= LooseVersion("3.6.0"):
markers = getattr(method, 'pytestmark', [])
for mark in markers:
if mark.name in ('skipif', 'skip', 'xfail', 'xslow'):
marks.append(mark)
else:
for mname in ['skipif', 'skip', 'xfail', 'xslow']:
if hasattr(method, mname):
marks += [getattr(method, mname)]
yield pytest.param(cls, method_name, marks=marks)
class Test64Bit(object):
MAT_CLASSES = [bsr_matrix, coo_matrix, csc_matrix, csr_matrix, dia_matrix]
def _create_some_matrix(self, mat_cls, m, n):
return mat_cls(np.random.rand(m, n))
def _compare_index_dtype(self, m, dtype):
dtype = np.dtype(dtype)
if isinstance(m, (csc_matrix, csr_matrix, bsr_matrix)):
return (m.indices.dtype == dtype) and (m.indptr.dtype == dtype)
elif isinstance(m, coo_matrix):
return (m.row.dtype == dtype) and (m.col.dtype == dtype)
elif isinstance(m, dia_matrix):
return (m.offsets.dtype == dtype)
else:
raise ValueError("matrix %r has no integer indices" % (m,))
def test_decorator_maxval_limit(self):
# Test that the with_64bit_maxval_limit decorator works
@with_64bit_maxval_limit(maxval_limit=10)
def check(mat_cls):
m = mat_cls(np.random.rand(10, 1))
assert_(self._compare_index_dtype(m, np.int32))
m = mat_cls(np.random.rand(11, 1))
assert_(self._compare_index_dtype(m, np.int64))
for mat_cls in self.MAT_CLASSES:
check(mat_cls)
def test_decorator_maxval_random(self):
# Test that the with_64bit_maxval_limit decorator works (2)
@with_64bit_maxval_limit(random=True)
def check(mat_cls):
seen_32 = False
seen_64 = False
for k in range(100):
m = self._create_some_matrix(mat_cls, 9, 9)
seen_32 = seen_32 or self._compare_index_dtype(m, np.int32)
seen_64 = seen_64 or self._compare_index_dtype(m, np.int64)
if seen_32 and seen_64:
break
else:
raise AssertionError("both 32 and 64 bit indices not seen")
for mat_cls in self.MAT_CLASSES:
check(mat_cls)
def _check_resiliency(self, cls, method_name, **kw):
# Resiliency test, to check that sparse matrices deal reasonably
# with varying index data types.
@with_64bit_maxval_limit(**kw)
def check(cls, method_name):
instance = cls()
if hasattr(instance, 'setup_method'):
instance.setup_method()
try:
getattr(instance, method_name)()
finally:
if hasattr(instance, 'teardown_method'):
instance.teardown_method()
check(cls, method_name)
@pytest.mark.parametrize('cls,method_name', cases_64bit())
def test_resiliency_limit_10(self, cls, method_name):
self._check_resiliency(cls, method_name, maxval_limit=10)
@pytest.mark.parametrize('cls,method_name', cases_64bit())
def test_resiliency_random(self, cls, method_name):
# bsr_matrix.eliminate_zeros relies on csr_matrix constructor
# not making copies of index arrays --- this is not
# necessarily true when we pick the index data type randomly
self._check_resiliency(cls, method_name, random=True)
@pytest.mark.parametrize('cls,method_name', cases_64bit())
def test_resiliency_all_32(self, cls, method_name):
self._check_resiliency(cls, method_name, fixed_dtype=np.int32)
@pytest.mark.parametrize('cls,method_name', cases_64bit())
def test_resiliency_all_64(self, cls, method_name):
self._check_resiliency(cls, method_name, fixed_dtype=np.int64)
@pytest.mark.parametrize('cls,method_name', cases_64bit())
def test_no_64(self, cls, method_name):
self._check_resiliency(cls, method_name, assert_32bit=True)
def test_downcast_intp(self):
# Check that bincount and ufunc.reduceat intp downcasts are
# dealt with. The point here is to trigger points in the code
# that can fail on 32-bit systems when using 64-bit indices,
# due to use of functions that only work with intp-size
# indices.
@with_64bit_maxval_limit(fixed_dtype=np.int64,
downcast_maxval=1)
def check_limited():
# These involve indices larger than `downcast_maxval`
a = csc_matrix([[1, 2], [3, 4], [5, 6]])
assert_raises(AssertionError, a.getnnz, axis=1)
assert_raises(AssertionError, a.sum, axis=0)
a = csr_matrix([[1, 2, 3], [3, 4, 6]])
assert_raises(AssertionError, a.getnnz, axis=0)
a = coo_matrix([[1, 2, 3], [3, 4, 5]])
assert_raises(AssertionError, a.getnnz, axis=0)
@with_64bit_maxval_limit(fixed_dtype=np.int64)
def check_unlimited():
# These involve indices larger than `downcast_maxval`
a = csc_matrix([[1, 2], [3, 4], [5, 6]])
a.getnnz(axis=1)
a.sum(axis=0)
a = csr_matrix([[1, 2, 3], [3, 4, 6]])
a.getnnz(axis=0)
a = coo_matrix([[1, 2, 3], [3, 4, 5]])
a.getnnz(axis=0)
check_limited()
check_unlimited()
| 36.770464 | 122 | 0.533736 |
89f0bbf4d12b8152c8e54f67d0d4e59db10f9a20 | 419 | py | Python | blog/migrations/0008_auto_20180126_0622.py | mhn-mnsr/Portfolio | 3414eff08d7974965717b95537d5972312003030 | [
"MIT"
] | 6 | 2018-02-01T16:57:29.000Z | 2022-02-08T08:30:35.000Z | blog/migrations/0008_auto_20180126_0622.py | mhn-mnsr/Portfolio | 3414eff08d7974965717b95537d5972312003030 | [
"MIT"
] | 2 | 2018-01-28T10:32:09.000Z | 2018-04-17T13:41:11.000Z | blog/migrations/0008_auto_20180126_0622.py | mhn-mnsr/Portfolio | 3414eff08d7974965717b95537d5972312003030 | [
"MIT"
] | 4 | 2019-08-08T20:15:33.000Z | 2020-10-01T04:18:32.000Z | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import ckeditor.fields
class Migration(migrations.Migration):
dependencies = [
('blog', '0007_auto_20170909_2231'),
]
operations = [
migrations.AlterField(
model_name='post',
name='brief',
field=ckeditor.fields.RichTextField(),
),
]
| 19.952381 | 50 | 0.613365 |
ad39b261a53c5c576b73c539e74ecf69df5a33df | 754 | py | Python | sensors/watchExtensionsV1beta1ThirdPartyResourceList.py | blinkops/stackstorm-kubernetes | 3b4a15d42f603f3e700efaf534169e2ec361f5d2 | [
"Apache-2.0"
] | 20 | 2016-12-24T01:35:41.000Z | 2022-03-06T08:32:16.000Z | sensors/watchExtensionsV1beta1ThirdPartyResourceList.py | blinkops/stackstorm-kubernetes | 3b4a15d42f603f3e700efaf534169e2ec361f5d2 | [
"Apache-2.0"
] | 16 | 2017-05-02T19:38:57.000Z | 2021-06-17T08:31:17.000Z | sensors/watchExtensionsV1beta1ThirdPartyResourceList.py | blinkops/stackstorm-kubernetes | 3b4a15d42f603f3e700efaf534169e2ec361f5d2 | [
"Apache-2.0"
] | 18 | 2017-06-20T00:44:12.000Z | 2022-03-30T08:41:42.000Z | from os import sys, path
if __name__ == '__main__' and __package__ is None:
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from sensor_base import SensorBase
class watchExtensionsV1beta1ThirdPartyResourceList(SensorBase):
def __init__(
self,
sensor_service,
config=None,
extension="/apis/extensions/v1beta1/watch/thirdpartyresources",
trigger_ref="kubernetes.thirdpartyresources"):
super( # pylint: disable=bad-super-call
self.__class__, # pylint: disable=bad-super-call
self).__init__(
sensor_service=sensor_service,
config=config,
extension=extension,
trigger_ref=trigger_ref)
| 32.782609 | 75 | 0.655172 |
525e71a538957de71ea2c61d1d1a109f05483620 | 3,460 | py | Python | catalyst/rl/scripts/run_trainer.py | cgarciae/catalyst | 391ff89ab0d9a1961b88719e894f917ac0fb7fc3 | [
"Apache-2.0"
] | 1 | 2019-11-26T06:41:33.000Z | 2019-11-26T06:41:33.000Z | catalyst/rl/scripts/run_trainer.py | cgarciae/catalyst | 391ff89ab0d9a1961b88719e894f917ac0fb7fc3 | [
"Apache-2.0"
] | null | null | null | catalyst/rl/scripts/run_trainer.py | cgarciae/catalyst | 391ff89ab0d9a1961b88719e894f917ac0fb7fc3 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
import argparse
import os
from catalyst import utils
from catalyst.rl.offpolicy.trainer import OffpolicyTrainer as OffpolicyTrainer
from catalyst.rl.onpolicy.trainer import OnpolicyTrainer as OnpolicyTrainer
from catalyst.rl.registry import (
DATABASES, ENVIRONMENTS, OFFPOLICY_ALGORITHMS, ONPOLICY_ALGORITHMS
)
from catalyst.rl.scripts.misc import (
OFFPOLICY_ALGORITHMS_NAMES, ONPOLICY_ALGORITHMS_NAMES
)
from catalyst.utils import (
boolean_flag, dump_code, dump_environment, import_module, parse_args_uargs,
prepare_cudnn, set_global_seed
)
def build_args(parser):
parser.add_argument(
"--config",
"--configs",
"-C",
nargs="+",
help="path to config/configs",
metavar="CONFIG_PATH",
dest="configs",
required=True
)
parser.add_argument("--expdir", type=str, default=None)
parser.add_argument("--logdir", type=str, default=None)
parser.add_argument("--resume", type=str, default=None)
parser.add_argument("--seed", type=int, default=42)
boolean_flag(
parser, "deterministic",
default=None,
help="Deterministic mode if running in CuDNN backend"
)
boolean_flag(
parser, "benchmark",
default=None,
help="Use CuDNN benchmark"
)
return parser
def parse_args():
parser = argparse.ArgumentParser()
build_args(parser)
args, unknown_args = parser.parse_known_args()
return args, unknown_args
def main(args, unknown_args):
args, config = parse_args_uargs(args, unknown_args)
set_global_seed(args.seed)
prepare_cudnn(args.deterministic, args.benchmark)
if args.logdir is not None:
os.makedirs(args.logdir, exist_ok=True)
dump_environment(config, args.logdir, args.configs)
if args.expdir is not None:
module = import_module(expdir=args.expdir) # noqa: F841
if args.logdir is not None:
dump_code(args.expdir, args.logdir)
env = ENVIRONMENTS.get_from_params(**config["environment"])
algorithm_name = config["algorithm"].pop("algorithm")
if algorithm_name in OFFPOLICY_ALGORITHMS_NAMES:
ALGORITHMS = OFFPOLICY_ALGORITHMS
trainer_fn = OffpolicyTrainer
sync_epoch = False
elif algorithm_name in ONPOLICY_ALGORITHMS_NAMES:
ALGORITHMS = ONPOLICY_ALGORITHMS
trainer_fn = OnpolicyTrainer
sync_epoch = True
else:
# @TODO: add registry for algorithms, trainers, samplers
raise NotImplementedError()
db_server = DATABASES.get_from_params(
**config.get("db", {}), sync_epoch=sync_epoch
)
algorithm_fn = ALGORITHMS.get(algorithm_name)
algorithm = algorithm_fn.prepare_for_trainer(env_spec=env, config=config)
if args.resume is not None:
checkpoint = utils.load_checkpoint(filepath=args.resume)
checkpoint = utils.any2device(checkpoint, utils.get_device())
algorithm.unpack_checkpoint(
checkpoint=checkpoint,
with_optimizer=False
)
monitoring_params = config.get("monitoring_params", None)
trainer = trainer_fn(
algorithm=algorithm,
env_spec=env,
db_server=db_server,
logdir=args.logdir,
monitoring_params=monitoring_params,
**config["trainer"],
)
trainer.run()
if __name__ == "__main__":
args, unknown_args = parse_args()
main(args, unknown_args)
| 29.07563 | 79 | 0.684682 |
9e84562d8dec433e7968f7c8ca0be6a2cd5112d8 | 706 | py | Python | data/scripts/templates/object/tangible/deed/pet_deed/shared_deed_r4_advanced_basic.py | obi-two/GameServer | 7d37024e2291a97d49522610cd8f1dbe5666afc2 | [
"MIT"
] | 20 | 2015-02-23T15:11:56.000Z | 2022-03-18T20:56:48.000Z | data/scripts/templates/object/tangible/deed/pet_deed/shared_deed_r4_advanced_basic.py | apathyboy/swganh | 665128efe9154611dec4cb5efc61d246dd095984 | [
"MIT"
] | null | null | null | data/scripts/templates/object/tangible/deed/pet_deed/shared_deed_r4_advanced_basic.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/deed/pet_deed/shared_deed_r4_advanced_basic.iff"
result.attribute_template_id = 2
result.stfName("deed","r4_advanced_basic_deed")
#### BEGIN MODIFICATIONS ####
result.setStringAttribute("radial_filename", "radials/deed_datapad.py")
result.setStringAttribute("deed_pcd", "object/intangible/pet/shared_r4_crafted.iff")
result.setStringAttribute("deed_mobile", "object/mobile/shared_r4_crafted.iff")
#### END MODIFICATIONS ####
return result | 35.3 | 85 | 0.767705 |
b9e342097d1286f0596a88ba5c65f3a8fe890b94 | 1,102 | py | Python | graduated_site/migrations/0036_company.py | vbacaksiz/KTU-MEBSIS | e1afaa07a16e00ff9be3f39b728603b64f08590e | [
"MIT"
] | null | null | null | graduated_site/migrations/0036_company.py | vbacaksiz/KTU-MEBSIS | e1afaa07a16e00ff9be3f39b728603b64f08590e | [
"MIT"
] | null | null | null | graduated_site/migrations/0036_company.py | vbacaksiz/KTU-MEBSIS | e1afaa07a16e00ff9be3f39b728603b64f08590e | [
"MIT"
] | null | null | null | # Generated by Django 3.0 on 2019-12-20 13:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('graduated_site', '0035_auto_20191219_1039'),
]
operations = [
migrations.CreateModel(
name='company',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('phone_number', models.CharField(max_length=11, null=True, verbose_name='Telefon Numarası')),
('adress', models.CharField(max_length=200, null=True, verbose_name='Adres')),
('company_name', models.CharField(max_length=25, null=True, verbose_name='Şirket Adı')),
('company_type', models.CharField(max_length=25, null=True, verbose_name='Şirket Türü')),
('company_sector', models.ManyToManyField(help_text='Şirketin çalışma alanlarını seçiniz.(Birden fazla seçilebilir.)', related_name='sektör', to='graduated_site.working_area', verbose_name='Şirket Sektörü')),
],
),
]
| 44.08 | 224 | 0.646098 |
75dbc94023a9adae4aa9b135304f47a0dca191d4 | 1,280 | py | Python | examples/color_wheel.py | falkaer/tplink-lb130-api | 9ba3617679f7b7ec1614d0dda16bfe1c2ef2dce5 | [
"Unlicense"
] | 4 | 2019-03-10T00:50:04.000Z | 2020-12-19T01:22:25.000Z | examples/color_wheel.py | falkaer/tplink-lb130-api | 9ba3617679f7b7ec1614d0dda16bfe1c2ef2dce5 | [
"Unlicense"
] | null | null | null | examples/color_wheel.py | falkaer/tplink-lb130-api | 9ba3617679f7b7ec1614d0dda16bfe1c2ef2dce5 | [
"Unlicense"
] | null | null | null | # transitions between red -> green -> blue -> red...
# every 5 seconds, for a total of 15 seconds in a roundtrip
known_bulbs = 4
import socket
import time
from multiprocessing.pool import ThreadPool
bulbs = set()
from lb130 import discover_local
def cb(bulb, _):
print('Discovered bulb at', bulb.protocol.ip)
bulbs.add(bulb)
discover_local(cb, 10, 0.1, known_bulbs)
interval = 5
# red -> green -> blue
h = 0
s = 60
b = 60
def transition(bulb, h, s, b, interval):
i = interval
st = time.time()
while True:
try:
bulb.transition_light_state(h, s, b, transition_period=int(i * 1000))
break
except socket.timeout:
t = time.time()
i = st + interval - t
if i < 1: # less than one second left
break
with ThreadPool(len(bulbs)) as p:
while True:
print('Transitioning lights to HSB(%d, %d, %d) over %d seconds' % (h, s, b, interval))
for bulb in bulbs:
p.apply_async(transition, (bulb, h, s, b, interval))
h = (h + 120) % 360
time.sleep(interval + 0.1) # give it +0.1 to account for TCP latency (no jerky transitions)
| 23.272727 | 100 | 0.553125 |
7685f57dfdbb2a0e8bb323883784782ef0f7c6c2 | 5,176 | py | Python | python_modules/dagster/dagster/core/host_representation/selector.py | withshubh/dagster | ff4a0db53e126f44097a337eecef54988cc718ef | [
"Apache-2.0"
] | null | null | null | python_modules/dagster/dagster/core/host_representation/selector.py | withshubh/dagster | ff4a0db53e126f44097a337eecef54988cc718ef | [
"Apache-2.0"
] | 1 | 2021-06-21T18:30:02.000Z | 2021-06-25T21:18:39.000Z | python_modules/dagster/dagster/core/host_representation/selector.py | withshubh/dagster | ff4a0db53e126f44097a337eecef54988cc718ef | [
"Apache-2.0"
] | null | null | null | from collections import namedtuple
from dagster import check
class PipelineSelector(
namedtuple("_PipelineSelector", "location_name repository_name pipeline_name solid_selection")
):
"""
The information needed to resolve a pipeline within a host process.
"""
def __new__(
cls,
location_name,
repository_name,
pipeline_name,
solid_selection,
):
return super(PipelineSelector, cls).__new__(
cls,
location_name=check.str_param(location_name, "location_name"),
repository_name=check.str_param(repository_name, "repository_name"),
pipeline_name=check.str_param(pipeline_name, "pipeline_name"),
solid_selection=check.opt_nullable_list_param(solid_selection, "solid_selection", str),
)
def to_graphql_input(self):
return {
"repositoryLocationName": self.location_name,
"repositoryName": self.repository_name,
"pipelineName": self.pipeline_name,
"solidSelection": self.solid_selection,
}
def with_solid_selection(self, solid_selection):
check.invariant(
self.solid_selection is None,
"Can not invoke with_solid_selection when solid_selection={} is already set".format(
solid_selection
),
)
return PipelineSelector(
self.location_name, self.repository_name, self.pipeline_name, solid_selection
)
class RepositorySelector(namedtuple("_RepositorySelector", "location_name repository_name")):
def __new__(cls, location_name, repository_name):
return super(RepositorySelector, cls).__new__(
cls,
location_name=check.str_param(location_name, "location_name"),
repository_name=check.str_param(repository_name, "repository_name"),
)
def to_graphql_input(self):
return {
"repositoryLocationName": self.location_name,
"repositoryName": self.repository_name,
}
@staticmethod
def from_graphql_input(graphql_data):
return RepositorySelector(
location_name=graphql_data["repositoryLocationName"],
repository_name=graphql_data["repositoryName"],
)
class ScheduleSelector(
namedtuple("_ScheduleSelector", "location_name repository_name schedule_name")
):
def __new__(cls, location_name, repository_name, schedule_name):
return super(ScheduleSelector, cls).__new__(
cls,
location_name=check.str_param(location_name, "location_name"),
repository_name=check.str_param(repository_name, "repository_name"),
schedule_name=check.str_param(schedule_name, "schedule_name"),
)
def to_graphql_input(self):
return {
"repositoryLocationName": self.location_name,
"repositoryName": self.repository_name,
"scheduleName": self.schedule_name,
}
@staticmethod
def from_graphql_input(graphql_data):
return ScheduleSelector(
location_name=graphql_data["repositoryLocationName"],
repository_name=graphql_data["repositoryName"],
schedule_name=graphql_data["scheduleName"],
)
class SensorSelector(namedtuple("_SensorSelector", "location_name repository_name sensor_name")):
def __new__(cls, location_name, repository_name, sensor_name):
return super(SensorSelector, cls).__new__(
cls,
location_name=check.str_param(location_name, "location_name"),
repository_name=check.str_param(repository_name, "repository_name"),
sensor_name=check.str_param(sensor_name, "sensor_name"),
)
def to_graphql_input(self):
return {
"repositoryLocationName": self.location_name,
"repositoryName": self.repository_name,
"sensorName": self.sensor_name,
}
@staticmethod
def from_graphql_input(graphql_data):
return SensorSelector(
location_name=graphql_data["repositoryLocationName"],
repository_name=graphql_data["repositoryName"],
sensor_name=graphql_data["sensorName"],
)
class JobSelector(namedtuple("_JobSelector", "location_name repository_name job_name")):
def __new__(cls, location_name, repository_name, job_name):
return super(JobSelector, cls).__new__(
cls,
location_name=check.str_param(location_name, "location_name"),
repository_name=check.str_param(repository_name, "repository_name"),
job_name=check.str_param(job_name, "job_name"),
)
def to_graphql_input(self):
return {
"repositoryLocationName": self.location_name,
"repositoryName": self.repository_name,
"jobName": self.job_name,
}
@staticmethod
def from_graphql_input(graphql_data):
return JobSelector(
location_name=graphql_data["repositoryLocationName"],
repository_name=graphql_data["repositoryName"],
job_name=graphql_data["jobName"],
)
| 35.696552 | 99 | 0.663253 |
da577c7c53fd289384d44d3f6cfacfe6f26d2a55 | 1,942 | py | Python | trainer/tests/stop.py | bromjiri/Presto | e5790f60d0935bb1182f676db414b0724ba35c1b | [
"MIT"
] | null | null | null | trainer/tests/stop.py | bromjiri/Presto | e5790f60d0935bb1182f676db414b0724ba35c1b | [
"MIT"
] | null | null | null | trainer/tests/stop.py | bromjiri/Presto | e5790f60d0935bb1182f676db414b0724ba35c1b | [
"MIT"
] | null | null | null | import datetime
import trainer.corpora as crp
import trainer.features as ftr
import trainer.classifier_test as cls
import os
# vars
type = "stop-pos"
nltk_run = True
sklearn_run = False
COUNT = 5000
cut = int((COUNT / 2) * 3 / 4)
array = [True]
def run(dataset):
nlt = dict()
skl = dict()
dir = "output/" + dataset + "/" + type + "/"
os.makedirs(dir, exist_ok=True)
# file
for variable in array:
var_name = str(variable)
if nltk_run:
nlt_file = dir + dataset + "-" + type + "-" + var_name + "-nlt.csv"
nlt[var_name] = open(nlt_file, 'a')
nlt[var_name].write(str(datetime.datetime.today()) + "\n")
if sklearn_run:
skl_file = dir + dataset + "-" + type + "-" + var_name + "-skl.csv"
skl[var_name] = open(skl_file, 'a')
skl[var_name].write(str(datetime.datetime.today()) + "\n")
# cycle
for x in range(0, 10):
print(x)
corpora = crp.Corpora(dataset, count=COUNT, shuffle=True)
for variable in array:
print(str(variable))
var_name = str(variable)
features = ftr.Features(corpora, total=COUNT, bigram=False, stop=variable, pos=["J", "V", "N", "R"])
posfeats = features.get_features_pos()
negfeats = features.get_fearures_neg()
trainfeats = negfeats[:cut] + posfeats[:cut]
testfeats = negfeats[cut:] + posfeats[cut:]
nlt_output, skl_output = cls.train(trainfeats, testfeats, nlt=nltk_run, skl=sklearn_run)
if nltk_run:
print(str(nlt_output))
nlt[var_name].write(nlt_output)
nlt[var_name].flush()
if sklearn_run:
print(str(skl_output))
skl[var_name].write(skl_output)
skl[var_name].flush()
dataset_array = ["stwits"]
for dataset in dataset_array:
run(dataset) | 27.742857 | 112 | 0.568486 |
99f03a6551ab1b20f110b2945fa8870d60c2e7e9 | 5,154 | py | Python | utilities/autoware_launcher/src/autoware_launcher/tool/editor.py | alanjclark/autoware.ai | ba97edbbffb6f22e78912bf96400a59ef6a13daf | [
"Apache-2.0"
] | 20 | 2019-05-21T06:14:17.000Z | 2021-11-03T04:36:09.000Z | ros/src/util/packages/autoware_launcher/src/autoware_launcher/tool/editor.py | anhnv3991/autoware | d5b2ed9dc309193c8a2a7c77a2b6c88104c28328 | [
"Apache-2.0"
] | 40 | 2019-06-24T16:56:15.000Z | 2022-02-28T13:41:58.000Z | ros/src/util/packages/autoware_launcher/src/autoware_launcher/tool/editor.py | anhnv3991/autoware | d5b2ed9dc309193c8a2a7c77a2b6c88104c28328 | [
"Apache-2.0"
] | 31 | 2020-05-29T07:51:58.000Z | 2022-03-26T05:46:33.000Z | from autoware_launcher.core import plugin
from autoware_launcher.core import myutils
from python_qt_binding import QtCore
from python_qt_binding import QtWidgets
import argparse
import collections
import re
import rospkg
import yaml
import xml.etree.ElementTree as xtree
def represent_ordered_dict(dumper, instance):
return dumper.represent_mapping('tag:yaml.org,2002:map', instance.items())
yaml.add_representer(collections.OrderedDict, represent_ordered_dict)
def main(sys_argv):
if len(sys_argv) < 2:
print("missing plugin file path")
return 2
application = QtWidgets.QApplication(sys_argv)
widget = PluginEditWidget()
ynode = plugin.AwPluginNode(None, sys_argv[1])
ynode.load(myutils.package("plugins"))
xnode = load_launch_xml(ynode.rosxml())
fields = [PluginEditField(child.attrib) for child in xnode if child.tag == "arg"]
for field in fields: widget.add_field(field)
widget.add_button()
for field in ynode.args(): widget.set_yaml(field)
widget.show()
return application.exec_()
def load_launch_xml(rosxml):
rospack = rospkg.RosPack()
regex = re.compile("\$\(find (.*?)\)")
match = regex.match(rosxml)
xpath = regex.sub(rospack.get_path(match.group(1)), rosxml)
return xtree.parse(xpath).getroot()
class PluginEditWidget(QtWidgets.QWidget):
header = ["Field Name", "Field Type", "Array Type", "Default Value"]
def __init__(self):
super(PluginEditWidget, self).__init__()
self.fields = collections.OrderedDict()
self.setLayout(QtWidgets.QGridLayout())
for col,text in enumerate(PluginEditWidget.header):
self.layout().addWidget(QtWidgets.QLabel(text), 0, col)
self.export = QtWidgets.QPushButton("Export")
self.export.clicked.connect(self.export_yaml)
def add_field(self, field):
row = self.layout().rowCount()
self.layout().addWidget(field.name, row, 0)
self.layout().addWidget(field.type, row, 1)
self.layout().addWidget(field.list, row, 2)
self.layout().addWidget(field.default, row, 3)
self.fields[field.name.text()] = field
def add_button(self):
row = self.layout().rowCount()
self.layout().addWidget(self.export, row, 0, 1, 4)
def set_yaml(self, data):
self.fields[data.name].set_yaml(data)
def export_yaml(self):
views = [field.export_view() for field in self.fields.values()]
fields = [field.export_dict() for field in self.fields.values()]
data = collections.OrderedDict()
data["args"] = fields
data["panel"] = collections.OrderedDict()
data["panel"]["widget"] = "node.panel"
data["panel"]["frames"] = views
text = yaml.dump(data, default_flow_style=None)
print(text)
clipboard = QtWidgets.QApplication.clipboard()
clipboard.setText(text)
class PluginEditField(object):
viewtypes = {"str":"text", "int":"int", "real":"real", "bool":"bool"}
def __init__(self, attr):
self.name = QtWidgets.QLabel()
self.type = QtWidgets.QComboBox()
self.list = QtWidgets.QComboBox()
self.default = QtWidgets.QLineEdit()
self.name.setText(attr["name"])
self.type.addItems(["str", "int", "real", "bool"])
self.list.addItems(["none", "space", "yaml"])
self.default.setText(attr.get("default"))
self.type.setCurrentIndex(-1)
if attr.get("default"):
itype = self.type_inference(attr["default"])
self.type.setCurrentIndex(self.type.findText(itype))
def type_inference(self, value):
if value.lower() in ["true", "false"]: return "bool"
if value.isdigit(): return "int"
if value.replace('.','',1).isdigit(): return "real"
return "str"
def set_yaml(self, data):
self.type.setCurrentIndex(self.type.findText(data.type))
if data.list:
self.list.setCurrentIndex(self.list.findText(data.list))
if data.rest.get("default"):
self.default.setText(str(data.rest["default"]))
def export_dict(self):
data = collections.OrderedDict()
data["name"] = str(self.name.text())
data["type"] = str(self.type.currentText())
if self.list.currentText() != "none":
data["list"] = str(self.list.currentText())
if self.default.text():
data["default"] = self.export_default(data, self.default.text())
return data
def export_default(self, data, value):
if data.get("list") is None:
if data["type"] == "str" : return str(value)
if data["type"] == "int" : return int(value)
if data["type"] == "real": return float(value)
if data["type"] == "bool": return (value.lower() == "true")
raise NotImplementedError("Unkown Type: " + str(data))
def export_view(self):
data = collections.OrderedDict()
data["target"] = "args." + str(self.name.text())
data["widget"] = "basic." + PluginEditField.viewtypes[self.type.currentText()]
return data | 32.828025 | 86 | 0.633683 |
a1f4677223e0ae57c25e5aa43301a3720dc0888e | 1,762 | py | Python | nowallet/exchange_rate.py | zularizal/nowallet | ca8d87a222a0ed2ccd12319a648d981a5b93a414 | [
"MIT"
] | null | null | null | nowallet/exchange_rate.py | zularizal/nowallet | ca8d87a222a0ed2ccd12319a648d981a5b93a414 | [
"MIT"
] | null | null | null | nowallet/exchange_rate.py | zularizal/nowallet | ca8d87a222a0ed2ccd12319a648d981a5b93a414 | [
"MIT"
] | null | null | null | import logging
import asyncio
import json
from typing import Dict, List, Any
from .socks_http import urlopen
CURRENCIES = ["USD", "EUR", "GBP", "AUD",
"CAD", "JPY", "CNY"] # type: List[str]
async def fetch_from_api(base_url: str,
chain_1209k: str,
loop=None) -> Dict[str, Any]:
fiats = ",".join(CURRENCIES) # type: str
url = base_url.format(chain_1209k.upper(), fiats) # type: str
logging.info("Fetching rates from URL: %s", url)
return json.loads(await urlopen(url, loop=loop))
async def fetch_exchange_rates(chain_1209k: str = "btc",
loop=None) -> Dict[str, Dict]:
btcav_url = ("https://apiv2.bitcoinaverage.com/indices/" +
"global/ticker/short?crypto={}&fiat={}") # type: str
ccomp_url = ("https://min-api.cryptocompare.com/data/" +
"price?fsym={}&tsyms={}") # type: str
all_rates = dict()
btcav_json = await fetch_from_api(
btcav_url, chain_1209k, loop=loop) # type: Dict[str, Any]
btcav_rates = dict() # type: Dict[str, float]
for key, value in btcav_json.items():
symbol = key.replace(chain_1209k.upper(), "") # type: str
if symbol in CURRENCIES:
btcav_rates[symbol] = value["last"]
all_rates["btcav"] = btcav_rates
ccomp_json = await fetch_from_api(
ccomp_url, chain_1209k, loop=loop) # type: Dict[str, Any]
all_rates["ccomp"] = ccomp_json
return all_rates
def main():
loop = asyncio.get_event_loop() # type: asyncio.AbstractEventLoop
result = loop.run_until_complete(
fetch_exchange_rates()) # type: Dict[str, float]
print(result)
loop.close()
if __name__ == "__main__":
main()
| 35.24 | 70 | 0.6084 |
fa2c6922b126ea54064cc4111412112bcd9d53ea | 2,101 | py | Python | tests/test_graphics_images.py | sbluen/reportlab | 98758940eeae30db80bbc9c555e42b8c89b86be8 | [
"BSD-3-Clause"
] | 9 | 2016-12-21T02:19:24.000Z | 2021-08-07T11:39:47.000Z | tests/test_graphics_images.py | sbluen/reportlab | 98758940eeae30db80bbc9c555e42b8c89b86be8 | [
"BSD-3-Clause"
] | 2 | 2015-03-16T18:32:58.000Z | 2019-03-20T07:17:04.000Z | tests/test_graphics_images.py | sbluen/reportlab | 98758940eeae30db80bbc9c555e42b8c89b86be8 | [
"BSD-3-Clause"
] | 26 | 2015-03-16T18:27:04.000Z | 2022-03-25T10:08:33.000Z | #Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
"""
Tests for RLG Image shapes.
"""
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, outputfile, printLocation
setOutDir(__name__)
import os
import unittest
from reportlab.graphics.shapes import Image, Drawing
from reportlab.graphics import renderPDF
from reportlab.lib.pagesizes import A4
IMAGES = []
IMAGENAME = 'cs_logo.gif'
IMAGENAME = 'pythonpowered.gif'
class ImageTestCase(unittest.TestCase):
"Test RLG Image shape."
def __del__(self):
if IMAGES[-1] != None:
return
else:
del IMAGES[-1]
d = Drawing(A4[0], A4[1])
for img in IMAGES:
d.add(img)
outPath = outputfile("test_graphics_images.pdf")
renderPDF.drawToFile(d, outPath) #, '')
assert os.path.exists(outPath) == 1
def test0(self):
"Test convert a bitmap file as Image shape into a tmp. PDF file."
d = Drawing(110, 44)
inPath = IMAGENAME
img = Image(0, 0, 110, 44, inPath)
d.add(img)
IMAGES.append(img)
def test1(self):
"Test Image shape, adding it to a PDF page."
inPath = IMAGENAME
img = Image(0, 0, 110, 44, inPath)
IMAGES.append(img)
def test2(self):
"Test scaled Image shape adding it to a PDF page."
inPath = IMAGENAME
img = Image(0, 0, 110, 44, inPath)
d = Drawing(110, 44)
d.add(img)
d.translate(120, 0)
d.scale(2, 2)
IMAGES.append(d)
def test3(self):
"Test rotated Image shape adding it to a PDF page."
inPath = IMAGENAME
img = Image(0, 0, 110, 44, inPath)
d = Drawing(110, 44)
d.add(img)
d.translate(420, 0)
d.scale(2, 2)
d.rotate(45)
IMAGES.append(d)
IMAGES.append(None) # used to indicate last test
def makeSuite():
return makeSuiteForClasses(ImageTestCase)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
printLocation()
| 23.344444 | 92 | 0.609234 |
0a4f14cd5de66e2091039038c10df7443c362bcb | 376 | py | Python | MachSuite/bfs/bulk/matspy.py | Sacusa/ALADDIN | 45ff9ab7edf84dfa964bc870f0c3634d1a4c55fb | [
"BSD-3-Clause"
] | 82 | 2015-04-12T17:29:48.000Z | 2020-06-19T00:33:51.000Z | MachSuite/bfs/bulk/matspy.py | Sacusa/ALADDIN | 45ff9ab7edf84dfa964bc870f0c3634d1a4c55fb | [
"BSD-3-Clause"
] | 31 | 2015-05-13T09:43:00.000Z | 2020-06-20T16:26:06.000Z | MachSuite/bfs/bulk/matspy.py | Sacusa/ALADDIN | 45ff9ab7edf84dfa964bc870f0c3634d1a4c55fb | [
"BSD-3-Clause"
] | 47 | 2015-02-10T02:37:11.000Z | 2020-06-04T01:24:01.000Z | #!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
from mat import mat, mat2
#(fig,ax)=plt.subplots()
plt.imshow(mat);
plt.savefig('mat.png')
plt.imshow(mat2);
plt.savefig('mat2.png')
print sum(map(sum,mat))
print sum(map(sum,mat2))
#d=dict(zip(list('ABCD'),[0,0,0,0]))
#for c in mat:
# d[c] += 1
#s=sum(d.values())
#for k in d:
# print 100*d[k]/s
| 17.090909 | 36 | 0.656915 |
108c4f94456e4fea0a1cc1e780a0e187c41ea94f | 1,567 | py | Python | src/configs/approach_crnn_plus_new.py | dbis-uibk/MediaEval2019 | d6e21a298e0c65966262f26036fdccda3722743a | [
"BSD-2-Clause"
] | 6 | 2019-09-27T02:14:23.000Z | 2022-03-31T07:37:38.000Z | src/configs/approach_crnn_plus_new.py | dbis-uibk/MediaEval2019 | d6e21a298e0c65966262f26036fdccda3722743a | [
"BSD-2-Clause"
] | 1 | 2020-08-08T03:12:33.000Z | 2020-08-08T03:12:33.000Z | src/configs/approach_crnn_plus_new.py | dbis-uibk/MediaEval2019 | d6e21a298e0c65966262f26036fdccda3722743a | [
"BSD-2-Clause"
] | null | null | null | import common
from dbispipeline.evaluators import FixedSplitGridEvaluator
import dbispipeline.result_handlers as result_handlers
from dbispipeline.utils import prefix_path
from loaders.combined import CombinedLoader
from models.crnn import CRNNPlusModel
from sklearn.pipeline import Pipeline
dataloader = CombinedLoader(
mel_data_path=prefix_path("melspec_data", common.DEFAULT_PATH),
mel_training_path=prefix_path("autotagging_moodtheme-train.tsv",
common.DEFAULT_PATH),
mel_test_path=prefix_path("autotagging_moodtheme-test.tsv",
common.DEFAULT_PATH),
mel_validate_path=prefix_path("autotagging_moodtheme-validation.tsv",
common.DEFAULT_PATH),
ess_training_path=prefix_path("accousticbrainz-train.pickle",
common.DEFAULT_PATH),
ess_test_path=prefix_path("accousticbrainz-test.pickle",
common.DEFAULT_PATH),
ess_validate_path=prefix_path("accousticbrainz-validation.pickle",
common.DEFAULT_PATH),
window='random',
num_windows=5,
)
pipeline = Pipeline([("model", CRNNPlusModel(dataloader=dataloader))])
grid_params = common.grid_params()
grid_params['n_jobs'] = 1
evaluator = FixedSplitGridEvaluator(
params={
"model__epochs": [8, 16],
"model__output_dropout": [0.3],
"model__concat_bn": [True],
},
grid_params=grid_params,
)
result_handlers = [
result_handlers.print_gridsearch_results,
]
| 35.613636 | 73 | 0.686662 |
3ec3a5facf36cf502136956861ec2dc0dc393530 | 2,309 | py | Python | example/channel/server.py | so1n/rap | e4e3f4fab9df6190793ec97008bccb669546f207 | [
"Apache-2.0"
] | 3 | 2020-12-24T14:42:49.000Z | 2022-03-23T07:28:58.000Z | example/channel/server.py | so1n/rap | e4e3f4fab9df6190793ec97008bccb669546f207 | [
"Apache-2.0"
] | 1 | 2021-01-20T10:24:49.000Z | 2021-01-30T07:52:47.000Z | example/channel/server.py | so1n/rap | e4e3f4fab9df6190793ec97008bccb669546f207 | [
"Apache-2.0"
] | null | null | null | import asyncio
from typing import Any
from aredis import StrictRedis # type: ignore
from rap.server import Server, UserChannel
from rap.server.plugin.processor import CryptoProcessor
async def async_channel(channel: UserChannel) -> None:
while await channel.loop():
body: Any = await channel.read_body()
if body == "hello":
cnt: int = 0
await channel.write(f"hello {cnt}")
while await channel.loop(cnt < 10):
cnt += 1
await channel.write(f"hello {cnt}")
else:
await channel.write("I don't know")
async def echo_body(channel: UserChannel) -> None:
cnt: int = 0
async for body in channel.iter_body():
await asyncio.sleep(0.1)
cnt += 1
print(cnt, body)
if cnt > 10:
break
await channel.write(f"pong! {cnt}")
async def echo_response(channel: UserChannel) -> None:
cnt: int = 0
async for response in channel.iter():
await asyncio.sleep(0.1)
cnt += 1
if cnt > 10:
break
await channel.write(response.body)
if __name__ == "__main__":
import logging
logging.basicConfig(
format="[%(asctime)s %(levelname)s] %(message)s", datefmt="%y-%m-%d %H:%M:%S", level=logging.DEBUG
)
loop = asyncio.new_event_loop()
rpc_server_1: Server = Server("example")
rpc_server_1.load_processor([CryptoProcessor({"test": "keyskeyskeyskeys"})])
rpc_server_1.register(async_channel)
rpc_server_1.register(echo_body)
rpc_server_1.register(echo_response)
rpc_server_2: Server = Server("example", port=9001)
rpc_server_2.load_processor([CryptoProcessor({"test": "keyskeyskeyskeys"})])
rpc_server_2.register(async_channel)
rpc_server_2.register(echo_body)
rpc_server_2.register(echo_response)
rpc_server_3: Server = Server("example", port=9002)
rpc_server_3.load_processor([CryptoProcessor({"test": "keyskeyskeyskeys"})])
rpc_server_3.register(async_channel)
rpc_server_3.register(echo_body)
rpc_server_3.register(echo_response)
async def run_forever() -> None:
await asyncio.gather(*[rpc_server_1.run_forever(), rpc_server_2.run_forever(), rpc_server_3.run_forever()])
loop.run_until_complete(run_forever())
| 31.202703 | 115 | 0.659593 |
e160067ade820c54a465cf05ce0848473be79b50 | 3,463 | py | Python | scripts/epi.py | reckbo/ppl | 916d96188a43bbc5915020edfa12f14895b5f66c | [
"BSD-3-Clause"
] | null | null | null | scripts/epi.py | reckbo/ppl | 916d96188a43bbc5915020edfa12f14895b5f66c | [
"BSD-3-Clause"
] | null | null | null | scripts/epi.py | reckbo/ppl | 916d96188a43bbc5915020edfa12f14895b5f66c | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
from __future__ import print_function
from os.path import basename, splitext, abspath, exists, dirname, join
from os import getpid
from util import logfmt, TemporaryDirectory, getext
from util.scripts import bse_py, antsApplyTransformsDWI_sh
from util.ants import antsRegistrationSyN_sh, antsApplyTransforms, antsRegistration
from plumbum import local, cli
from plumbum.cmd import unu
import logging
logger = logging.getLogger()
logging.basicConfig(level=logging.DEBUG, format=logfmt(__file__))
class App(cli.Application):
debug = cli.Flag(['-d', '--debug'], help='Debug, don\'t delete temporary directory')
dwi = cli.SwitchAttr('--dwi', cli.ExistingFile, help='DWI (nrrd)')
dwimask = cli.SwitchAttr('--dwimask', cli.ExistingFile, help='DWI mask (nrrd)')
t2 = cli.SwitchAttr('--t2', cli.ExistingFile, help='T2w (nrrd)')
t2mask = cli.SwitchAttr('--t2mask', cli.ExistingFile, help='T2w mask (nrrd)')
out = cli.SwitchAttr(['-o', '--out'], cli.NonexistentPath, help='EPI corrected DWI')
def main(self):
with TemporaryDirectory() as tmpdir:
tmpdir = local.path(tmpdir)
bse = tmpdir / "maskedbse.nrrd"
t2masked = tmpdir / "maskedt2.nrrd"
t2inbse = tmpdir / "t2inbse.nrrd"
epiwarp = tmpdir / "epiwarp.nii.gz"
t2tobse_rigid = tmpdir / "t2tobse_rigid"
logging.info('1. Extract and mask the DWI b0')
bse_py('-m', self.dwimask ,'-i', self.dwi ,'-o', bse)
logging.info("2. Mask the T2")
unu("3op", "ifelse", self.t2mask, self.t2, "0", "-o", t2masked)
logging.info(
"3. Compute a rigid registration from the T2 to the DWI baseline")
antsRegistrationSyN_sh("-d", "3"
,"-f", bse
,"-m", t2masked
,"-t", "r"
,"-o", tmpdir / "t2tobse_rigid")
antsApplyTransforms("-d", "3"
,"-i", t2masked
,"-o", t2inbse
,"-r", bse
,"-t", tmpdir / "t2tobse_rigid0GenericAffine.mat")
logging.info("4. Compute 1d nonlinear registration from the DWI to the T2 along the phase direction")
moving = bse
fixed = t2inbse
pre = tmpdir / "epi"
dwiepi = tmpdir / "dwiepi"+getext(self.out)
antsRegistration("-d", "3"
,"-m", "cc["+fixed+","+moving+",1,2]"
,"-t", "SyN[0.25,3,0]"
,"-c", "50x50x10"
,"-f", "4x2x1"
, "-s", "2x1x0"
,"--restrict-deformation", "0x1x0"
,"-v", "1"
,"-o", pre)
local.path(pre+"0Warp.nii.gz").move(epiwarp)
logging.info("5. Apply warp to the DWI")
antsApplyTransformsDWI_sh(self.dwi, self.dwimask, epiwarp, dwiepi)
if getext(dwiepi) == '.nhdr':
unu("save","-e","gzip","-f","nrrd","-i",dwiepi,self.out)
else:
dwiepi.move(self.out)
if self.debug:
tmpdir.move("epidebug-"+getpid())
if __name__ == '__main__':
App.run()
| 41.722892 | 113 | 0.509962 |
63ca731e5fec3f476c10f6064ac724cc3f695a62 | 1,100 | py | Python | airflow/contrib/sensors/file_sensor.py | khilawar4/airflow | 5f3f65b82517f615f31f0c8a7f8ac0facb325235 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 3 | 2021-01-29T20:33:56.000Z | 2021-08-06T17:35:16.000Z | airflow/contrib/sensors/file_sensor.py | khilawar4/airflow | 5f3f65b82517f615f31f0c8a7f8ac0facb325235 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 210 | 2021-07-17T00:25:52.000Z | 2021-12-29T00:44:48.000Z | airflow/contrib/sensors/file_sensor.py | khilawar4/airflow | 5f3f65b82517f615f31f0c8a7f8ac0facb325235 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 2 | 2021-04-14T11:15:17.000Z | 2021-12-15T16:58:24.000Z | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""This module is deprecated. Please use :mod:`airflow.sensors.filesystem`."""
import warnings
# pylint: disable=unused-import
from airflow.sensors.filesystem import FileSensor # noqa
warnings.warn(
"This module is deprecated. Please use `airflow.sensors.filesystem`.", DeprecationWarning, stacklevel=2
)
| 39.285714 | 107 | 0.770909 |
4c87d7707a26c6da2cf631fb573a03b674ed4608 | 298 | py | Python | tests/test_mpv.py | ktaranov/HPI | 3aa21107465b19b8b09884fbda8326617d3324ae | [
"MIT"
] | 1 | 2021-08-04T18:54:53.000Z | 2021-08-04T18:54:53.000Z | tests/test_mpv.py | ktaranov/HPI | 3aa21107465b19b8b09884fbda8326617d3324ae | [
"MIT"
] | null | null | null | tests/test_mpv.py | ktaranov/HPI | 3aa21107465b19b8b09884fbda8326617d3324ae | [
"MIT"
] | null | null | null | from my.mpv import history, all_history, Media
def test_mpv():
hist = list(history())
all_hist = list(all_history())
assert len(hist) > 1
play = hist[0]
assert isinstance(play, Media)
# just test an attr
assert len(play.path) > 0
assert len(all_hist) > len(hist)
| 21.285714 | 46 | 0.64094 |
291b0dfa1bcbb9a8b9e92597bc9d161d824c1f2e | 1,210 | py | Python | pp_api/tests/test_gs.py | alexisdimi/pp_api | 0f1a64e2b45e0aac33ccebba77b5e6812967cb96 | [
"MIT"
] | 3 | 2017-12-01T16:22:44.000Z | 2018-03-01T10:00:32.000Z | pp_api/tests/test_gs.py | alexisdimi/pp_api | 0f1a64e2b45e0aac33ccebba77b5e6812967cb96 | [
"MIT"
] | 3 | 2017-07-27T08:36:22.000Z | 2018-09-25T12:20:12.000Z | pp_api/tests/test_gs.py | alexisdimi/pp_api | 0f1a64e2b45e0aac33ccebba77b5e6812967cb96 | [
"MIT"
] | 5 | 2017-05-04T13:50:00.000Z | 2018-08-28T15:14:31.000Z | import logging
import unittest
from decouple import config
from pp_api import GraphSearch
log = logging.getLogger(__name__)
server = config('PP_SERVER')
auth_data = (config('GRAPHSEARCH_USER'), config('GRAPHSEARCH_PASS'))
search_space_id = config('GRAPHSEARCH_SEARCH_SPACE_ID')
graph_search = GraphSearch(server=server, auth_data=auth_data)
class TestSearch(unittest.TestCase):
def test_search_without_filters_response_OK(self):
response = graph_search.search(search_space_id=search_space_id)
self.assertEqual(200, response.status_code)
def test_search_with_filter_fulltext_response_OK(self):
search_filter = graph_search.filter_full_text('wall street')
response = graph_search.search(search_filters=search_filter, search_space_id=search_space_id)
self.assertEqual(200, response.status_code)
def test_search_with_filter_cpt_response_OK(self):
search_filter = graph_search.filter_cpt('http://profit.poolparty.biz/profit_thesaurus/2084')
response = graph_search.search(search_filters=search_filter, search_space_id=search_space_id)
self.assertEqual(200, response.status_code)
if __name__ == '__main__':
unittest.main()
| 32.702703 | 101 | 0.780992 |
9029f2d7921ed14be27fe8b3751c41c7bbfcbc54 | 824 | py | Python | Python-Programs/Dynamic Programming/LongestIncreasingSubsequence.py | adityaverma121/Simple-Programs | 8450560b97f89e0fa3da16a623ad35c0b26409c9 | [
"MIT"
] | 71 | 2021-09-30T11:25:12.000Z | 2021-10-03T11:33:22.000Z | Python-Programs/Dynamic Programming/LongestIncreasingSubsequence.py | adityaverma121/Simple-Programs | 8450560b97f89e0fa3da16a623ad35c0b26409c9 | [
"MIT"
] | 186 | 2021-09-30T12:25:16.000Z | 2021-10-03T13:45:04.000Z | Python-Programs/Dynamic Programming/LongestIncreasingSubsequence.py | adityaverma121/Simple-Programs | 8450560b97f89e0fa3da16a623ad35c0b26409c9 | [
"MIT"
] | 385 | 2021-09-30T11:34:23.000Z | 2021-10-03T13:41:00.000Z | # Dynamic programming Python implementation
# of LIS problem
# lis returns length of the longest
# increasing subsequence in arr of size n
def lis(arr):
n = len(arr)
# Declare the list (array) for LIS and
# initialize LIS values for all indexes
lis = [1] * n
# Compute optimized LIS values in bottom up manner
for i in range(1, n):
for j in range(0, i):
if arr[i] > arr[j] and lis[i] < lis[j] + 1:
lis[i] = lis[j] + 1
# Initialize maximum to 0 to get
# the maximum of all LIS
maximum = 0
# Pick maximum of all LIS values
for i in range(n):
maximum = max(maximum, lis[i])
return maximum
# end of lis function
# Driver program to test above function
arr = [10, 22, 9, 33, 21, 50, 41, 60]
print("Length of lis is", lis(arr))
| 22.888889 | 55 | 0.609223 |
c2c1b6e37beab82cdc7f906fd940525d074d88b6 | 5,642 | py | Python | examples/causality/do_granger_causality.py | fboers/jumeg | e04896989faf72f4dbe7adf136e4d158d212f24a | [
"BSD-3-Clause"
] | 6 | 2015-04-10T07:13:07.000Z | 2021-12-12T04:04:37.000Z | examples/causality/do_granger_causality.py | fboers/jumeg | e04896989faf72f4dbe7adf136e4d158d212f24a | [
"BSD-3-Clause"
] | 112 | 2015-01-07T10:19:24.000Z | 2022-02-01T15:48:16.000Z | examples/causality/do_granger_causality.py | fboers/jumeg | e04896989faf72f4dbe7adf136e4d158d212f24a | [
"BSD-3-Clause"
] | 22 | 2015-03-11T12:19:50.000Z | 2021-11-20T04:24:42.000Z | #!/usr/bin/env python3
'''
Perform Granger based causality analysis using Generalized Parital Directed
Coherence on example dataset.
Uses the data and example from mne-python combined with the Scot package
to perform the Granger Causality analysis.
Author: Praveen Sripad <pravsripad@gmail.com>
'''
import numpy as np
from scipy import stats
import mne
from mne.datasets import sample
from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator
from jumeg.jumeg_utils import get_jumeg_path
from jumeg.connectivity.causality import (compute_order, do_mvar_evaluation,
prepare_causality_matrix)
from jumeg.connectivity import (plot_grouped_connectivity_circle,
plot_grouped_causality_circle)
import scot
import scot.connectivity_statistics as scs
from scot.connectivity import connectivity
import yaml
import time
t_start = time.time()
print(('Scot version -', scot.__version__))
yaml_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml'
labels_fname = get_jumeg_path() + '/data/desikan_label_names.yaml'
data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_raw = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
fname_event = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
# Load data
inverse_operator = read_inverse_operator(fname_inv)
raw = mne.io.read_raw_fif(fname_raw)
events = mne.read_events(fname_event)
# Add a bad channel
raw.info['bads'] += ['MEG 2443']
# Pick MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,
exclude='bads')
# Define epochs for left-auditory condition
event_id, tmin, tmax = 1, -0.2, 0.5
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13,
eog=150e-6))
if not epochs.preload:
epochs.load_data()
# parameters, lots of parameters
snr = 1.0
lambda2 = 1.0 / snr ** 2
method = "MNE" # use MNE method (could also be MNE or sLORETA)
stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method,
pick_ori="normal", return_generator=True)
# Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi
labels = mne.read_labels_from_annot('sample', parc='aparc',
subjects_dir=subjects_dir)
label_colors = [label.color for label in labels]
# Average the source estimates within each label using sign-flips to reduce
# signal cancellations, also here we return a generator
src = inverse_operator['src']
label_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip',
return_generator=False)
label_ts_ = np.array(label_ts)
bands = ['alpha']
freqs = [(8, 13)]
gcmethod = 'GPDC'
n_surr = 1 # number of surrogates
surr_thresh = 95 # percentile of surr threshold used
n_jobs = 1
nfft = 512
# normalize the representative ts
print('\nperform normalization using zscoring...')
label_ts = stats.zscore(label_ts_, axis=2)
morder = 15 # set fixed model order
# set this to find the optimal model order using the BIC criterion
# be advised, this takes a long time !!
# morder, bic = compute_order(label_ts, m_max=100) # code provided by Qunxi
# print('the model order based on BIC is..', morder)
# evaluate the chosen model order
print(('\nShape of label_ts -', label_ts.shape))
# mvar needs (trials, channels, samples)
print(('\nRunning for model order - ', morder))
thr_cons, whit_min, whit_max = 0.8, 1., 3.
is_white, consistency, is_stable = do_mvar_evaluation(label_ts, morder,
whit_max, whit_min,
thr_cons)
print(('model_order, whiteness, consistency, stability: %d, %s, %f, %s\n'
% (morder, str(is_white), consistency, str(is_stable))))
# compute the Granger Partial Directed Coherence values
print('computing GPDC connectivity...')
mvar = scot.var.VAR(morder)
# result : array, shape (`repeats`, n_channels, n_channels, nfft)
surr = scs.surrogate_connectivity(gcmethod, label_ts, mvar, nfft=nfft,
n_jobs=n_jobs, repeats=n_surr)
mvar.fit(label_ts)
# mvar coefficients (n_channels, n_channels * model_order)
# mvar covariance matrix (n_channels, n_channels)
# result : array, shape (n_channels, n_channels, `nfft`)
cau = connectivity(gcmethod, mvar.coef, mvar.rescov, nfft=nfft)
# get the band averaged, thresholded connectivity matrix
caus, max_cons, max_surrs = prepare_causality_matrix(
cau, surr, freqs, nfft=nfft,
sfreq=epochs.info['sfreq'], surr_thresh=surr_thresh)
print(('Shape of causality matrix: ', caus.shape))
# read the label names used for plotting
# with open(labels_fname, 'r') as f:
# label_names = pickle.load(f)
with open(labels_fname, 'r') as f:
label_names = yaml.safe_load(f)['label_names']
plot_grouped_causality_circle(caus[0], yaml_fname, label_names, n_lines=10,
labels_mode=None, replacer_dict=None,
out_fname='causality_sample.png',
colormap='Blues', colorbar=True,
arrowstyle='->,head_length=1,head_width=1',
figsize=(10, 6), show=False)
t_end = time.time()
total_time_taken = t_end - t_start
print(('Total time taken in minutes: %f' % (total_time_taken / 60.)))
| 37.118421 | 80 | 0.685395 |
d2cf929aa266f82a0b9618b68aa528a92a7de65c | 48,743 | py | Python | src/bootstrap/bootstrap.py | bdalrhm/rust | cfc856acf3112d241bd4de55ec91df5aef66c352 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 392 | 2019-03-08T14:23:03.000Z | 2021-07-19T16:23:23.000Z | src/bootstrap/bootstrap.py | bdalrhm/rust | cfc856acf3112d241bd4de55ec91df5aef66c352 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 39 | 2019-06-25T11:28:23.000Z | 2021-07-17T07:49:02.000Z | src/bootstrap/bootstrap.py | bdalrhm/rust | cfc856acf3112d241bd4de55ec91df5aef66c352 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 30 | 2019-03-22T15:47:24.000Z | 2021-07-02T08:41:43.000Z | from __future__ import absolute_import, division, print_function
import argparse
import contextlib
import datetime
import distutils.version
import hashlib
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
from time import time
def support_xz():
try:
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_path = temp_file.name
with tarfile.open(temp_path, "w:xz"):
pass
return True
except tarfile.CompressionError:
return False
def get(url, path, verbose=False, do_verify=True):
suffix = '.sha256'
sha_url = url + suffix
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_path = temp_file.name
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as sha_file:
sha_path = sha_file.name
try:
if do_verify:
download(sha_path, sha_url, False, verbose)
if os.path.exists(path):
if verify(path, sha_path, False):
if verbose:
print("using already-download file", path)
return
else:
if verbose:
print("ignoring already-download file",
path, "due to failed verification")
os.unlink(path)
download(temp_path, url, True, verbose)
if do_verify and not verify(temp_path, sha_path, verbose):
raise RuntimeError("failed verification")
if verbose:
print("moving {} to {}".format(temp_path, path))
shutil.move(temp_path, path)
finally:
delete_if_present(sha_path, verbose)
delete_if_present(temp_path, verbose)
def delete_if_present(path, verbose):
"""Remove the given file if present"""
if os.path.isfile(path):
if verbose:
print("removing", path)
os.unlink(path)
def download(path, url, probably_big, verbose):
for _ in range(0, 4):
try:
_download(path, url, probably_big, verbose, True)
return
except RuntimeError:
print("\nspurious failure, trying again")
_download(path, url, probably_big, verbose, False)
def _download(path, url, probably_big, verbose, exception):
if probably_big or verbose:
print("downloading {}".format(url))
# see https://serverfault.com/questions/301128/how-to-download
if sys.platform == 'win32':
run(["PowerShell.exe", "/nologo", "-Command",
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
"(New-Object System.Net.WebClient).DownloadFile('{}', '{}')".format(url, path)],
verbose=verbose,
exception=exception)
else:
if probably_big or verbose:
option = "-#"
else:
option = "-s"
require(["curl", "--version"])
run(["curl", option,
"-y", "30", "-Y", "10", # timeout if speed is < 10 bytes/sec for > 30 seconds
"--connect-timeout", "30", # timeout if cannot connect within 30 seconds
"--retry", "3", "-Sf", "-o", path, url],
verbose=verbose,
exception=exception)
def verify(path, sha_path, verbose):
"""Check if the sha256 sum of the given path is valid"""
if verbose:
print("verifying", path)
with open(path, "rb") as source:
found = hashlib.sha256(source.read()).hexdigest()
with open(sha_path, "r") as sha256sum:
expected = sha256sum.readline().split()[0]
verified = found == expected
if not verified:
print("invalid checksum:\n"
" found: {}\n"
" expected: {}".format(found, expected))
return verified
def unpack(tarball, tarball_suffix, dst, verbose=False, match=None):
"""Unpack the given tarball file"""
print("extracting", tarball)
fname = os.path.basename(tarball).replace(tarball_suffix, "")
with contextlib.closing(tarfile.open(tarball)) as tar:
for member in tar.getnames():
if "/" not in member:
continue
name = member.replace(fname + "/", "", 1)
if match is not None and not name.startswith(match):
continue
name = name[len(match) + 1:]
dst_path = os.path.join(dst, name)
if verbose:
print(" extracting", member)
tar.extract(member, dst)
src_path = os.path.join(dst, member)
if os.path.isdir(src_path) and os.path.exists(dst_path):
continue
shutil.move(src_path, dst_path)
shutil.rmtree(os.path.join(dst, fname))
def run(args, verbose=False, exception=False, is_bootstrap=False, **kwargs):
"""Run a child program in a new process"""
if verbose:
print("running: " + ' '.join(args))
sys.stdout.flush()
# Use Popen here instead of call() as it apparently allows powershell on
# Windows to not lock up waiting for input presumably.
ret = subprocess.Popen(args, **kwargs)
code = ret.wait()
if code != 0:
err = "failed to run: " + ' '.join(args)
if verbose or exception:
raise RuntimeError(err)
# For most failures, we definitely do want to print this error, or the user will have no
# idea what went wrong. But when we've successfully built bootstrap and it failed, it will
# have already printed an error above, so there's no need to print the exact command we're
# running.
if is_bootstrap:
sys.exit(1)
else:
sys.exit(err)
def require(cmd, exit=True):
'''Run a command, returning its output.
On error,
If `exit` is `True`, exit the process.
Otherwise, return None.'''
try:
return subprocess.check_output(cmd).strip()
except (subprocess.CalledProcessError, OSError) as exc:
if not exit:
return None
print("error: unable to run `{}`: {}".format(' '.join(cmd), exc))
print("Please make sure it's installed and in the path.")
sys.exit(1)
def stage0_data(rust_root):
"""Build a dictionary from stage0.txt"""
nightlies = os.path.join(rust_root, "src/stage0.txt")
with open(nightlies, 'r') as nightlies:
lines = [line.rstrip() for line in nightlies
if not line.startswith("#")]
return dict([line.split(": ", 1) for line in lines if line])
def format_build_time(duration):
"""Return a nicer format for build time
>>> format_build_time('300')
'0:05:00'
"""
return str(datetime.timedelta(seconds=int(duration)))
def default_build_triple(verbose):
"""Build triple as in LLVM"""
# If the user already has a host build triple with an existing `rustc`
# install, use their preference. This fixes most issues with Windows builds
# being detected as GNU instead of MSVC.
default_encoding = sys.getdefaultencoding()
try:
version = subprocess.check_output(["rustc", "--version", "--verbose"],
stderr=subprocess.DEVNULL)
version = version.decode(default_encoding)
host = next(x for x in version.split('\n') if x.startswith("host: "))
triple = host.split("host: ")[1]
if verbose:
print("detected default triple {}".format(triple))
return triple
except Exception as e:
if verbose:
print("rustup not detected: {}".format(e))
print("falling back to auto-detect")
required = sys.platform != 'win32'
ostype = require(["uname", "-s"], exit=required)
cputype = require(['uname', '-m'], exit=required)
# If we do not have `uname`, assume Windows.
if ostype is None or cputype is None:
return 'x86_64-pc-windows-msvc'
ostype = ostype.decode(default_encoding)
cputype = cputype.decode(default_encoding)
# The goal here is to come up with the same triple as LLVM would,
# at least for the subset of platforms we're willing to target.
ostype_mapper = {
'Darwin': 'apple-darwin',
'DragonFly': 'unknown-dragonfly',
'FreeBSD': 'unknown-freebsd',
'Haiku': 'unknown-haiku',
'NetBSD': 'unknown-netbsd',
'OpenBSD': 'unknown-openbsd'
}
# Consider the direct transformation first and then the special cases
if ostype in ostype_mapper:
ostype = ostype_mapper[ostype]
elif ostype == 'Linux':
os_from_sp = subprocess.check_output(
['uname', '-o']).strip().decode(default_encoding)
if os_from_sp == 'Android':
ostype = 'linux-android'
else:
ostype = 'unknown-linux-gnu'
elif ostype == 'SunOS':
ostype = 'pc-solaris'
# On Solaris, uname -m will return a machine classification instead
# of a cpu type, so uname -p is recommended instead. However, the
# output from that option is too generic for our purposes (it will
# always emit 'i386' on x86/amd64 systems). As such, isainfo -k
# must be used instead.
cputype = require(['isainfo', '-k']).decode(default_encoding)
# sparc cpus have sun as a target vendor
if 'sparc' in cputype:
ostype = 'sun-solaris'
elif ostype.startswith('MINGW'):
# msys' `uname` does not print gcc configuration, but prints msys
# configuration. so we cannot believe `uname -m`:
# msys1 is always i686 and msys2 is always x86_64.
# instead, msys defines $MSYSTEM which is MINGW32 on i686 and
# MINGW64 on x86_64.
ostype = 'pc-windows-gnu'
cputype = 'i686'
if os.environ.get('MSYSTEM') == 'MINGW64':
cputype = 'x86_64'
elif ostype.startswith('MSYS'):
ostype = 'pc-windows-gnu'
elif ostype.startswith('CYGWIN_NT'):
cputype = 'i686'
if ostype.endswith('WOW64'):
cputype = 'x86_64'
ostype = 'pc-windows-gnu'
elif sys.platform == 'win32':
# Some Windows platforms might have a `uname` command that returns a
# non-standard string (e.g. gnuwin32 tools returns `windows32`). In
# these cases, fall back to using sys.platform.
return 'x86_64-pc-windows-msvc'
else:
err = "unknown OS type: {}".format(ostype)
sys.exit(err)
if cputype == 'powerpc' and ostype == 'unknown-freebsd':
cputype = subprocess.check_output(
['uname', '-p']).strip().decode(default_encoding)
cputype_mapper = {
'BePC': 'i686',
'aarch64': 'aarch64',
'amd64': 'x86_64',
'arm64': 'aarch64',
'i386': 'i686',
'i486': 'i686',
'i686': 'i686',
'i786': 'i686',
'powerpc': 'powerpc',
'powerpc64': 'powerpc64',
'powerpc64le': 'powerpc64le',
'ppc': 'powerpc',
'ppc64': 'powerpc64',
'ppc64le': 'powerpc64le',
's390x': 's390x',
'x64': 'x86_64',
'x86': 'i686',
'x86-64': 'x86_64',
'x86_64': 'x86_64'
}
# Consider the direct transformation first and then the special cases
if cputype in cputype_mapper:
cputype = cputype_mapper[cputype]
elif cputype in {'xscale', 'arm'}:
cputype = 'arm'
if ostype == 'linux-android':
ostype = 'linux-androideabi'
elif ostype == 'unknown-freebsd':
cputype = subprocess.check_output(
['uname', '-p']).strip().decode(default_encoding)
ostype = 'unknown-freebsd'
elif cputype == 'armv6l':
cputype = 'arm'
if ostype == 'linux-android':
ostype = 'linux-androideabi'
else:
ostype += 'eabihf'
elif cputype in {'armv7l', 'armv8l'}:
cputype = 'armv7'
if ostype == 'linux-android':
ostype = 'linux-androideabi'
else:
ostype += 'eabihf'
elif cputype == 'mips':
if sys.byteorder == 'big':
cputype = 'mips'
elif sys.byteorder == 'little':
cputype = 'mipsel'
else:
raise ValueError("unknown byteorder: {}".format(sys.byteorder))
elif cputype == 'mips64':
if sys.byteorder == 'big':
cputype = 'mips64'
elif sys.byteorder == 'little':
cputype = 'mips64el'
else:
raise ValueError('unknown byteorder: {}'.format(sys.byteorder))
# only the n64 ABI is supported, indicate it
ostype += 'abi64'
elif cputype == 'sparc' or cputype == 'sparcv9' or cputype == 'sparc64':
pass
else:
err = "unknown cpu type: {}".format(cputype)
sys.exit(err)
return "{}-{}".format(cputype, ostype)
@contextlib.contextmanager
def output(filepath):
tmp = filepath + '.tmp'
with open(tmp, 'w') as f:
yield f
try:
if os.path.exists(filepath):
os.remove(filepath) # PermissionError/OSError on Win32 if in use
except OSError:
shutil.copy2(tmp, filepath)
os.remove(tmp)
return
os.rename(tmp, filepath)
class RustBuild(object):
"""Provide all the methods required to build Rust"""
def __init__(self):
self.date = ''
self._download_url = ''
self.rustc_channel = ''
self.rustfmt_channel = ''
self.build = ''
self.build_dir = ''
self.clean = False
self.config_toml = ''
self.rust_root = ''
self.use_locked_deps = ''
self.use_vendored_sources = ''
self.verbose = False
self.git_version = None
self.nix_deps_dir = None
self.rustc_commit = None
def download_toolchain(self, stage0=True, rustc_channel=None):
"""Fetch the build system for Rust, written in Rust
This method will build a cache directory, then it will fetch the
tarball which has the stage0 compiler used to then bootstrap the Rust
compiler itself.
Each downloaded tarball is extracted, after that, the script
will move all the content to the right place.
"""
if rustc_channel is None:
rustc_channel = self.rustc_channel
rustfmt_channel = self.rustfmt_channel
bin_root = self.bin_root(stage0)
key = self.date
if not stage0:
key += str(self.rustc_commit)
if self.rustc(stage0).startswith(bin_root) and \
(not os.path.exists(self.rustc(stage0)) or
self.program_out_of_date(self.rustc_stamp(stage0), key)):
if os.path.exists(bin_root):
shutil.rmtree(bin_root)
tarball_suffix = '.tar.xz' if support_xz() else '.tar.gz'
filename = "rust-std-{}-{}{}".format(
rustc_channel, self.build, tarball_suffix)
pattern = "rust-std-{}".format(self.build)
self._download_component_helper(filename, pattern, tarball_suffix, stage0)
filename = "rustc-{}-{}{}".format(rustc_channel, self.build,
tarball_suffix)
self._download_component_helper(filename, "rustc", tarball_suffix, stage0)
# download-rustc doesn't need its own cargo, it can just use beta's.
if stage0:
filename = "cargo-{}-{}{}".format(rustc_channel, self.build,
tarball_suffix)
self._download_component_helper(filename, "cargo", tarball_suffix)
self.fix_bin_or_dylib("{}/bin/cargo".format(bin_root))
else:
filename = "rustc-dev-{}-{}{}".format(rustc_channel, self.build, tarball_suffix)
self._download_component_helper(
filename, "rustc-dev", tarball_suffix, stage0
)
self.fix_bin_or_dylib("{}/bin/rustc".format(bin_root))
self.fix_bin_or_dylib("{}/bin/rustdoc".format(bin_root))
lib_dir = "{}/lib".format(bin_root)
for lib in os.listdir(lib_dir):
if lib.endswith(".so"):
self.fix_bin_or_dylib(os.path.join(lib_dir, lib))
with output(self.rustc_stamp(stage0)) as rust_stamp:
rust_stamp.write(key)
if self.rustfmt() and self.rustfmt().startswith(bin_root) and (
not os.path.exists(self.rustfmt())
or self.program_out_of_date(self.rustfmt_stamp(), self.rustfmt_channel)
):
if rustfmt_channel:
tarball_suffix = '.tar.xz' if support_xz() else '.tar.gz'
[channel, date] = rustfmt_channel.split('-', 1)
filename = "rustfmt-{}-{}{}".format(channel, self.build, tarball_suffix)
self._download_component_helper(
filename, "rustfmt-preview", tarball_suffix, key=date
)
self.fix_bin_or_dylib("{}/bin/rustfmt".format(bin_root))
self.fix_bin_or_dylib("{}/bin/cargo-fmt".format(bin_root))
with output(self.rustfmt_stamp()) as rustfmt_stamp:
rustfmt_stamp.write(self.rustfmt_channel)
# Avoid downloading LLVM twice (once for stage0 and once for the master rustc)
if self.downloading_llvm() and stage0:
# We want the most recent LLVM submodule update to avoid downloading
# LLVM more often than necessary.
#
# This git command finds that commit SHA, looking for bors-authored
# merges that modified src/llvm-project.
#
# This works even in a repository that has not yet initialized
# submodules.
top_level = subprocess.check_output([
"git", "rev-parse", "--show-toplevel",
]).decode(sys.getdefaultencoding()).strip()
llvm_sha = subprocess.check_output([
"git", "log", "--author=bors", "--format=%H", "-n1",
"-m", "--first-parent",
"--",
"{}/src/llvm-project".format(top_level),
"{}/src/bootstrap/download-ci-llvm-stamp".format(top_level),
# the LLVM shared object file is named `LLVM-12-rust-{version}-nightly`
"{}/src/version".format(top_level)
]).decode(sys.getdefaultencoding()).strip()
llvm_assertions = self.get_toml('assertions', 'llvm') == 'true'
llvm_root = self.llvm_root()
llvm_lib = os.path.join(llvm_root, "lib")
if self.program_out_of_date(self.llvm_stamp(), llvm_sha + str(llvm_assertions)):
self._download_ci_llvm(llvm_sha, llvm_assertions)
for binary in ["llvm-config", "FileCheck"]:
self.fix_bin_or_dylib(os.path.join(llvm_root, "bin", binary))
for lib in os.listdir(llvm_lib):
if lib.endswith(".so"):
self.fix_bin_or_dylib(os.path.join(llvm_lib, lib))
with output(self.llvm_stamp()) as llvm_stamp:
llvm_stamp.write(llvm_sha + str(llvm_assertions))
def downloading_llvm(self):
opt = self.get_toml('download-ci-llvm', 'llvm')
# This is currently all tier 1 targets (since others may not have CI
# artifacts)
# https://doc.rust-lang.org/rustc/platform-support.html#tier-1
supported_platforms = [
"aarch64-unknown-linux-gnu",
"i686-pc-windows-gnu",
"i686-pc-windows-msvc",
"i686-unknown-linux-gnu",
"x86_64-unknown-linux-gnu",
"x86_64-apple-darwin",
"x86_64-pc-windows-gnu",
"x86_64-pc-windows-msvc",
]
return opt == "true" \
or (opt == "if-available" and self.build in supported_platforms)
def _download_component_helper(
self, filename, pattern, tarball_suffix, stage0=True, key=None
):
if key is None:
if stage0:
key = self.date
else:
key = self.rustc_commit
cache_dst = os.path.join(self.build_dir, "cache")
rustc_cache = os.path.join(cache_dst, key)
if not os.path.exists(rustc_cache):
os.makedirs(rustc_cache)
if stage0:
url = "{}/dist/{}".format(self._download_url, key)
else:
url = "https://ci-artifacts.rust-lang.org/rustc-builds/{}".format(self.rustc_commit)
tarball = os.path.join(rustc_cache, filename)
if not os.path.exists(tarball):
get("{}/{}".format(url, filename), tarball, verbose=self.verbose, do_verify=stage0)
unpack(tarball, tarball_suffix, self.bin_root(stage0), match=pattern, verbose=self.verbose)
def _download_ci_llvm(self, llvm_sha, llvm_assertions):
cache_prefix = "llvm-{}-{}".format(llvm_sha, llvm_assertions)
cache_dst = os.path.join(self.build_dir, "cache")
rustc_cache = os.path.join(cache_dst, cache_prefix)
if not os.path.exists(rustc_cache):
os.makedirs(rustc_cache)
url = "https://ci-artifacts.rust-lang.org/rustc-builds/{}".format(llvm_sha)
if llvm_assertions:
url = url.replace('rustc-builds', 'rustc-builds-alt')
# ci-artifacts are only stored as .xz, not .gz
if not support_xz():
print("error: XZ support is required to download LLVM")
print("help: consider disabling `download-ci-llvm` or using python3")
exit(1)
tarball_suffix = '.tar.xz'
filename = "rust-dev-nightly-" + self.build + tarball_suffix
tarball = os.path.join(rustc_cache, filename)
if not os.path.exists(tarball):
get("{}/{}".format(url, filename), tarball, verbose=self.verbose, do_verify=False)
unpack(tarball, tarball_suffix, self.llvm_root(),
match="rust-dev",
verbose=self.verbose)
def fix_bin_or_dylib(self, fname):
"""Modifies the interpreter section of 'fname' to fix the dynamic linker,
or the RPATH section, to fix the dynamic library search path
This method is only required on NixOS and uses the PatchELF utility to
change the interpreter/RPATH of ELF executables.
Please see https://nixos.org/patchelf.html for more information
"""
default_encoding = sys.getdefaultencoding()
try:
ostype = subprocess.check_output(
['uname', '-s']).strip().decode(default_encoding)
except subprocess.CalledProcessError:
return
except OSError as reason:
if getattr(reason, 'winerror', None) is not None:
return
raise reason
if ostype != "Linux":
return
# Use `/etc/os-release` instead of `/etc/NIXOS`.
# The latter one does not exist on NixOS when using tmpfs as root.
try:
with open("/etc/os-release", "r") as f:
if not any(line.strip() == "ID=nixos" for line in f):
return
except FileNotFoundError:
return
if os.path.exists("/lib"):
return
# At this point we're pretty sure the user is running NixOS
nix_os_msg = "info: you seem to be running NixOS. Attempting to patch"
print(nix_os_msg, fname)
# Only build `.nix-deps` once.
nix_deps_dir = self.nix_deps_dir
if not nix_deps_dir:
# Run `nix-build` to "build" each dependency (which will likely reuse
# the existing `/nix/store` copy, or at most download a pre-built copy).
#
# Importantly, we create a gc-root called `.nix-deps` in the `build/`
# directory, but still reference the actual `/nix/store` path in the rpath
# as it makes it significantly more robust against changes to the location of
# the `.nix-deps` location.
#
# bintools: Needed for the path of `ld-linux.so` (via `nix-support/dynamic-linker`).
# zlib: Needed as a system dependency of `libLLVM-*.so`.
# patchelf: Needed for patching ELF binaries (see doc comment above).
nix_deps_dir = "{}/{}".format(self.build_dir, ".nix-deps")
nix_expr = '''
with (import <nixpkgs> {});
symlinkJoin {
name = "rust-stage0-dependencies";
paths = [
zlib
patchelf
stdenv.cc.bintools
];
}
'''
try:
subprocess.check_output([
"nix-build", "-E", nix_expr, "-o", nix_deps_dir,
])
except subprocess.CalledProcessError as reason:
print("warning: failed to call nix-build:", reason)
return
self.nix_deps_dir = nix_deps_dir
patchelf = "{}/bin/patchelf".format(nix_deps_dir)
rpath_entries = [
# Relative default, all binary and dynamic libraries we ship
# appear to have this (even when `../lib` is redundant).
"$ORIGIN/../lib",
os.path.join(os.path.realpath(nix_deps_dir), "lib")
]
patchelf_args = ["--set-rpath", ":".join(rpath_entries)]
if not fname.endswith(".so"):
# Finally, set the corret .interp for binaries
with open("{}/nix-support/dynamic-linker".format(nix_deps_dir)) as dynamic_linker:
patchelf_args += ["--set-interpreter", dynamic_linker.read().rstrip()]
try:
subprocess.check_output([patchelf] + patchelf_args + [fname])
except subprocess.CalledProcessError as reason:
print("warning: failed to call patchelf:", reason)
return
# If `download-rustc` is set, download the most recent commit with CI artifacts
def maybe_download_ci_toolchain(self):
# If `download-rustc` is not set, default to rebuilding.
download_rustc = self.get_toml("download-rustc", section="rust")
if download_rustc is None or download_rustc == "false":
return None
assert download_rustc == "true" or download_rustc == "if-unchanged", download_rustc
# Handle running from a directory other than the top level
rev_parse = ["git", "rev-parse", "--show-toplevel"]
top_level = subprocess.check_output(rev_parse, universal_newlines=True).strip()
compiler = "{}/compiler/".format(top_level)
library = "{}/library/".format(top_level)
# Look for a version to compare to based on the current commit.
# Only commits merged by bors will have CI artifacts.
merge_base = ["git", "log", "--author=bors", "--pretty=%H", "-n1"]
commit = subprocess.check_output(merge_base, universal_newlines=True).strip()
# Warn if there were changes to the compiler or standard library since the ancestor commit.
status = subprocess.call(["git", "diff-index", "--quiet", commit, "--", compiler, library])
if status != 0:
if download_rustc == "if-unchanged":
return None
print("warning: `download-rustc` is enabled, but there are changes to \
compiler/ or library/")
if self.verbose:
print("using downloaded stage1 artifacts from CI (commit {})".format(commit))
self.rustc_commit = commit
# FIXME: support downloading artifacts from the beta channel
self.download_toolchain(False, "nightly")
def rustc_stamp(self, stage0):
"""Return the path for .rustc-stamp at the given stage
>>> rb = RustBuild()
>>> rb.build_dir = "build"
>>> rb.rustc_stamp(True) == os.path.join("build", "stage0", ".rustc-stamp")
True
>>> rb.rustc_stamp(False) == os.path.join("build", "ci-rustc", ".rustc-stamp")
True
"""
return os.path.join(self.bin_root(stage0), '.rustc-stamp')
def rustfmt_stamp(self):
"""Return the path for .rustfmt-stamp
>>> rb = RustBuild()
>>> rb.build_dir = "build"
>>> rb.rustfmt_stamp() == os.path.join("build", "stage0", ".rustfmt-stamp")
True
"""
return os.path.join(self.bin_root(True), '.rustfmt-stamp')
def llvm_stamp(self):
"""Return the path for .rustfmt-stamp
>>> rb = RustBuild()
>>> rb.build_dir = "build"
>>> rb.llvm_stamp() == os.path.join("build", "ci-llvm", ".llvm-stamp")
True
"""
return os.path.join(self.llvm_root(), '.llvm-stamp')
def program_out_of_date(self, stamp_path, key):
"""Check if the given program stamp is out of date"""
if not os.path.exists(stamp_path) or self.clean:
return True
with open(stamp_path, 'r') as stamp:
return key != stamp.read()
def bin_root(self, stage0):
"""Return the binary root directory for the given stage
>>> rb = RustBuild()
>>> rb.build_dir = "build"
>>> rb.bin_root(True) == os.path.join("build", "stage0")
True
>>> rb.bin_root(False) == os.path.join("build", "ci-rustc")
True
When the 'build' property is given should be a nested directory:
>>> rb.build = "devel"
>>> rb.bin_root(True) == os.path.join("build", "devel", "stage0")
True
"""
if stage0:
subdir = "stage0"
else:
subdir = "ci-rustc"
return os.path.join(self.build_dir, self.build, subdir)
def llvm_root(self):
"""Return the CI LLVM root directory
>>> rb = RustBuild()
>>> rb.build_dir = "build"
>>> rb.llvm_root() == os.path.join("build", "ci-llvm")
True
When the 'build' property is given should be a nested directory:
>>> rb.build = "devel"
>>> rb.llvm_root() == os.path.join("build", "devel", "ci-llvm")
True
"""
return os.path.join(self.build_dir, self.build, "ci-llvm")
def get_toml(self, key, section=None):
"""Returns the value of the given key in config.toml, otherwise returns None
>>> rb = RustBuild()
>>> rb.config_toml = 'key1 = "value1"\\nkey2 = "value2"'
>>> rb.get_toml("key2")
'value2'
If the key does not exists, the result is None:
>>> rb.get_toml("key3") is None
True
Optionally also matches the section the key appears in
>>> rb.config_toml = '[a]\\nkey = "value1"\\n[b]\\nkey = "value2"'
>>> rb.get_toml('key', 'a')
'value1'
>>> rb.get_toml('key', 'b')
'value2'
>>> rb.get_toml('key', 'c') is None
True
>>> rb.config_toml = 'key1 = true'
>>> rb.get_toml("key1")
'true'
"""
cur_section = None
for line in self.config_toml.splitlines():
section_match = re.match(r'^\s*\[(.*)\]\s*$', line)
if section_match is not None:
cur_section = section_match.group(1)
match = re.match(r'^{}\s*=(.*)$'.format(key), line)
if match is not None:
value = match.group(1)
if section is None or section == cur_section:
return self.get_string(value) or value.strip()
return None
def cargo(self):
"""Return config path for cargo"""
return self.program_config('cargo')
def rustc(self, stage0):
"""Return config path for rustc"""
return self.program_config('rustc', stage0)
def rustfmt(self):
"""Return config path for rustfmt"""
if not self.rustfmt_channel:
return None
return self.program_config('rustfmt')
def program_config(self, program, stage0=True):
"""Return config path for the given program at the given stage
>>> rb = RustBuild()
>>> rb.config_toml = 'rustc = "rustc"\\n'
>>> rb.program_config('rustc')
'rustc'
>>> rb.config_toml = ''
>>> cargo_path = rb.program_config('cargo', True)
>>> cargo_path.rstrip(".exe") == os.path.join(rb.bin_root(True),
... "bin", "cargo")
True
>>> cargo_path = rb.program_config('cargo', False)
>>> cargo_path.rstrip(".exe") == os.path.join(rb.bin_root(False),
... "bin", "cargo")
True
"""
config = self.get_toml(program)
if config:
return os.path.expanduser(config)
return os.path.join(self.bin_root(stage0), "bin", "{}{}".format(
program, self.exe_suffix()))
@staticmethod
def get_string(line):
"""Return the value between double quotes
>>> RustBuild.get_string(' "devel" ')
'devel'
>>> RustBuild.get_string(" 'devel' ")
'devel'
>>> RustBuild.get_string('devel') is None
True
>>> RustBuild.get_string(' "devel ')
''
"""
start = line.find('"')
if start != -1:
end = start + 1 + line[start + 1:].find('"')
return line[start + 1:end]
start = line.find('\'')
if start != -1:
end = start + 1 + line[start + 1:].find('\'')
return line[start + 1:end]
return None
@staticmethod
def exe_suffix():
"""Return a suffix for executables"""
if sys.platform == 'win32':
return '.exe'
return ''
def bootstrap_binary(self):
"""Return the path of the bootstrap binary
>>> rb = RustBuild()
>>> rb.build_dir = "build"
>>> rb.bootstrap_binary() == os.path.join("build", "bootstrap",
... "debug", "bootstrap")
True
"""
return os.path.join(self.build_dir, "bootstrap", "debug", "bootstrap")
def build_bootstrap(self):
"""Build bootstrap"""
build_dir = os.path.join(self.build_dir, "bootstrap")
if self.clean and os.path.exists(build_dir):
shutil.rmtree(build_dir)
env = os.environ.copy()
# `CARGO_BUILD_TARGET` breaks bootstrap build.
# See also: <https://github.com/rust-lang/rust/issues/70208>.
if "CARGO_BUILD_TARGET" in env:
del env["CARGO_BUILD_TARGET"]
env["CARGO_TARGET_DIR"] = build_dir
env["RUSTC"] = self.rustc(True)
env["LD_LIBRARY_PATH"] = os.path.join(self.bin_root(True), "lib") + \
(os.pathsep + env["LD_LIBRARY_PATH"]) \
if "LD_LIBRARY_PATH" in env else ""
env["DYLD_LIBRARY_PATH"] = os.path.join(self.bin_root(True), "lib") + \
(os.pathsep + env["DYLD_LIBRARY_PATH"]) \
if "DYLD_LIBRARY_PATH" in env else ""
env["LIBRARY_PATH"] = os.path.join(self.bin_root(True), "lib") + \
(os.pathsep + env["LIBRARY_PATH"]) \
if "LIBRARY_PATH" in env else ""
# preserve existing RUSTFLAGS
env.setdefault("RUSTFLAGS", "")
env["RUSTFLAGS"] += " -Cdebuginfo=2"
build_section = "target.{}".format(self.build)
target_features = []
if self.get_toml("crt-static", build_section) == "true":
target_features += ["+crt-static"]
elif self.get_toml("crt-static", build_section) == "false":
target_features += ["-crt-static"]
if target_features:
env["RUSTFLAGS"] += " -C target-feature=" + (",".join(target_features))
target_linker = self.get_toml("linker", build_section)
if target_linker is not None:
env["RUSTFLAGS"] += " -C linker=" + target_linker
env["RUSTFLAGS"] += " -Wrust_2018_idioms -Wunused_lifetimes"
env["RUSTFLAGS"] += " -Wsemicolon_in_expressions_from_macros"
if self.get_toml("deny-warnings", "rust") != "false":
env["RUSTFLAGS"] += " -Dwarnings"
env["PATH"] = os.path.join(self.bin_root(True), "bin") + \
os.pathsep + env["PATH"]
if not os.path.isfile(self.cargo()):
raise Exception("no cargo executable found at `{}`".format(
self.cargo()))
args = [self.cargo(), "build", "--manifest-path",
os.path.join(self.rust_root, "src/bootstrap/Cargo.toml")]
for _ in range(1, self.verbose):
args.append("--verbose")
if self.use_locked_deps:
args.append("--locked")
if self.use_vendored_sources:
args.append("--frozen")
run(args, env=env, verbose=self.verbose)
def build_triple(self):
"""Build triple as in LLVM
Note that `default_build_triple` is moderately expensive,
so use `self.build` where possible.
"""
config = self.get_toml('build')
if config:
return config
return default_build_triple(self.verbose)
def check_submodule(self, module, slow_submodules):
if not slow_submodules:
checked_out = subprocess.Popen(["git", "rev-parse", "HEAD"],
cwd=os.path.join(self.rust_root, module),
stdout=subprocess.PIPE)
return checked_out
else:
return None
def update_submodule(self, module, checked_out, recorded_submodules):
module_path = os.path.join(self.rust_root, module)
if checked_out is not None:
default_encoding = sys.getdefaultencoding()
checked_out = checked_out.communicate()[0].decode(default_encoding).strip()
if recorded_submodules[module] == checked_out:
return
print("Updating submodule", module)
run(["git", "submodule", "-q", "sync", module],
cwd=self.rust_root, verbose=self.verbose)
update_args = ["git", "submodule", "update", "--init", "--recursive"]
if self.git_version >= distutils.version.LooseVersion("2.11.0"):
update_args.append("--progress")
update_args.append(module)
run(update_args, cwd=self.rust_root, verbose=self.verbose, exception=True)
run(["git", "reset", "-q", "--hard"],
cwd=module_path, verbose=self.verbose)
run(["git", "clean", "-qdfx"],
cwd=module_path, verbose=self.verbose)
def update_submodules(self):
"""Update submodules"""
if (not os.path.exists(os.path.join(self.rust_root, ".git"))) or \
self.get_toml('submodules') == "false":
return
default_encoding = sys.getdefaultencoding()
# check the existence and version of 'git' command
git_version_str = require(['git', '--version']).split()[2].decode(default_encoding)
self.git_version = distutils.version.LooseVersion(git_version_str)
slow_submodules = self.get_toml('fast-submodules') == "false"
start_time = time()
if slow_submodules:
print('Unconditionally updating submodules')
else:
print('Updating only changed submodules')
default_encoding = sys.getdefaultencoding()
# Only update submodules that are needed to build bootstrap. These are needed because Cargo
# currently requires everything in a workspace to be "locally present" when starting a
# build, and will give a hard error if any Cargo.toml files are missing.
# FIXME: Is there a way to avoid cloning these eagerly? Bootstrap itself doesn't need to
# share a workspace with any tools - maybe it could be excluded from the workspace?
# That will still require cloning the submodules the second you check the standard
# library, though...
# FIXME: Is there a way to avoid hard-coding the submodules required?
# WARNING: keep this in sync with the submodules hard-coded in bootstrap/lib.rs
submodules = [
"src/tools/rust-installer",
"src/tools/cargo",
"src/tools/rls",
"src/tools/miri",
"library/backtrace",
"library/stdarch"
]
filtered_submodules = []
submodules_names = []
for module in submodules:
check = self.check_submodule(module, slow_submodules)
filtered_submodules.append((module, check))
submodules_names.append(module)
recorded = subprocess.Popen(["git", "ls-tree", "HEAD"] + submodules_names,
cwd=self.rust_root, stdout=subprocess.PIPE)
recorded = recorded.communicate()[0].decode(default_encoding).strip().splitlines()
# { filename: hash }
recorded_submodules = {}
for data in recorded:
# [mode, kind, hash, filename]
data = data.split()
recorded_submodules[data[3]] = data[2]
for module in filtered_submodules:
self.update_submodule(module[0], module[1], recorded_submodules)
print("Submodules updated in %.2f seconds" % (time() - start_time))
def set_normal_environment(self):
"""Set download URL for normal environment"""
if 'RUSTUP_DIST_SERVER' in os.environ:
self._download_url = os.environ['RUSTUP_DIST_SERVER']
else:
self._download_url = 'https://static.rust-lang.org'
def set_dev_environment(self):
"""Set download URL for development environment"""
if 'RUSTUP_DEV_DIST_SERVER' in os.environ:
self._download_url = os.environ['RUSTUP_DEV_DIST_SERVER']
else:
self._download_url = 'https://dev-static.rust-lang.org'
def check_vendored_status(self):
"""Check that vendoring is configured properly"""
vendor_dir = os.path.join(self.rust_root, 'vendor')
if 'SUDO_USER' in os.environ and not self.use_vendored_sources:
if os.environ.get('USER') != os.environ['SUDO_USER']:
self.use_vendored_sources = True
print('info: looks like you are running this command under `sudo`')
print(' and so in order to preserve your $HOME this will now')
print(' use vendored sources by default.')
if not os.path.exists(vendor_dir):
print('error: vendoring required, but vendor directory does not exist.')
print(' Run `cargo vendor` without sudo to initialize the '
'vendor directory.')
raise Exception("{} not found".format(vendor_dir))
if self.use_vendored_sources:
if not os.path.exists('.cargo'):
os.makedirs('.cargo')
with output('.cargo/config') as cargo_config:
cargo_config.write(
"[source.crates-io]\n"
"replace-with = 'vendored-sources'\n"
"registry = 'https://example.com'\n"
"\n"
"[source.vendored-sources]\n"
"directory = '{}/vendor'\n"
.format(self.rust_root))
else:
if os.path.exists('.cargo'):
shutil.rmtree('.cargo')
def ensure_vendored(self):
"""Ensure that the vendored sources are available if needed"""
vendor_dir = os.path.join(self.rust_root, 'vendor')
# Note that this does not handle updating the vendored dependencies if
# the rust git repository is updated. Normal development usually does
# not use vendoring, so hopefully this isn't too much of a problem.
if self.use_vendored_sources and not os.path.exists(vendor_dir):
run([
self.cargo(),
"vendor",
"--sync=./src/tools/rust-analyzer/Cargo.toml",
"--sync=./compiler/rustc_codegen_cranelift/Cargo.toml",
], verbose=self.verbose, cwd=self.rust_root)
def bootstrap(help_triggered):
"""Configure, fetch, build and run the initial bootstrap"""
# If the user is asking for help, let them know that the whole download-and-build
# process has to happen before anything is printed out.
if help_triggered:
print("info: Downloading and building bootstrap before processing --help")
print(" command. See src/bootstrap/README.md for help with common")
print(" commands.")
parser = argparse.ArgumentParser(description='Build rust')
parser.add_argument('--config')
parser.add_argument('--build')
parser.add_argument('--clean', action='store_true')
parser.add_argument('-v', '--verbose', action='count', default=0)
args = [a for a in sys.argv if a != '-h' and a != '--help']
args, _ = parser.parse_known_args(args)
# Configure initial bootstrap
build = RustBuild()
build.rust_root = os.path.abspath(os.path.join(__file__, '../../..'))
build.verbose = args.verbose
build.clean = args.clean
# Read from `RUST_BOOTSTRAP_CONFIG`, then `--config`, then fallback to `config.toml` (if it
# exists).
toml_path = os.getenv('RUST_BOOTSTRAP_CONFIG') or args.config
if not toml_path and os.path.exists('config.toml'):
toml_path = 'config.toml'
if toml_path:
if not os.path.exists(toml_path):
toml_path = os.path.join(build.rust_root, toml_path)
with open(toml_path) as config:
build.config_toml = config.read()
profile = build.get_toml('profile')
if profile is not None:
include_file = 'config.{}.toml'.format(profile)
include_dir = os.path.join(build.rust_root, 'src', 'bootstrap', 'defaults')
include_path = os.path.join(include_dir, include_file)
# HACK: This works because `build.get_toml()` returns the first match it finds for a
# specific key, so appending our defaults at the end allows the user to override them
with open(include_path) as included_toml:
build.config_toml += os.linesep + included_toml.read()
config_verbose = build.get_toml('verbose', 'build')
if config_verbose is not None:
build.verbose = max(build.verbose, int(config_verbose))
build.use_vendored_sources = build.get_toml('vendor', 'build') == 'true'
build.use_locked_deps = build.get_toml('locked-deps', 'build') == 'true'
build.check_vendored_status()
build_dir = build.get_toml('build-dir', 'build') or 'build'
build.build_dir = os.path.abspath(build_dir.replace("$ROOT", build.rust_root))
data = stage0_data(build.rust_root)
build.date = data['date']
build.rustc_channel = data['rustc']
if "rustfmt" in data:
build.rustfmt_channel = data['rustfmt']
if 'dev' in data:
build.set_dev_environment()
else:
build.set_normal_environment()
build.build = args.build or build.build_triple()
build.update_submodules()
# Fetch/build the bootstrap
build.download_toolchain()
# Download the master compiler if `download-rustc` is set
build.maybe_download_ci_toolchain()
sys.stdout.flush()
build.ensure_vendored()
build.build_bootstrap()
sys.stdout.flush()
# Run the bootstrap
args = [build.bootstrap_binary()]
args.extend(sys.argv[1:])
env = os.environ.copy()
env["BOOTSTRAP_PARENT_ID"] = str(os.getpid())
env["BOOTSTRAP_PYTHON"] = sys.executable
env["BUILD_DIR"] = build.build_dir
env["RUSTC_BOOTSTRAP"] = '1'
if toml_path:
env["BOOTSTRAP_CONFIG"] = toml_path
if build.rustc_commit is not None:
env["BOOTSTRAP_DOWNLOAD_RUSTC"] = '1'
run(args, env=env, verbose=build.verbose, is_bootstrap=True)
def main():
"""Entry point for the bootstrap process"""
start_time = time()
# x.py help <cmd> ...
if len(sys.argv) > 1 and sys.argv[1] == 'help':
sys.argv = [sys.argv[0], '-h'] + sys.argv[2:]
help_triggered = (
'-h' in sys.argv) or ('--help' in sys.argv) or (len(sys.argv) == 1)
try:
bootstrap(help_triggered)
if not help_triggered:
print("Build completed successfully in {}".format(
format_build_time(time() - start_time)))
except (SystemExit, KeyboardInterrupt) as error:
if hasattr(error, 'code') and isinstance(error.code, int):
exit_code = error.code
else:
exit_code = 1
print(error)
if not help_triggered:
print("Build completed unsuccessfully in {}".format(
format_build_time(time() - start_time)))
sys.exit(exit_code)
if __name__ == '__main__':
main()
| 39.725346 | 100 | 0.58431 |
8a9d2c307302a06e803687d4036a23c66346ed11 | 2,336 | py | Python | scripts/tcpperf_plot.py | ptallada/pysparkling | f0e8e8d039f3313c2693b7c7576cb1b7ba5a6d78 | [
"Apache-2.0"
] | 260 | 2015-05-11T18:08:44.000Z | 2022-01-15T13:19:43.000Z | scripts/tcpperf_plot.py | ptallada/pysparkling | f0e8e8d039f3313c2693b7c7576cb1b7ba5a6d78 | [
"Apache-2.0"
] | 79 | 2015-06-02T09:53:25.000Z | 2021-09-26T11:18:18.000Z | scripts/tcpperf_plot.py | ptallada/pysparkling | f0e8e8d039f3313c2693b7c7576cb1b7ba5a6d78 | [
"Apache-2.0"
] | 50 | 2015-06-06T17:00:58.000Z | 2022-01-15T13:19:18.000Z | from collections import namedtuple
import csv
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
class Plot:
def __init__(self, filename, x_label=None, y_label=None):
self.filename = filename
self.x_label = x_label or 'connections per second'
self.y_label = y_label or 'processed messages per second'
self.record = None
self.data = list(self.read())
self.frame()
def read(self):
with open(self.filename, 'r') as f:
reader = csv.reader(f)
try:
first_line = next(reader)
except StopIteration:
return
self.record = namedtuple('record', [k.strip().replace('# ', '')
for k in first_line])
for row_raw in reader:
row = self.record._make([int(v) for v in row_raw])
yield row
def frame(self):
fig, ax = plt.subplots()
x = [row.messages for row in self.data]
y = [row.hello for row in self.data]
# add some text for labels, title and axes ticks
ax.set_xlabel(self.x_label)
ax.set_ylabel(self.y_label)
# ax.set_xticks(x)
ax.set_xlim(-300, max(x) + 300)
ax.set_ylim(-300, max(y) + 2000)
fig.tight_layout()
self.fig, self.ax = fig, ax
return self
def plot(self):
x = [row.messages for row in self.data]
ideal, = self.ax.plot([0.0, max(x)], [0.0, max(x)], label='ideal',
color='black', linestyle='--', linewidth=1)
graphs = [
self.ax.plot(x, [getattr(row, k) for row in self.data], label=k)
for k in self.record._fields if k != 'messages'
]
self.ax.legend(
handles=[ideal] + [g for g, in graphs],
loc='upper left',
)
return self
def show(self):
plt.show()
return self
def save(self):
self.fig.savefig(self.filename + '.pdf')
self.fig.savefig(self.filename + '.png', dpi=300)
return self
if __name__ == '__main__':
Plot('tests/tcpperf_connections.csv').plot().save()
(Plot('tests/tcpperf_messages.csv',
x_label='inbound messages per second')
.plot()
.save())
| 27.482353 | 76 | 0.540668 |
8173170d87eff572399a72044753d173ac3e84af | 884 | py | Python | workbook_logging.py | intrepiduiuc/cs-205 | abe87c37b5cc2d061640f90916511d477426bc9e | [
"MIT"
] | null | null | null | workbook_logging.py | intrepiduiuc/cs-205 | abe87c37b5cc2d061640f90916511d477426bc9e | [
"MIT"
] | null | null | null | workbook_logging.py | intrepiduiuc/cs-205 | abe87c37b5cc2d061640f90916511d477426bc9e | [
"MIT"
] | null | null | null | # Based off of code from:
# http://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output
import logging
logging.basicConfig(level=logging.INFO)
def add_coloring_to_emit_ansi(fn):
# add methods we need to the class
def new(*args):
levelno = args[1].levelno
if(levelno>=50):
color = '\x1b[31m' # red
elif(levelno>=40):
color = '\x1b[31m' # red
elif(levelno>=30):
color = '\x1b[33m' # yellow
elif(levelno>=20):
color = '\x1b[32m' # green
elif(levelno>=10):
color = '\x1b[35m' # pink
else:
color = '\x1b[0m' # normal
args[1].msg = color + args[1].msg + '\x1b[0m' # normal
#print "after"
return fn(*args)
return new
logging.StreamHandler.emit = add_coloring_to_emit_ansi(logging.StreamHandler.emit)
| 30.482759 | 83 | 0.578054 |
e98958b6b760439f9afafbb3f6090de58c8f0ecb | 4,664 | py | Python | src/dispatch/individual/service.py | stefanm8/dispatch | a7fe52f870a5deec8a161ca7395ca869aaf8f2c9 | [
"Apache-2.0"
] | 2 | 2020-03-24T13:37:41.000Z | 2020-04-11T04:00:43.000Z | src/dispatch/individual/service.py | stefanm8/dispatch | a7fe52f870a5deec8a161ca7395ca869aaf8f2c9 | [
"Apache-2.0"
] | null | null | null | src/dispatch/individual/service.py | stefanm8/dispatch | a7fe52f870a5deec8a161ca7395ca869aaf8f2c9 | [
"Apache-2.0"
] | null | null | null | from typing import List, Optional
from dispatch.database.core import SessionLocal
from dispatch.incident.models import Incident
from dispatch.plugin import service as plugin_service
from dispatch.project import service as project_service
from dispatch.search_filter import service as search_filter_service
from .models import IndividualContact, IndividualContactCreate, IndividualContactUpdate
def resolve_user_by_email(email, db_session: SessionLocal):
"""Resolves a user's details given their email."""
plugin = plugin_service.get_active_instance(db_session=db_session, plugin_type="contact")
return plugin.instance.get(email)
def get(*, db_session, individual_contact_id: int) -> Optional[IndividualContact]:
"""Returns an individual given an individual id."""
return (
db_session.query(IndividualContact)
.filter(IndividualContact.id == individual_contact_id)
.one_or_none()
)
def get_by_email(*, db_session, email: str) -> Optional[IndividualContact]:
"""Returns an individual given an individual email address."""
return (
db_session.query(IndividualContact).filter(IndividualContact.email == email).one_or_none()
)
def get_all(*, db_session) -> List[Optional[IndividualContact]]:
"""Returns all individuals."""
return db_session.query(IndividualContact)
def get_or_create(
*, db_session, email: str, incident: Incident = None, **kwargs
) -> IndividualContact:
"""Gets or creates an individual."""
# we fetch the individual contact from the database
individual_contact = get_by_email(db_session=db_session, email=email)
# we try to fetch the individual's contact information using the contact plugin
contact_plugin = plugin_service.get_active_instance(
db_session=db_session, project_id=incident.project.id, plugin_type="contact"
)
individual_info = {}
if contact_plugin:
individual_info = contact_plugin.instance.get(email, db_session=db_session)
kwargs["email"] = individual_info.get("email", email)
kwargs["name"] = individual_info.get("fullname", "Unknown")
kwargs["weblink"] = individual_info.get("weblink", "Unknown")
if not individual_contact:
# we create a new contact
individual_contact_in = IndividualContactCreate(**kwargs, project=incident.project)
individual_contact = create(
db_session=db_session, individual_contact_in=individual_contact_in
)
else:
# we update the existing contact
individual_contact_in = IndividualContactUpdate(**kwargs, project=incident.project)
individual_contact = update(
db_session=db_session,
individual_contact=individual_contact,
individual_contact_in=individual_contact_in,
)
return individual_contact
def create(*, db_session, individual_contact_in: IndividualContactCreate) -> IndividualContact:
"""Creates an individual."""
project = project_service.get_by_name_or_raise(
db_session=db_session, project_in=individual_contact_in.project
)
contact = IndividualContact(
**individual_contact_in.dict(exclude={"project", "filters"}),
project=project,
)
if individual_contact_in.filters is not None:
filters = [
search_filter_service.get(db_session=db_session, search_filter_id=f.id)
for f in individual_contact_in.filters
]
contact.filters = filters
db_session.add(contact)
db_session.commit()
return contact
def update(
*,
db_session,
individual_contact: IndividualContact,
individual_contact_in: IndividualContactUpdate,
) -> IndividualContact:
"""Updates an individual."""
individual_contact_data = individual_contact.dict()
update_data = individual_contact_in.dict(skip_defaults=True, exclude={"filters"})
for field in individual_contact_data:
if field in update_data:
setattr(individual_contact, field, update_data[field])
if individual_contact_in.filters is not None:
filters = [
search_filter_service.get(db_session=db_session, search_filter_id=f.id)
for f in individual_contact_in.filters
]
individual_contact.filters = filters
db_session.commit()
return individual_contact
def delete(*, db_session, individual_contact_id: int):
"""Deletes an individual."""
individual = (
db_session.query(IndividualContact)
.filter(IndividualContact.id == individual_contact_id)
.first()
)
individual.terms = []
db_session.delete(individual)
db_session.commit()
| 34.548148 | 98 | 0.718696 |
418cd899c580de46cd0b942bd12040f51612b662 | 7,757 | py | Python | parsing.py | iGiant/koncertsamara | 876267b7efc0ada608315367689cb8f60052b5ad | [
"Apache-2.0"
] | null | null | null | parsing.py | iGiant/koncertsamara | 876267b7efc0ada608315367689cb8f60052b5ad | [
"Apache-2.0"
] | null | null | null | parsing.py | iGiant/koncertsamara | 876267b7efc0ada608315367689cb8f60052b5ad | [
"Apache-2.0"
] | null | null | null | import logging
import urllib.parse
import requests
from lxml import html
from tqdm import trange
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from mysclient import send_message_to_slack
engine = create_engine('sqlite:///D:/Programs/python/db/koncertsamara.sqlite', echo=False)
Base = declarative_base()
Session = sessionmaker(engine)
class Subscription(Base):
__tablename__ = 'subscription'
id = Column(Integer, primary_key=True)
trigger = Column(String(50), nullable=False)
telegram_id = Column(Integer)
mail = Column(String(50))
count = Column(Integer)
def __repr__(self):
telegram = f'telegram: {self.telegram_id}, ' if self.telegram_id else ''
mail = f'mail: {self.mail}, ' if self.mail else ''
return f'trigger: {self.trigger}, {telegram}{mail}count: {self.count}'
def getafisha()-> tuple:
def addtusa(mystr: str)-> str:
temp = tuple(parsed_body.xpath(mystr))
return temp[0] if temp else ''
def changequotes(mytext: str)-> str:
if mytext and mytext[0] == '"':
mytext = '«' + mytext[1:]
return mytext.replace(' "', ' «').replace('"', '»').lstrip().rstrip()
def search(eventlist: tuple):
def send_mail(mail: str, key: str, event: dict):
import smtplib
from concertsamaradata import SMTPSERVER, SERVICESMAILLOGIN, SERVICESMAILPASS, BACKMAILADRR
from email.mime.text import MIMEText
mailtext = f"""Сработал триггер на слово "<b>{key}</b>"<br>
Мероприятие <a href="{event['url']}">{event['name']}</a> пройдет {event['date']} ({event['time'][:2]})
в {event['time'][3:]} в следующем месте: <i>{event['place']}</i>.<br><br>Билеты можно купить
<a href="{event['buy']}">здесь</a><br><br>{event['detail']}"""
msg = MIMEText(mailtext, 'HTML', 'utf-8')
msg['Subject'] = f'Культурные мероприятия Самары: сработал триггер {key}'
msg['From'] = BACKMAILADRR
msg['To'] = mail
smtpObj = smtplib.SMTP(SMTPSERVER, 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.ehlo()
smtpObj.login(SERVICESMAILLOGIN, SERVICESMAILPASS)
try:
smtpObj.sendmail(BACKMAILADRR, mail, msg.as_string())
except Exception:
pass
smtpObj.quit()
session = Session()
for event in eventlist:
if session.query(Subscription).count() > 0:
for subscr in session.query(Subscription).all():
if subscr.count != -1 and (subscr.trigger.lower() in event.get('name', '').lower() or
subscr.trigger.lower() in event.get('detail', '').lower()):
if subscr.count != 0:
if subscr.count == 1:
subscr.count = -1
else:
subscr.count -= 1
session.commit()
telegram_text = (f"Сработал триггер на слово *{subscr.trigger}*,\n" +
f"Мероприятие {event['name']} пройдет {event['date']} в {event['place']}")
send_message_to_slack(':sound: Concert', telegram_text)
if subscr.mail:
send_mail(subscr.mail, subscr.trigger, event)
logger.info(f'''Письмо на "{subscr.mail}", кодовое слово "{subscr.trigger}"''')
session.close()
logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO, filename=r'd:\python\logs\parsing.log')
logger = logging.getLogger(__name__)
logger.info('*' * 25)
http = 'http://koncertsamara.ru/afisha/'
afisha = []
pages = 0
while True:
temp_response = html.fromstring(requests.get(f'{http}?a-page={pages}').text)
temp_page = temp_response.xpath('//div[@class="pagination"]/ul/li/a/text()')
if temp_page[-1] != 'Следующая':
pages = int(temp_page[-1])
break
pages = int(temp_page[-2]) - 1
for page in trange(pages):
response = requests.get(http + '?a-page=' + str(page))
parsed_body = html.fromstring(response.text)
for i in range(1, round(parsed_body.xpath('count(//ul[@class="list"]/li)')) + 1):
tusa = {}
tusa['name'] = changequotes(addtusa(f'//ul[@class="list"]/li[{i}]/div/div[2]/h3/text()'))
tusa['date'] = addtusa(f'//ul[@class="list"]/li[{i}]/div/div[1]/span[1]/text()')
tusa['time'] = addtusa(f'//ul[@class="list"]/li[{i}]/div/div[1]/span[3]/text()')
tusa['place'] = changequotes(addtusa(f'//ul[@class="list"]/li[{i}]/h4/a/text()'))
tusa['url'] = addtusa(f'//ul[@class="list"]/li[{i}]/div/div[4]/div/a[1]/@href')
tusa['buy'] = addtusa(f'//ul[@class="list"]/li[{i}]/div/div[4]/div/a[2]/@href')
if not tusa['url']:
tusa['url'] = addtusa(f'//ul[@class="list"]/li[{i}]/div/div[4]/div/a[2]/@href')
tusa['buy'] = addtusa(f'//ul[@class="list"]/li[{i}]/div/div[4]/div/a[3]/@href')
tusa['url'] = urllib.parse.urljoin(http, tusa['url'])
tusa['buy'] = urllib.parse.urljoin(http, tusa['buy'])
temp_response = html.fromstring(requests.get(tusa['url']).text)
temp_detail = temp_response.xpath('//*[@id="current-description"]/p/text()')
tusa['detail'] = max(temp_detail, key=len) if temp_detail else ''
afisha.append(tusa)
result = tuple(afisha)
search(result)
return result
def savetofile(afisha, file='koncert.xlsx'):
import openpyxl
from openpyxl.styles import fonts, alignment, Side, Border
from openpyxl.styles.colors import COLOR_INDEX
from openpyxl.comments import comments
wb = openpyxl.Workbook()
ws = wb.active
ws.append(['Дата', 'Время', 'Событие (клик – подробно)', 'Место проведения (клик – бронирование)'])
side = Side(style='thin', color=COLOR_INDEX[0])
dside = Side(style='double', color=COLOR_INDEX[0])
border = Border(left=side, right=side, top=side, bottom=side)
hborder = Border(left=side, right=side, top=side, bottom=dside)
for i in range(len(afisha)):
ws.append([afisha[i]['date'], afisha[i]['time'],
'=HYPERLINK("%s","%s")' % (afisha[i]['url'], afisha[i]['name']),
'=HYPERLINK("%s","%s")' % (afisha[i]['buy'], afisha[i]['place'])])
if len(afisha[i]['detail']) > 10:
ws['C' + str(i + 2)].comment = comments.Comment(afisha[i]['detail'], '')
for r in ('A', 'B', 'C', 'D'):
ws[r + str(i + 2)].border = border
if r in ('A', 'B'):
ws[r + str(i + 2)].alignment = alignment.Alignment(horizontal='center')
for sym in ('A1', 'B1', 'C1', 'D1'):
ws[sym].font = fonts.Font(size=12, bold=True)
ws[sym].alignment = alignment.Alignment(horizontal='center')
ws[sym].border = hborder
ws.column_dimensions['A'].width = 18
ws.column_dimensions['B'].width = 12
ws.column_dimensions['C'].width = 60
ws.column_dimensions['D'].width = 60
wb.save(file)
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
if not sys.argv[1].endswith('.xlsx'):
sys.argv[1] += '.xlsx'
savetofile(getafisha(), sys.argv[1])
else:
afisha = getafisha()
print(*[f"{event['date']} - {event['time']} : {event['name']} ({event['place']})" for event in afisha],
sep = '\n')
input()
| 46.449102 | 119 | 0.562975 |
d20a7f10d0806bf0d831b02666b7debec4c5a71b | 2,472 | py | Python | scripts/powerup.py | saidwho12/JulyGame | 064654aaaf516931a074ce4d5021f2ecdbe621e0 | [
"MIT"
] | null | null | null | scripts/powerup.py | saidwho12/JulyGame | 064654aaaf516931a074ce4d5021f2ecdbe621e0 | [
"MIT"
] | null | null | null | scripts/powerup.py | saidwho12/JulyGame | 064654aaaf516931a074ce4d5021f2ecdbe621e0 | [
"MIT"
] | null | null | null | import glm
IDLE, DIE = range(2)
class Powerup:
state = -1
timer = 1
mesh_name = 'models/items/powerup'
tex_name = 'apple'
def __init__(self, engine, item_id, pos):
self.engine = engine
self.item_id = item_id
self.texture = self.engine.graphics.get_texture(self.tex_name)
self.mesh = self.engine.graphics.get_mesh(self.mesh_name)
self.pos = glm.vec3(*pos)
self.angle = 0
self.scale = 1
self.set_state(IDLE)
def spawn(self):
self.engine.game_manager.powerups.append(self)
self.engine.renderer.scene.append(self)
def despawn(self):
self.engine.renderer.scene.remove(self)
def on_collect(self):
pass
def set_state(self, state):
if state == DIE:
self.timer = 1
self.state = state
def update(self, dt):
if self.state is IDLE:
self.angle += 30 * dt
p_col = self.engine.game_manager.player.collider
if glm.distance(self.pos.xz, p_col.pos.xz) < 2:
if p_col.pos.y <= self.pos.y < p_col.pos.y + p_col.height:
self.set_state(DIE)
elif self.state is DIE:
self.timer -= dt
if self.timer > 0:
self.scale = self.timer
else:
self.despawn()
self.engine.game_manager.powerups.remove(self)
self.on_collect()
def draw(self, renderer):
renderer.push_matrix()
renderer.translate(*self.pos)
renderer.rotate(self.angle, 0, 1, 0)
if self.state is DIE:
renderer.scale(self.scale)
renderer.update_matrix()
renderer.set_texture(self.texture)
self.mesh.draw()
renderer.pop_matrix()
class Health(Powerup):
mesh_name = 'models/items/health'
tex_name = 'apple'
def on_collect(self):
self.engine.game_manager.player.add_health()
class Fuel(Powerup):
mesh_name = 'models/items/powerup'
tex_name = 'apple'
def on_collect(self):
self.engine.game_manager.player.add_fuel()
class SlowTime(Powerup):
mesh_name = 'models/items/clock'
tex_name = 'clock'
def on_collect(self):
self.engine.game_manager.player.start_slow_motion()
class Chips(Powerup):
mesh_name = 'models/items/chips'
tex_name = 'chips'
def on_collect(self):
self.engine.game_manager.player.add_markers(5)
| 23.769231 | 74 | 0.596278 |
1420ccfaf2da4823929ebc9365ca821c7d1882d8 | 10,806 | py | Python | sunpy/image/tests/test_transform.py | RhnSharma/sunpy | 03700193d287156ca1922eb27c4c2ad50040e53f | [
"BSD-2-Clause"
] | 628 | 2015-01-14T17:34:10.000Z | 2022-03-29T06:07:50.000Z | sunpy/image/tests/test_transform.py | RhnSharma/sunpy | 03700193d287156ca1922eb27c4c2ad50040e53f | [
"BSD-2-Clause"
] | 3,983 | 2015-01-03T11:16:21.000Z | 2022-03-31T16:55:38.000Z | sunpy/image/tests/test_transform.py | RhnSharma/sunpy | 03700193d287156ca1922eb27c4c2ad50040e53f | [
"BSD-2-Clause"
] | 582 | 2015-01-14T10:09:24.000Z | 2022-03-29T06:07:12.000Z | import numpy as np
import pytest
import skimage.data as images
from skimage import transform as tf
from sunpy.image.transform import affine_transform
from sunpy.util import SunpyUserWarning
# Tolerance for tests
RTOL = 1.0e-10
@pytest.fixture
def original():
# Test image
return images.camera().astype('float')
@pytest.fixture
def identity():
return np.array([[1, 0], [0, 1]])
def compare_results(expect, result, allclose=True):
"""
Function to check that the obtained results are what was expected, to
within the relative tolerance defined above.
"""
# Outermost pixels can contain artefacts which will be ignored.
exp = expect[1:-1, 1:-1]
res = result[1:-1, 1:-1]
t1 = abs(exp.mean() - res.mean()) <= RTOL*exp.mean()
# Don't do the allclose test for scipy as the bicubic algorithm has edge effects
# TODO: Develop a way of testing this for scipy
if not allclose:
return t1
else:
notclose = ~np.isclose(exp, res, rtol=RTOL)
t2 = not np.any(notclose)
# Print out every mismatch
if not t2:
mismatches = np.stack([*notclose.nonzero(), exp[notclose], res[notclose]]).T
for row in mismatches:
print(f"i={int(row[0]+1)}, j={int(row[1]+1)}: expected={row[2]}, result={row[3]}, "
f"adiff={row[2]-row[3]}, rdiff={(row[2]-row[3])/row[2]}")
return t1 and t2
@pytest.mark.parametrize("angle, k", [(90.0, 1), (-90.0, -1), (-270.0, 1),
(-90.0, 3), (360.0, 0), (-360.0, 0)])
def test_rotation(original, angle, k):
# Test rotation against expected outcome
angle = np.radians(angle)
c = np.round(np.cos(angle))
s = np.round(np.sin(angle))
rmatrix = np.array([[c, -s], [s, c]])
expected = np.rot90(original, k=k)
# Run the tests at order 4 as it produces more accurate 90 deg rotations
rot = affine_transform(original, order=4, rmatrix=rmatrix)
assert compare_results(expected, rot)
# TODO: Check incremental 360 degree rotation against original image
# Check derotated image against original
derot_matrix = np.array([[c, s], [-s, c]])
derot = affine_transform(rot, order=4, rmatrix=derot_matrix)
assert compare_results(original, derot)
@pytest.mark.parametrize("angle, k", [(90.0, 1), (-90.0, -1), (-270.0, 1),
(-90.0, 3), (360.0, 0), (-360.0, 0)])
def test_scipy_rotation(original, angle, k):
# Test rotation against expected outcome
angle = np.radians(angle)
c = np.round(np.cos(angle))
s = np.round(np.sin(angle))
rmatrix = np.array([[c, -s], [s, c]])
expected = np.rot90(original, k=k)
rot = affine_transform(original, rmatrix=rmatrix, use_scipy=True)
assert compare_results(expected, rot, allclose=False)
# TODO: Check incremental 360 degree rotation against original image
# Check derotated image against original
derot_matrix = np.array([[c, s], [-s, c]])
derot = affine_transform(rot, rmatrix=derot_matrix, use_scipy=True)
assert compare_results(original, derot, allclose=False)
dx_values, dy_values = list(range(-100, 101, 100))*3, list(range(-100, 101, 100))*3
dy_values.sort()
@pytest.mark.parametrize("dx, dy", list(zip(dx_values, dy_values)))
def test_shift(original, dx, dy):
# Rotation center for all translation tests.
image_center = np.array(original.shape)/2.0 - 0.5
# No rotation for all translation tests.
rmatrix = np.array([[1.0, 0.0], [0.0, 1.0]])
# Check a shifted shape against expected outcome
expected = np.roll(np.roll(original, dx, axis=1), dy, axis=0)
rcen = image_center - np.array([dx, dy])
shift = affine_transform(original, rmatrix=rmatrix, recenter=True, image_center=rcen)
ymin, ymax = max([0, dy]), min([original.shape[1], original.shape[1]+dy])
xmin, xmax = max([0, dx]), min([original.shape[0], original.shape[0]+dx])
assert compare_results(expected[ymin:ymax, xmin:xmax], shift[ymin:ymax, xmin:xmax])
# Check shifted and unshifted shape against original image
rcen = image_center + np.array([dx, dy])
unshift = affine_transform(shift, rmatrix=rmatrix, recenter=True, image_center=rcen)
# Need to ignore the portion of the image cut off by the first shift
ymin, ymax = max([0, -dy]), min([original.shape[1], original.shape[1]-dy])
xmin, xmax = max([0, -dx]), min([original.shape[0], original.shape[0]-dx])
assert compare_results(original[ymin:ymax, xmin:xmax], unshift[ymin:ymax, xmin:xmax])
@pytest.mark.parametrize("scale_factor", [0.25, 0.5, 0.75, 1.0, 1.25, 1.5])
def test_scale(original, scale_factor):
# No rotation for all scaling tests.
rmatrix = np.array([[1.0, 0.0], [0.0, 1.0]])
# Check a scaled image against the expected outcome
newim = tf.rescale(original / original.max(), scale_factor, order=4,
mode='constant', multichannel=False, anti_aliasing=False) * original.max()
# Old width and new center of image
w = original.shape[0] / 2.0 - 0.5
new_c = (newim.shape[0] / 2.0) - 0.5
expected = np.zeros(original.shape)
upper = int(w + new_c + 1)
if scale_factor > 1:
lower = int(new_c - w)
expected = newim[lower:upper, lower:upper]
else:
lower = int(w - new_c)
expected[lower:upper, lower:upper] = newim
scale = affine_transform(original, rmatrix=rmatrix, scale=scale_factor, order=4)
assert compare_results(expected, scale)
@pytest.mark.parametrize("angle, dx, dy, scale_factor", [(90, -100, 40, 0.25),
(-90, 40, -80, 0.75),
(180, 20, 50, 1.5)])
def test_all(original, angle, dx, dy, scale_factor):
"""
Tests to make sure that combinations of scaling, shifting and rotation
produce the expected output.
"""
k = int(angle / 90)
angle = np.radians(angle)
image_center = np.array(original.shape) / 2.0 - 0.5
# Check a shifted, rotated and scaled shape against expected outcome
c = np.round(np.cos(angle))
s = np.round(np.sin(angle))
rmatrix = np.array([[c, -s], [s, c]])
scale = tf.rescale(original / original.max(), scale_factor, order=4,
mode='constant', multichannel=False, anti_aliasing=False) * original.max()
new = np.zeros(original.shape)
disp = np.array([dx, dy])
dxs, dys = np.asarray(disp * scale_factor, dtype=int)
# Old width and new center of image
w = np.array(original.shape[0])/2.0 - 0.5
new_c = (np.array(scale.shape[0])/2.0 - 0.5)
upper = int(w+new_c+1)
if scale_factor > 1:
lower = int(new_c-w)
new = scale[lower-dys:upper-dys, lower-dxs:upper-dxs]
else:
lower = int(w-new_c)
new[lower+dys:upper+dys, lower+dxs:upper+dxs] = scale
rcen = image_center - disp
expected = np.rot90(new, k=k)
rotscaleshift = affine_transform(original, rmatrix=rmatrix, scale=scale_factor, order=4,
recenter=True, image_center=rcen)
assert compare_results(expected, rotscaleshift)
# Check a rotated/shifted and restored image against original
transformed = affine_transform(original, rmatrix=rmatrix, scale=1.0, order=4, recenter=True,
image_center=rcen)
inv_rcen = image_center + np.dot(rmatrix.T, np.array([dx, dy]))
inverse = affine_transform(transformed, rmatrix=rmatrix.T, scale=1.0, order=4, recenter=True,
image_center=inv_rcen)
# Need to ignore the portion of the image cut off by the first shift
ymin, ymax = max([0, -dy]), min([original.shape[1], original.shape[1]-dy])
xmin, xmax = max([0, -dx]), min([original.shape[0], original.shape[0]-dx])
assert compare_results(original[ymin:ymax, xmin:xmax], inverse[ymin:ymax, xmin:xmax])
def test_flat(identity):
# Test that a flat array can be rotated using scikit-image
in_arr = np.array([[100]], dtype=np.float64)
out_arr = affine_transform(in_arr, rmatrix=identity)
assert np.allclose(in_arr, out_arr, rtol=RTOL)
# Although a depreaction warning is raised, behaviour is as expected and will
# continue after the depreaction period, so ignore the warnings
@pytest.mark.filterwarnings('ignore:Passing `np.nan` to mean no clipping in np.clip has always '
'been unreliable, and is now deprecated')
def test_nan_skimage_low(identity):
# Test non-replacement of NaN values for scikit-image rotation with order <= 3
in_arr = np.array([[np.nan]])
out_arr = affine_transform(in_arr, rmatrix=identity, order=3)
assert np.all(np.isnan(out_arr))
def test_nan_skimage_high(identity):
# Test replacement of NaN values for scikit-image rotation with order >=4
in_arr = np.array([[np.nan]])
with pytest.warns(SunpyUserWarning, match='Setting NaNs to 0 for higher-order scikit-image rotation.'):
out_arr = affine_transform(in_arr, rmatrix=identity, order=4)
assert not np.all(np.isnan(out_arr))
def test_nan_scipy(identity):
# Test replacement of NaN values for scipy rotation
in_arr = np.array([[np.nan]])
with pytest.warns(SunpyUserWarning, match='Setting NaNs to 0 for SciPy rotation.'):
out_arr = affine_transform(in_arr, rmatrix=identity, use_scipy=True)
assert not np.all(np.isnan(out_arr))
def test_int(identity):
# Test casting of integer array to float array
in_arr = np.array([[100]], dtype=int)
with pytest.warns(SunpyUserWarning, match='Integer input data has been cast to float64'):
out_arr = affine_transform(in_arr, rmatrix=identity)
assert np.issubdtype(out_arr.dtype, np.floating)
def test_float32(identity):
# Check that float32 input remains as float32 output
# Test casting of integer array to float array
in_arr = np.array([[100]], dtype=np.float32)
out_arr = affine_transform(in_arr, rmatrix=identity)
assert np.issubdtype(out_arr.dtype, np.float32)
def test_reproducible_matrix_multiplication():
# Test whether matrix multiplication involving a large matrix always gives the same answer
# This indirectly tests whichever BLAS/LAPACK libraries that NumPy is linking to (if any)
x = np.arange(500000, dtype=np.float64)
src = np.vstack((x, -10*x)).T
matrix = np.array([[0, 1], [1, 0]])
expected = np.vstack((-10*x, x)).T # src @ matrix
mismatches = np.zeros(500, int)
for i in range(len(mismatches)):
result = src @ matrix
mismatches[i] = (~np.isclose(result, expected)).sum()
if mismatches[i] != 0:
print(f"{mismatches[i]} mismatching elements in multiplication #{i}")
assert np.sum(mismatches != 0) == 0
| 40.777358 | 107 | 0.650565 |
d8aff38dc2b867868dc4ea513cbbc79dc1ff26e8 | 7,722 | py | Python | Lib/site-packages/isapi/threaded_extension.py | Srinath-tr/Goferbot | 0f734d01c6504c6c97dbdf45f5adf8b25c0f9fd9 | [
"Apache-2.0",
"bzip2-1.0.6"
] | 1 | 2019-04-23T21:50:08.000Z | 2019-04-23T21:50:08.000Z | deps/salt/python/App/Lib/site-packages/isapi/threaded_extension.py | vmware-archive/salt-windows-install | e7407e33419ef6f882b86ec9ce3522c5a884ee16 | [
"BSD-2-Clause"
] | null | null | null | deps/salt/python/App/Lib/site-packages/isapi/threaded_extension.py | vmware-archive/salt-windows-install | e7407e33419ef6f882b86ec9ce3522c5a884ee16 | [
"BSD-2-Clause"
] | 2 | 2019-02-14T08:13:33.000Z | 2019-04-23T21:47:48.000Z | """An ISAPI extension base class implemented using a thread-pool."""
# $Id: threaded_extension.py,v 1.6 2009/03/02 04:41:10 mhammond Exp $
import sys
import time
from isapi import isapicon, ExtensionError
import isapi.simple
from win32file import GetQueuedCompletionStatus, CreateIoCompletionPort, \
PostQueuedCompletionStatus, CloseHandle
from win32security import SetThreadToken
from win32event import INFINITE
from pywintypes import OVERLAPPED
# Python 2.3 and earlier insists on "C" locale - if it isn't, subtle things
# break, such as floating point constants loaded from .pyc files.
# The threading module uses such floating-points as an argument to sleep(),
# resulting in extremely long sleeps when tiny intervals are specified.
# We can work around this by resetting the C locale before the import.
if sys.hexversion < 0x02040000:
import locale
locale.setlocale(locale.LC_NUMERIC, "C")
import threading
import traceback
ISAPI_REQUEST = 1
ISAPI_SHUTDOWN = 2
class WorkerThread(threading.Thread):
def __init__(self, extension, io_req_port):
self.running = False
self.io_req_port = io_req_port
self.extension = extension
threading.Thread.__init__(self)
# We wait 15 seconds for a thread to terminate, but if it fails to,
# we don't want the process to hang at exit waiting for it...
self.setDaemon(True)
def run(self):
self.running = True
while self.running:
errCode, bytes, key, overlapped = \
GetQueuedCompletionStatus(self.io_req_port, INFINITE)
if key == ISAPI_SHUTDOWN and overlapped is None:
break
# Let the parent extension handle the command.
dispatcher = self.extension.dispatch_map.get(key)
if dispatcher is None:
raise RuntimeError("Bad request '%s'" % (key,))
dispatcher(errCode, bytes, key, overlapped)
def call_handler(self, cblock):
self.extension.Dispatch(cblock)
# A generic thread-pool based extension, using IO Completion Ports.
# Sub-classes can override one method to implement a simple extension, or
# may leverage the CompletionPort to queue their own requests, and implement a
# fully asynch extension.
class ThreadPoolExtension(isapi.simple.SimpleExtension):
"Base class for an ISAPI extension based around a thread-pool"
max_workers = 20
worker_shutdown_wait = 15000 # 15 seconds for workers to quit...
def __init__(self):
self.workers = []
# extensible dispatch map, for sub-classes that need to post their
# own requests to the completion port.
# Each of these functions is called with the result of
# GetQueuedCompletionStatus for our port.
self.dispatch_map = {
ISAPI_REQUEST: self.DispatchConnection,
}
def GetExtensionVersion(self, vi):
isapi.simple.SimpleExtension.GetExtensionVersion(self, vi)
# As per Q192800, the CompletionPort should be created with the number
# of processors, even if the number of worker threads is much larger.
# Passing 0 means the system picks the number.
self.io_req_port = CreateIoCompletionPort(-1, None, 0, 0)
# start up the workers
self.workers = []
for i in range(self.max_workers):
worker = WorkerThread(self, self.io_req_port)
worker.start()
self.workers.append(worker)
def HttpExtensionProc(self, control_block):
overlapped = OVERLAPPED()
overlapped.object = control_block
PostQueuedCompletionStatus(self.io_req_port, 0, ISAPI_REQUEST, overlapped)
return isapicon.HSE_STATUS_PENDING
def TerminateExtension(self, status):
for worker in self.workers:
worker.running = False
for worker in self.workers:
PostQueuedCompletionStatus(self.io_req_port, 0, ISAPI_SHUTDOWN, None)
# wait for them to terminate - pity we aren't using 'native' threads
# as then we could do a smart wait - but now we need to poll....
end_time = time.time() + self.worker_shutdown_wait/1000
alive = self.workers
while alive:
if time.time() > end_time:
# xxx - might be nice to log something here.
break
time.sleep(0.2)
alive = [w for w in alive if w.isAlive()]
self.dispatch_map = {} # break circles
CloseHandle(self.io_req_port)
# This is the one operation the base class supports - a simple
# Connection request. We setup the thread-token, and dispatch to the
# sub-class's 'Dispatch' method.
def DispatchConnection(self, errCode, bytes, key, overlapped):
control_block = overlapped.object
# setup the correct user for this request
hRequestToken = control_block.GetImpersonationToken()
SetThreadToken(None, hRequestToken)
try:
try:
self.Dispatch(control_block)
except:
self.HandleDispatchError(control_block)
finally:
# reset the security context
SetThreadToken(None, None)
def Dispatch(self, ecb):
"""Overridden by the sub-class to handle connection requests.
This class creates a thread-pool using a Windows completion port,
and dispatches requests via this port. Sub-classes can generally
implement each connection request using blocking reads and writes, and
the thread-pool will still provide decent response to the end user.
The sub-class can set a max_workers attribute (default is 20). Note
that this generally does *not* mean 20 threads will all be concurrently
running, via the magic of Windows completion ports.
There is no default implementation - sub-classes must implement this.
"""
raise NotImplementedError("sub-classes should override Dispatch")
def HandleDispatchError(self, ecb):
"""Handles errors in the Dispatch method.
When a Dispatch method call fails, this method is called to handle
the exception. The default implementation formats the traceback
in the browser.
"""
ecb.HttpStatusCode = isapicon.HSE_STATUS_ERROR
#control_block.LogData = "we failed!"
exc_typ, exc_val, exc_tb = sys.exc_info()
limit = None
try:
try:
import cgi
ecb.SendResponseHeaders("200 OK", "Content-type: text/html\r\n\r\n",
False)
print >> ecb
print >> ecb, "<H3>Traceback (most recent call last):</H3>"
list = traceback.format_tb(exc_tb, limit) + \
traceback.format_exception_only(exc_typ, exc_val)
print >> ecb, "<PRE>%s<B>%s</B></PRE>" % (
cgi.escape("".join(list[:-1])), cgi.escape(list[-1]),)
except ExtensionError:
# The client disconnected without reading the error body -
# its probably not a real browser at the other end, ignore it.
pass
except:
print "FAILED to render the error message!"
traceback.print_exc()
print "ORIGINAL extension error:"
traceback.print_exception(exc_typ, exc_val, exc_tb)
finally:
# holding tracebacks in a local of a frame that may itself be
# part of a traceback used to be evil and cause leaks!
exc_tb = None
ecb.DoneWithSession()
| 42.662983 | 85 | 0.64245 |
3762a2560fc7ae2e0d4f9a8d8890581aab911f55 | 2,216 | py | Python | src/kalibr_to_camera_poses.py | Shuhei-YOSHIDA/tagslam | 1fa3bef064696b289fece0c98b92001b3fb84fae | [
"Apache-2.0"
] | 210 | 2018-04-04T12:34:02.000Z | 2022-03-24T03:49:46.000Z | src/kalibr_to_camera_poses.py | Shuhei-YOSHIDA/tagslam | 1fa3bef064696b289fece0c98b92001b3fb84fae | [
"Apache-2.0"
] | 27 | 2018-11-05T22:05:29.000Z | 2021-12-01T02:30:57.000Z | src/kalibr_to_camera_poses.py | Shuhei-YOSHIDA/tagslam | 1fa3bef064696b289fece0c98b92001b3fb84fae | [
"Apache-2.0"
] | 58 | 2018-04-30T02:43:33.000Z | 2022-01-28T16:48:55.000Z | #!/usr/bin/env python
#------------------------------------------------------------------------------
# convert kalibr format to camera_poses.yaml format
#
# 2019 Bernd Pfrommer
import rospy
import argparse
import copy
import yaml
import re
import numpy as np
import geometry_msgs
import sensor_msgs
import tf2_msgs
import time
import math
import read_calib
R = np.asarray(
[ 1000000.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 1000000.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 1000000.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1000000.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1000000.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 1000000.0])
def quaternion_to_axis_angle(q):
a = 2.0 * math.acos(q.w)
sqinv = 1.0 / math.sqrt(1.0 - q.w * q.w) if q.w * q.w < 1.0 - 1e-8 else 0
aa = a * np.asarray((q.x, q.y, q.z)) * sqinv
return aa
def rvec_tvec_to_mat(rvec, tvec):
l = np.linalg.norm(rvec)
n = rvec/l if l > 1e-8 else np.array([1.0, 0.0, 0.0])
T = tf.transformations.rotation_matrix(l, n)
T[0:3, 3] = tvec
return T
def print_item(name, tf):
aa = quaternion_to_axis_angle(tf.rotation)
print "%s:" % name
print " pose:"
print " position:"
print " x: ", tf.translation.x
print " y: ", tf.translation.y
print " z: ", tf.translation.z
print " rotation:"
print " x: ", aa[0]
print " y: ", aa[1]
print " z: ", aa[2]
print " R:"
print " [", ('{:.8f}, '*6).format(*R[0:6])
for i in range(0,4):
print " ", ('{:.8f}, '*6).format(*R[(i*6 + 6):(i*6 + 12)])
print " ", ('{:.8f}, '*5).format(*R[30:35]), "%.8f]" % R[35]
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='convert kalibr to camera_poses.yaml')
parser.add_argument(
'--use_imu_tf', '-i', action='store', default=False, type=bool,
help='use imu transform.')
parser.add_argument(
'--calib', action='store', default=None, required=True,
help='name of calibration file')
args = parser.parse_args()
tfs = read_calib.read_calib(args.calib, args.use_imu_tf)
for name in sorted(tfs.keys()):
print_item(name, tfs[name])
| 28.779221 | 79 | 0.544224 |
96764b1029a1c1ac3297084416174cde98442f25 | 4,407 | py | Python | etl/parsers/etw/Microsoft_Windows_Proximity_Common.py | IMULMUL/etl-parser | 76b7c046866ce0469cd129ee3f7bb3799b34e271 | [
"Apache-2.0"
] | 104 | 2020-03-04T14:31:31.000Z | 2022-03-28T02:59:36.000Z | etl/parsers/etw/Microsoft_Windows_Proximity_Common.py | IMULMUL/etl-parser | 76b7c046866ce0469cd129ee3f7bb3799b34e271 | [
"Apache-2.0"
] | 7 | 2020-04-20T09:18:39.000Z | 2022-03-19T17:06:19.000Z | etl/parsers/etw/Microsoft_Windows_Proximity_Common.py | IMULMUL/etl-parser | 76b7c046866ce0469cd129ee3f7bb3799b34e271 | [
"Apache-2.0"
] | 16 | 2020-03-05T18:55:59.000Z | 2022-03-01T10:19:28.000Z | # -*- coding: utf-8 -*-
"""
Microsoft-Windows-Proximity-Common
GUID : 28058203-d394-4afc-b2a6-2f9155a3bb95
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import Sid
from etl.parsers.etw.core import Etw, declare, guid
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=5, version=0)
class Microsoft_Windows_Proximity_Common_5_0(Etw):
pattern = Struct(
"Pointer1" / Int64ul
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=10, version=0)
class Microsoft_Windows_Proximity_Common_10_0(Etw):
pattern = Struct(
"Pointer1" / Int64ul
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=11, version=0)
class Microsoft_Windows_Proximity_Common_11_0(Etw):
pattern = Struct(
"Pointer1" / Int64ul,
"String2" / WString,
"String3" / WString
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=12, version=0)
class Microsoft_Windows_Proximity_Common_12_0(Etw):
pattern = Struct(
"Pointer1" / Int64ul,
"String2" / WString,
"String3" / WString
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=13, version=0)
class Microsoft_Windows_Proximity_Common_13_0(Etw):
pattern = Struct(
"Pointer1" / Int64ul,
"String2" / WString,
"String3" / WString
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=14, version=0)
class Microsoft_Windows_Proximity_Common_14_0(Etw):
pattern = Struct(
"HrResult" / Int32ul,
"DeviceCategory" / WString
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=15, version=0)
class Microsoft_Windows_Proximity_Common_15_0(Etw):
pattern = Struct(
"HrResult" / Int32ul,
"DeviceCategory" / WString
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=16, version=0)
class Microsoft_Windows_Proximity_Common_16_0(Etw):
pattern = Struct(
"String" / WString
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=17, version=0)
class Microsoft_Windows_Proximity_Common_17_0(Etw):
pattern = Struct(
"String" / WString
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=18, version=0)
class Microsoft_Windows_Proximity_Common_18_0(Etw):
pattern = Struct(
"Pointer1" / Int64ul
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=19, version=0)
class Microsoft_Windows_Proximity_Common_19_0(Etw):
pattern = Struct(
"Pointer1" / Int64ul
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=20, version=0)
class Microsoft_Windows_Proximity_Common_20_0(Etw):
pattern = Struct(
"String" / WString
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=21, version=0)
class Microsoft_Windows_Proximity_Common_21_0(Etw):
pattern = Struct(
"String" / WString
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=22, version=0)
class Microsoft_Windows_Proximity_Common_22_0(Etw):
pattern = Struct(
"String" / WString
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=23, version=0)
class Microsoft_Windows_Proximity_Common_23_0(Etw):
pattern = Struct(
"Integer4" / Int32ul,
"String" / WString
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=24, version=0)
class Microsoft_Windows_Proximity_Common_24_0(Etw):
pattern = Struct(
"String1" / WString,
"String2" / WString
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=30, version=0)
class Microsoft_Windows_Proximity_Common_30_0(Etw):
pattern = Struct(
"Pointer1" / Int64ul
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=31, version=0)
class Microsoft_Windows_Proximity_Common_31_0(Etw):
pattern = Struct(
"Pointer1" / Int64ul
)
@declare(guid=guid("28058203-d394-4afc-b2a6-2f9155a3bb95"), event_id=41, version=0)
class Microsoft_Windows_Proximity_Common_41_0(Etw):
pattern = Struct(
"TransportType" / Int32ul,
"HrConnectResult" / Int32ul
)
| 28.432258 | 123 | 0.705469 |
fa59d93a447b77800c140f07404e324ae460de52 | 5,648 | py | Python | src/circles.py | simra/CartridgeOCR | 445eb51b93c9297dedee076be8b197e6d7697b5d | [
"MIT"
] | null | null | null | src/circles.py | simra/CartridgeOCR | 445eb51b93c9297dedee076be8b197e6d7697b5d | [
"MIT"
] | null | null | null | src/circles.py | simra/CartridgeOCR | 445eb51b93c9297dedee076be8b197e6d7697b5d | [
"MIT"
] | null | null | null | import cv2
import numpy as np
import sys
import os
import json
import logging
import argparse
from math import sqrt
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser('Detect cartridge locations')
parser.add_argument('input', type=str, help='text file containing of files to process')
# todo: column to process
parser.add_argument('output', type=str, help='output text file containing circle positions')
parser.add_argument('--output_folder', type=str, default='outimages', help='where to save the output images')
parser.add_argument('--targetW', type=int, default=480, help='Image rescale width')
parser.add_argument('--blurRadius', type=int, default=5, help='Blur radius, in pixels, calibrated to targetW')
parser.add_argument('--edgeThreshold', type=int, default=50, help='Canny edge difference threshold')
parser.add_argument('--detectionThreshold', type=int, default=60, help='Voting threshold to be detected as a circle')
parser.add_argument('--minDist', type=int, default=50, help='minimum distance between circles')
parser.add_argument('--minRadius', type=int, default=0, help='minimum circle radius')
parser.add_argument('--maxRadius', type=int, default=0, help='maximum circle radius')
args=parser.parse_args()
def isValid(circle, priorCircles, w, h):
(x,y,r)=map(float,list(circle))
if x-r<-0.05*w or x+r>=1.05*w or y-r<-0.05*h or y+r>=1.05*h:
return False
for c0 in priorCircles:
(x0,y0,r0)=map(float,list(c0))
logging.debug((x-x0)**2+(y-y0)**2)
rc = sqrt((x-x0)**2+(y-y0)**2)
if rc<r+r0:
return False
return True
def detectCircles(filename,
targetW = 480,
blurRadius=5,
edgeThreshold=50,
detectionThreshold=60,
minDist=50,
minRadius=0,
maxRadius=0):
logging.info(f'loading {filename}')
img = cv2.imread(filename,0)
h, w = img.shape
logging.info(f'width: {w} height: {h}')
# TODO: build a pyramid and optimize
#targetW = 480
scale = float(targetW)/w
logging.info(f'scaling by {scale}')
img = cv2.resize(img, None, fx = scale, fy = scale)
img = cv2.medianBlur(img, blurRadius)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
h2, w2 = img.shape
# https://docs.opencv.org/3.4/dd/d1a/group__imgproc__feature.html#ga47849c3be0d0406ad3ca45db65a25d2d
# method Detection method, see HoughModes. Currently, the only implemented method is HOUGH_GRADIENT
# dp Inverse ratio of the accumulator resolution to the image resolution. For example, if dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has half as big width and height.
# minDist Minimum distance between the centers of the detected circles. If the parameter is too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is too large, some circles may be missed.
# param1 First method-specific parameter. In case of HOUGH_GRADIENT , it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller).
# param2 Second method-specific parameter. In case of HOUGH_GRADIENT , it is the accumulator threshold for the circle centers at the detection stage. The smaller it is, the more false circles may be detected. Circles, corresponding to the larger accumulator values, will be returned first.
# minRadius Minimum circle radius.
# maxRadius Maximum circle radius. If <= 0, uses the maximum image dimension. If < 0, returns centers without finding the radius.
logging.info('Apply Hough transform')
#minDist = 50
#edgeThreshold = 50
#detectionThreshold = 60
circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT, 1, minDist,
param1=edgeThreshold, param2=detectionThreshold,
minRadius=minRadius, maxRadius=maxRadius)
circles = np.uint16(np.around(circles))
# Take the largest?
# Eliminate circles inside?
result = list(sorted(circles[0,:], key=lambda x: x[2], reverse=True))
returnedResult = []
for i in result:
# must be fully contained in the image
# must not be contained in another circle
logging.info(f'circle: {i}')
if (isValid(i, returnedResult, w2, h2)):
# draw the outer circle
cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle
cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
returnedResult.append(i)
#cv2.imshow('detected circles',cimg)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
return(([r*scale for r in returnedResult],cimg))
if args.output_folder and not os.path.exists(args.output_folder):
os.makedirs(args.output_folder)
with open(args.input, 'r', encoding='utf-8') as inF, \
open(args.output, 'w', encoding='utf-8') as outF:
for (i,l) in enumerate(inF):
l=l.strip()
(circles,outImg) = detectCircles(l,
targetW = args.targetW,
blurRadius= args.blurRadius,
edgeThreshold= args.edgeThreshold,
detectionThreshold = args.detectionThreshold,
minDist = args.minDist,
minRadius = args.minRadius,
maxRadius=args.maxRadius
)
outImgPath = ''
if args.output_folder:
outImgPath = os.path.join(args.output_folder, f'{i}_processed.jpg')
cv2.imwrite(outImgPath, outImg)
outF.write(f'{l}\t{json.dumps(list([list(c) for c in circles]))}\t{outImgPath}\n')
| 45.184 | 293 | 0.666608 |
4d1e6811e2f5337b914abd46cd83fd8c161c0095 | 1,228 | py | Python | src/process_data.py | matthewmacleod/poem_jinn | 0599b77f36bf5f1be35cd35e0d894e458251ea8c | [
"MIT"
] | null | null | null | src/process_data.py | matthewmacleod/poem_jinn | 0599b77f36bf5f1be35cd35e0d894e458251ea8c | [
"MIT"
] | null | null | null | src/process_data.py | matthewmacleod/poem_jinn | 0599b77f36bf5f1be35cd35e0d894e458251ea8c | [
"MIT"
] | null | null | null | """
code to clean gutenburg text, run:
python src/process_data.py data/shelley.txt
"""
import sys, os
import re
def single_space(s):
while ' ' in s:
s = s.replace(' ', ' ')
return s
def poetry_clean(text):
# clean numbers
text = re.sub(r'\_?[0-9]+\.?', '', text)
text = text.replace(':', ' ')
return text
def process_text(target):
text = []
with open(target, mode='r') as f:
in_quote = False
for line in f:
if 'NOTES ON THE TEXT' in line:
break
if line.startswith('[') or line.startswith('('):
in_quote = True
if ']' in line or ')' in line:
in_quote = False
continue
if not in_quote:
line = line.rstrip()
line = poetry_clean(line)
line = single_space(line)
text.append(line)
return text
if len(sys.argv) != 2:
sys.exit('supply target file')
target = sys.argv[1]
print('Cleaning file:', target)
text = process_text(target)
outfile = target.replace('.txt', '_clean.txt')
with open(outfile, mode='w') as f:
for line in text:
f.write(line+'\n')
print('Done')
| 22.327273 | 60 | 0.527687 |
24b447e114b105eae146f37bf1258de2ed93ad86 | 34,740 | py | Python | work2.py | Esherymack/color-analyzer | 072d1f42d989abeed565b302418bd69d6d489661 | [
"Unlicense"
] | null | null | null | work2.py | Esherymack/color-analyzer | 072d1f42d989abeed565b302418bd69d6d489661 | [
"Unlicense"
] | null | null | null | work2.py | Esherymack/color-analyzer | 072d1f42d989abeed565b302418bd69d6d489661 | [
"Unlicense"
] | null | null | null |
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import numpy as np
import cv2
from collections import Counter
from skimage.color import rgb2lab, deltaE_cie76, rgb2hsv
import os
import colorsys
import operator
import csv
image_data_directory = "./data"
# Colors to try and match
colors_dict = {
"0048BA":"Absolute Zero","B0BF1A":"Acid green","7CB9E8":"Aero","C9FFE5":"Aer o blue","B284BE":"African violet","72A0C1":"Air superiority blue","EDEAE0":"Alabaster","F0F8FF":"Alice blue","C46210":"Alloy orange","EFDECD":"Almond","E52B50":"Amaranth","9F2B68":"Amaranth (M&P)","F19CBB":"Amaranth pink","AB274F":"Amaranth purple","D3212D":"Amaranth red","3B7A57":"Amazon","FFBF00":"Amber","FF7E00":"Amber (SAE/ECE)","9966CC":"Amethyst","A4C639":"Android green","CD9575":"Antique brass","665D1E":"Antique bronze","915C83":"Antique fuchsia","841B2D":"Antique ruby","FAEBD7":"Antique white","008000":"Ao (English)",
"8DB600":"Apple green","FBCEB1":"Apricot","00FFFF":"Aqua","7FFFD4":"Aquamarine","D0FF14":"Arctic lime","4B5320":"Army green","8F9779":"Artichoke","E9D66B":"Arylide yellow","B2BEB5":"Ash gray","87A96B":"Asparagus","FF9966":"Atomic tangerine","A52A2A":"Auburn","FDEE00":"Aureolin","568203":"Avocado","007FFF":"Azure","F0FFFF":"Azure (X11/web color)","89CFF0":"Baby blue","A1CAF1":"Baby blue eyes","F4C2C2":"Baby pink","FEFEFA":"Baby powder","FF91AF":"Baker-Miller pink","FAE7B5":"Banana Mania","DA1884":"Barbie Pink","7C0A02":"Barn red","848482":"Battleship grey","BCD4E6":"Beau blue",
"9F8170":"Beaver","F5F5DC":"Beige","2E5894":"B'dazzled blue","9C2542":"Big dip o’ruby","FFE4C4":"Bisque","3D2B1F":"Bistre","967117":"Bistre brown","CAE00D":"Bitter lemon","BFFF00":"Bitter lime","FE6F5E":"Bittersweet","BF4F51":"Bittersweet shimmer","000000":"Black","3D0C02":"Black bean","1B1811":"Black chocolate","3B2F2F":"Black coffee","54626F":"Black coral","3B3C36":"Black olive","BFAFB2":"Black Shadows","FFEBCD":"Blanched almond","A57164":"Blast-off bronze","318CE7":"Bleu de France","ACE5EE":"Blizzard blue","FAF0BE":"Blond","660000":"Blood red","0000FF":"Blue","1F75FE":"Blue (Crayola)",
"0093AF":"Blue (Munsell)","0087BD":"Blue (NCS)","0018A8":"Blue (Pantone)","333399":"Blue (pigment)","0247FE":"Blue (RYB)","A2A2D0":"Blue bell","6699CC":"Blue-gray","0D98BA":"Blue-green","064E40":"Blue-green (color wheel)","5DADEC":"Blue jeans","126180":"Blue sapphire","8A2BE2":"Blue-violet","7366BD":"Blue-violet (Crayola)","4D1A7F":"Blue-violet (color wheel)","5072A7":"Blue yonder","3C69E7":"Bluetiful","DE5D83":"Blush","79443B":"Bole","E3DAC9":"Bone","006A4E":"Bottle green","87413F":"Brandy","CB4154":"Brick red","66FF00":"Bright green","D891EF":"Bright lilac","C32148":"Bright maroon","1974D2":"Bright navy blue",
"FFAA1D":"Bright yellow (Crayola)","FF55A3":"Brilliant rose","FB607F":"Brink pink","004225":"British racing green","CD7F32":"Bronze","88540B":"Brown","AF6E4D":"Brown sugar","1B4D3E":"Brunswick green","7BB661":"Bud green","F0DC82":"Buff","800020":"Burgundy","DEB887":"Burlywood","A17A74":"Burnished brown","CC5500":"Burnt orange","E97451":"Burnt sienna","8A3324":"Burnt umber","BD33A4":"Byzantine","702963":"Byzantium","536872":"Cadet","5F9EA0":"Cadet blue","A9B2C3":"Cadet blue (Crayola)","91A3B0":"Cadet grey","006B3C":"Cadmium green","ED872D":"Cadmium orange","E30022":"Cadmium red","FFF600":"Cadmium yellow",
"A67B5B":"Café au lait","4B3621":"Café noir","A3C1AD":"Cambridge blue","C19A6B":"Camel","EFBBCC":"Cameo pink","FFFF99":"Canary","FFEF00":"Canary yellow","FF0800":"Candy apple red","E4717A":"Candy pink","00BFFF":"Capri","592720":"Caput mortuum","C41E3A":"Cardinal","00CC99":"Caribbean green","960018":"Carmine","D70040":"Carmine (M&P)","FFA6C9":"Carnation pink","B31B1B":"Carnelian","56A0D3":"Carolina blue","ED9121":"Carrot orange","00563F":"Castleton green","703642":"Catawba","C95A49":"Cedar Chest","ACE1AF":"Celadon","007BA7":"Celadon blue","2F847C":"Celadon green","B2FFFF":"Celeste",
"246BCE":"Celtic blue","DE3163":"Cerise","007BA7":"Cerulean","2A52BE":"Cerulean blue","6D9BC3":"Cerulean frost","1DACD6":"Cerulean (Crayola)","007AA5":"CG blue","E03C31":"CG red","F7E7CE":"Champagne","F1DDCF":"Champagne pink","36454F":"Charcoal","232B2B":"Charleston green","E68FAC":"Charm pink","DFFF00":"Chartreuse (traditional)","7FFF00":"Chartreuse (web)","FFB7C5":"Cherry blossom pink","954535":"Chestnut","DE6FA1":"China pink","A8516E":"China rose","AA381E":"Chinese red","856088":"Chinese violet","FFB200":"Chinese yellow","7B3F00":"Chocolate (traditional)","D2691E":"Chocolate (web)","FFA700":"Chrome yellow","98817B":"Cinereous",
"E34234":"Cinnabar","CD607E":"Cinnamon Satin","E4D00A":"Citrine","9FA91F":"Citron","7F1734":"Claret","0047AB":"Cobalt blue","D2691E":"Cocoa brown","6F4E37":"Coffee","B9D9EB":"Columbia Blue","F88379":"Congo pink","8C92AC":"Cool grey","B87333":"Copper","DA8A67":"Copper (Crayola)","AD6F69":"Copper penny","CB6D51":"Copper red","996666":"Copper rose","FF3800":"Coquelicot","FF7F50":"Coral","F88379":"Coral pink","893F45":"Cordovan","FBEC5D":"Corn","6495ED":"Cornflower blue","FFF8DC":"Cornsilk","2E2D88":"Cosmic cobalt","FFF8E7":"Cosmic latte","81613C":"Coyote brown",
"FFBCD9":"Cotton candy","FFFDD0":"Cream","DC143C":"Crimson","9E1B32":"Crimson (UA)","F5F5F5":"Cultured","00FFFF":"Cyan","00B7EB":"Cyan (process)","58427C":"Cyber grape","FFD300":"Cyber yellow","F56FA1":"Cyclamen","666699":"Dark blue-gray","654321":"Dark brown","5D3954":"Dark byzantium","26428B":"Dark cornflower blue","008B8B":"Dark cyan","536878":"Dark electric blue","B8860B":"Dark goldenrod","013220":"Dark green","006400":"Dark green (X11)","1A2421":"Dark jungle green","BDB76B":"Dark khaki","483C32":"Dark lava","534B4F":"Dark liver","543D37":"Dark liver (horses)","8B008B":"Dark magenta","4A5D23":"Dark moss green",
"556B2F":"Dark olive green","FF8C00":"Dark orange","9932CC":"Dark orchid","03C03C":"Dark pastel green","301934":"Dark purple","8B0000":"Dark red","E9967A":"Dark salmon","8FBC8F":"Dark sea green","3C1414":"Dark sienna","8CBED6":"Dark sky blue","483D8B":"Dark slate blue","2F4F4F":"Dark slate gray","177245":"Dark spring green","00CED1":"Dark turquoise","9400D3":"Dark violet","00703C":"Dartmouth green","555555":"Davy's grey","DA3287":"Deep cerise","FAD6A5":"Deep champagne","B94E48":"Deep chestnut","004B49":"Deep jungle green","FF1493":"Deep pink","FF9933":"Deep saffron","00BFFF":"Deep sky blue","4A646C":"Deep Space Sparkle","7E5E60":"Deep taupe",
"1560BD":"Denim","2243B6":"Denim blue","C19A6B":"Desert","EDC9AF":"Desert sand","696969":"Dim gray","1E90FF":"Dodger blue","D71868":"Dogwood rose","967117":"Drab","00009C":"Duke blue","EFDFBB":"Dutch white","E1A95F":"Earth yellow","555D50":"Ebony","C2B280":"Ecru","1B1B1B":"Eerie black","614051":"Eggplant","F0EAD6":"Eggshell","1034A6":"Egyptian blue","7DF9FF":"Electric blue","00FF00":"Electric green","6F00FF":"Electric indigo","CCFF00":"Electric lime","BF00FF":"Electric purple","8F00FF":"Electric violet","50C878":"Emerald","6C3082":"Eminence","1B4D3E":"English green",
"B48395":"English lavender","AB4B52":"English red","CC474B":"English vermillion","563C5C":"English violet","00FF40":"Erin","96C8A2":"Eton blue","C19A6B":"Fallow","801818":"Falu red","B53389":"Fandango","DE5285":"Fandango pink","F400A1":"Fashion fuchsia","E5AA70":"Fawn","4D5D53":"Feldgrau","4F7942":"Fern green","6C541E":"Field drab","FF5470":"Fiery rose","B22222":"Firebrick","CE2029":"Fire engine red","E95C4B":"Fire opal","E25822":"Flame","EEDC82":"Flax","0063dc":"Flickr Blue","FB0081":"Flickr Pink","A2006D":"Flirt","FFFAF0":"Floral white","15F4EE":"Fluorescent blue",
"5FA777":"Forest green (Crayola)","014421":"Forest green (traditional)","228B22":"Forest green (web)","A67B5B":"French beige","856D4D":"French bistre","0072BB":"French blue","FD3F92":"French fuchsia","86608E":"French lilac","9EFD38":"French lime","D473D4":"French mauve","FD6C9E":"French pink","C72C48":"French raspberry","F64A8A":"French rose","77B5FE":"French sky blue","8806CE":"French violet","E936A7":"Frostbite","FF00FF":"Fuchsia","C154C1":"Fuchsia (Crayola)","CC397B":"Fuchsia purple","C74375":"Fuchsia rose","E48400":"Fulvous","87421F":"Fuzzy Wuzzy","DCDCDC":"Gainsboro","E49B0F":"Gamboge","007F66":"Generic viridian","F8F8FF":"Ghost white",
"6082B6":"Glaucous","AB92B3":"Glossy grape","00AB66":"GO green","A57C00":"Gold","D4AF37":"Gold (metallic)","FFD700":"Gold (web) (Golden)","E6BE8A":"Gold (Crayola)","85754E":"Gold Fusion","996515":"Golden brown","FCC200":"Golden poppy","FFDF00":"Golden yellow","DAA520":"Goldenrod","676767":"Granite gray","A8E4A0":"Granny Smith apple","808080":"Gray (web)","BEBEBE":"Gray (X11 gray)","00FF00":"Green","1CAC78":"Green (Crayola)","008000":"Green (web)","00A877":"Green (Munsell)","009F6B":"Green (NCS)","00AD43":"Green (Pantone)","00A550":"Green (pigment)","66B032":"Green (RYB)","1164B4":"Green-blue","2887C8":"Green-blue (Crayola)",
"009966":"Green-cyan","A7F432":"Green Lizard","6EAEA1":"Green Sheen","ADFF2F":"Green-yellow","F0E891":"Green-yellow (Crayola)","A99A86":"Grullo","2a3439":"Gunmetal","446CCF":"Han blue","5218FA":"Han purple","E9D66B":"Hansa yellow","3FFF00":"Harlequin","DA9100":"Harvest gold","FF7A00":"Heat Wave","DF73FF":"Heliotrope","AA98A9":"Heliotrope gray","F400A1":"Hollywood cerise","F0FFF0":"Honeydew","006DB0":"Honolulu blue","49796B":"Hooker's green","FF1DCE":"Hot magenta","FF69B4":"Hot pink","355E3B":"Hunter green","71A6D2":"Iceberg","FCF75E":"Icterine","319177":"Illuminating emerald","ED2939":"Imperial red",
"B2EC5D":"Inchworm","4C516D":"Independence","138808":"India green","CD5C5C":"Indian red","E3A857":"Indian yellow","4B0082":"Indigo","00416A":"Indigo dye","002FA7":"International Klein Blue","FF4F00":"International orange (aerospace)","BA160C":"International orange (engineering)","C0362C":"International orange (Golden Gate Bridge)","5A4FCF":"Iris","B3446C":"Irresistible","F4F0EC":"Isabelline","B2FFFF":"Italian sky blue","FFFFF0":"Ivory","00A86B":"Jade","F8DE7E":"Jasmine","A50B5E":"Jazzberry jam","343434":"Jet","F4CA16":"Jonquil","BDDA57":"June bud","29AB87":"Jungle green","4CBB17":"Kelly green","3AB09E":"Keppel","E8F48C":"Key lime",
"C3B091":"Khaki (web)","F0E68C":"Khaki (X11) (Light khaki)","882D17":"Kobe","E79FC4":"Kobi","6B4423":"Kobicha","354230":"Kombu green","512888":"KSU purple","D6CADD":"Languid lavender","26619C":"Lapis lazuli","FFFF66":"Laser lemon","A9BA9D":"Laurel green","CF1020":"Lava","B57EDC":"Lavender (floral)","E6E6FA":"Lavender (web)","CCCCFF":"Lavender blue","FFF0F5":"Lavender blush","C4C3D0":"Lavender gray","7CFC00":"Lawn green","FFF700":"Lemon","FFFACD":"Lemon chiffon","CCA01D":"Lemon curry","FDFF00":"Lemon glacier","F6EABE":"Lemon meringue","FFF44F":"Lemon yellow","FFFF9F":"Lemon yellow (Crayola)","545AA7":"Liberty",
"ADD8E6":"Light blue","F08080":"Light coral","93CCEA":"Light cornflower blue","E0FFFF":"Light cyan","C8AD7F":"Light French beige","FAFAD2":"Light goldenrod yellow","D3D3D3":"Light gray","90EE90":"Light green","FED8B1":"Light orange","C5CBE1":"Light periwinkle","FFB6C1":"Light pink","FFA07A":"Light salmon","20B2AA":"Light sea green","87CEFA":"Light sky blue","778899":"Light slate gray","B0C4DE":"Light steel blue","FFFFE0":"Light yellow","C8A2C8":"Lilac","AE98AA":"Lilac Luster","BFFF00":"Lime (color wheel)","00FF00":"Lime (web) (X11 green)","32CD32":"Lime green","195905":"Lincoln green","FAF0E6":"Linen","C19A6B":"Lion","DE6FA1":"Liseran purple",
"6CA0DC":"Little boy blue","674C47":"Liver","B86D29":"Liver (dogs)","6C2E1F":"Liver (organ)","987456":"Liver chestnut","6699CC":"Livid","FFBD88":"Macaroni and Cheese","CC3336":"Madder Lake","FF00FF":"Magenta","F653A6":"Magenta (Crayola)","CA1F7B":"Magenta (dye)","D0417E":"Magenta (Pantone)","FF0090":"Magenta (process)","9F4576":"Magenta haze","AAF0D1":"Magic mint","F8F4FF":"Magnolia","C04000":"Mahogany","FBEC5D":"Maize","F2C649":"Maize (Crayola)","6050DC":"Majorelle blue","0BDA51":"Malachite","979AAA":"Manatee","F37A48":"Mandarin","FDBE02":"Mango","FF8243":"Mango Tango","74C365":"Mantis",
"880085":"Mardi Gras","EAA221":"Marigold","C32148":"Maroon (Crayola)","800000":"Maroon (web)","B03060":"Maroon (X11)","E0B0FF":"Mauve","915F6D":"Mauve taupe","EF98AA":"Mauvelous","47ABCC":"Maximum blue","30BFBF":"Maximum blue green","ACACE6":"Maximum blue purple","5E8C31":"Maximum green","D9E650":"Maximum green yellow","733380":"Maximum purple","D92121":"Maximum red","A63A79":"Maximum red purple","FAFA37":"Maximum yellow","F2BA49":"Maximum yellow red","4C9141":"May green","73C2FB":"Maya blue","66DDAA":"Medium aquamarine","0000CD":"Medium blue","E2062C":"Medium candy apple red","AF4035":"Medium carmine","F3E5AB":"Medium champagne","BA55D3":"Medium orchid",
"9370DB":"Medium purple","3CB371":"Medium sea green","7B68EE":"Medium slate blue","00FA9A":"Medium spring green","48D1CC":"Medium turquoise","C71585":"Medium violet-red","F8B878":"Mellow apricot","F8DE7E":"Mellow yellow","FEBAAD":"Melon","D3AF37":"Metallic gold","0A7E8C":"Metallic Seaweed","9C7C38":"Metallic Sunburst","E4007C":"Mexican pink","7ED4E6":"Middle blue","8DD9CC":"Middle blue green","8B72BE":"Middle blue purple","8B8680":"Middle grey","4D8C57":"Middle green","ACBF60":"Middle green yellow","D982B5":"Middle purple","E58E73":"Middle red","A55353":"Middle red purple","FFEB00":"Middle yellow","ECB176":"Middle yellow red","702670":"Midnight","191970":"Midnight blue",
"004953":"Midnight green (eagle green)","FFC40C":"Mikado yellow","FFDAE9":"Mimi pink","E3F988":"Mindaro","36747D":"Ming","F5E050":"Minion yellow","3EB489":"Mint","F5FFFA":"Mint cream","98FF98":"Mint green","BBB477":"Misty moss","FFE4E1":"Misty rose","967117":"Mode beige","8DA399":"Morning blue","8A9A5B":"Moss green","30BA8F":"Mountain Meadow","997A8D":"Mountbatten pink","18453B":"MSU green","C54B8C":"Mulberry","C8509B":"Mulberry (Crayola)","FFDB58":"Mustard","317873":"Myrtle green","D65282":"Mystic","AD4379":"Mystic maroon","F6ADC6":"Nadeshiko pink","FADA5E":"Naples yellow","FFDEAD":"Navajo white",
"000080":"Navy blue","1974D2":"Navy blue (Crayola)","4666FF":"Neon blue","39FF14":"Neon green","D7837F":"New York pink","727472":"Nickel","A4DDED":"Non-photo blue","E9FFDB":"Nyanza","4F42B5":"Ocean Blue","48BF91":"Ocean green","CC7722":"Ochre","43302E":"Old burgundy","CFB53B":"Old gold","FDF5E6":"Old lace","796878":"Old lavender","673147":"Old mauve","C08081":"Old rose","848482":"Old silver","808000":"Olive","6B8E23":"Olive Drab (#3)","3C341F":"Olive Drab (#7)","B5B35C":"Olive green","9AB973":"Olivine","353839":"Onyx","A8C3BC":"Opal","B784A7":"Opera mauve",
"FF7F00":"Orange","FF7538":"Orange (Crayola)","FF5800":"Orange (Pantone)","FFA500":"Orange (web)","FF9F00":"Orange peel","FF681F":"Orange-red","FF5349":"Orange-red (Crayola)","FA5B3D":"Orange soda","F5BD1F":"Orange-yellow","F8D568":"Orange-yellow (Crayola)","DA70D6":"Orchid","F2BDCD":"Orchid pink","E29CD2":"Orchid (Crayola)","2D383A":"Outer space (Crayola)","FF6E4A":"Outrageous Orange","800020":"Oxblood","002147":"Oxford blue","841617":"OU Crimson red","1CA9C9":"Pacific blue","006600":"Pakistan green","682860":"Palatinate purple","BCD4E6":"Pale aqua","9BC4E2":"Pale cerulean","FADADD":"Pale pink","FAE6FA":"Pale purple (Pantone)","C9C0BB":"Pale silver",
"ECEBBD":"Pale spring bud","78184A":"Pansy purple","009B7D":"Paolo Veronese green","FFEFD5":"Papaya whip","E63E62":"Paradise pink","50C878":"Paris Green","DEA5A4":"Pastel pink","800080":"Patriarch","536878":"Payne's grey","FFE5B4":"Peach","FFCBA4":"Peach (Crayola)","FFDAB9":"Peach puff","D1E231":"Pear","B768A2":"Pearly purple","CCCCFF":"Periwinkle","C3CDE6":"Periwinkle (Crayola)","E12C2C":"Permanent Geranium Lake","1C39BB":"Persian blue","00A693":"Persian green","32127A":"Persian indigo","D99058":"Persian orange","F77FBE":"Persian pink","701C1C":"Persian plum","CC3333":"Persian red","FE28A2":"Persian rose","EC5800":"Persimmon",
"8BA8B7":"Pewter Blue","DF00FF":"Phlox","000F89":"Phthalo blue","123524":"Phthalo green","2E2787":"Picotee blue","C30B4E":"Pictorial carmine","FDDDE6":"Piggy pink","01796F":"Pine green","2A2F23":"Pine tree","FFC0CB":"Pink","D74894":"Pink (Pantone)","FC74FD":"Pink flamingo","FFDDF4":"Pink lace","D8B2D1":"Pink lavender","F78FA7":"Pink Sherbet","93C572":"Pistachio","E5E4E2":"Platinum","8E4585":"Plum","DDA0DD":"Plum (web)","5946B2":"Plump Purple","5DA493":"Polished Pine","86608E":"Pomp and Power","BE4F62":"Popstar","FF5A36":"Portland Orange","B0E0E6":"Powder blue","F58025":"Princeton orange",
"701C1C":"Prune","003153":"Prussian blue","DF00FF":"Psychedelic purple","CC8899":"Puce","644117":"Pullman Brown (UPS Brown)","FF7518":"Pumpkin","6A0DAD":"Purple","800080":"Purple (web)","9F00C5":"Purple (Munsell)","A020F0":"Purple (X11)","9678B6":"Purple mountain majesty","4E5180":"Purple navy","FE4EDA":"Purple pizzazz","9C51B6":"Purple Plum","9A4EAE":"Purpureus","436B95":"Queen blue","E8CCD7":"Queen pink","A6A6A6":"Quick Silver","8E3A59":"Quinacridone magenta","FF355E":"Radical Red","242124":"Raisin black","FBAB60":"Rajah","E30B5D":"Raspberry","915F6D":"Raspberry glace","B3446C":"Raspberry rose","D68A59":"Raw Sienna",
"826644":"Raw umber","FF33CC":"Razzle dazzle rose","E3256B":"Razzmatazz","8D4E85":"Razzmic Berry","663399":"Rebecca Purple","FF0000":"Red","EE204D":"Red (Crayola)","F2003C":"Red (Munsell)","C40233":"Red (NCS)","ED2939":"Red (Pantone)","ED1C24":"Red (pigment)","FE2712":"Red (RYB)","FF5349":"Red-orange","FF681F":"Red-orange (Crayola)","FF4500":"Red-orange (Color wheel)","E40078":"Red-purple","FD3A4A":"Red Salsa","C71585":"Red-violet","C0448F":"Red-violet (Crayola)","922B3E":"Red-violet (Color wheel)","A45A52":"Redwood","002387":"Resolution blue","777696":"Rhythm","004040":"Rich black","010B13":"Rich black (FOGRA29)","010203":"Rich black (FOGRA39)",
"444C38":"Rifle green","00CCCC":"Robin egg blue","8A7F80":"Rocket metallic","838996":"Roman silver","FF007F":"Rose","F9429E":"Rose bonbon","9E5E6F":"Rose Dust","674846":"Rose ebony","E32636":"Rose madder","FF66CC":"Rose pink","AA98A9":"Rose quartz","C21E56":"Rose red","905D5D":"Rose taupe","AB4E52":"Rose vale","65000B":"Rosewood","D40000":"Rosso corsa","BC8F8F":"Rosy brown","002366":"Royal blue (dark)","4169E1":"Royal blue (light)","7851A9":"Royal purple","FADA5E":"Royal yellow","CE4676":"Ruber","D10056":"Rubine red","E0115F":"Ruby","9B111E":"Ruby red","A81C07":"Rufous",
"80461B":"Russet","679267":"Russian green","32174D":"Russian violet","B7410E":"Rust","DA2C43":"Rusty red","043927":"Sacramento State green","8B4513":"Saddle brown","FF7800":"Safety orange","FF6700":"Safety orange (blaze orange)","EED202":"Safety yellow","F4C430":"Saffron","BCB88A":"Sage","23297A":"St. Patrick's blue","FA8072":"Salmon","FF91A4":"Salmon pink","C2B280":"Sand","967117":"Sand dune","F4A460":"Sandy brown","507D2A":"Sap green","0F52BA":"Sapphire","0067A5":"Sapphire blue","0067A5":"Sapphire (Crayola)","CBA135":"Satin sheen gold","FF2400":"Scarlet","FF91AF":"Schauss pink","FFD800":"School bus yellow",
"66FF66":"Screamin' Green","2E8B57":"Sea green","00FFCD":"Sea green (Crayola)","59260B":"Seal brown","FFF5EE":"Seashell","FFBA00":"Selective yellow","704214":"Sepia","8A795D":"Shadow","778BA5":"Shadow blue","009E60":"Shamrock green","8FD400":"Sheen green","D98695":"Shimmering Blush","5FA778":"Shiny Shamrock","FC0FC0":"Shocking pink","FF6FFF":"Shocking pink (Crayola)","882D17":"Sienna","C0C0C0":"Silver","C9C0BB":"Silver (Crayola)","AAA9AD":"Silver (Metallic)","ACACAC":"Silver chalice","C4AEAD":"Silver pink","BFC1C2":"Silver sand","CB410B":"Sinopia","FF3855":"Sizzling Red","FFDB00":"Sizzling Sunrise","007474":"Skobeloff",
"87CEEB":"Sky blue","76D7EA":"Sky blue (Crayola)","CF71AF":"Sky magenta","6A5ACD":"Slate blue","708090":"Slate gray","299617":"Slimy green","C84186":"Smitten","100C08":"Smoky black","FFFAFA":"Snow","893843":"Solid pink","757575":"Sonic silver","1D2951":"Space cadet","807532":"Spanish bistre","0070B8":"Spanish blue","D10047":"Spanish carmine","989898":"Spanish gray","009150":"Spanish green","E86100":"Spanish orange","F7BFBE":"Spanish pink","E60026":"Spanish red","00FFFF":"Spanish sky blue","4C2882":"Spanish violet","007F5C":"Spanish viridian","A7FC00":"Spring bud","87FF2A":"Spring Frost","00FF7F":"Spring green",
"ECEBBD":"Spring green (Crayola)","007BB8":"Star command blue","4682B4":"Steel blue","CC33CC":"Steel pink","5F8A8B":"Steel Teal","FADA5E":"Stil de grain yellow","E4D96F":"Straw","914E75":"Sugar Plum","FFCC33":"Sunglow","E3AB57":"Sunray","FAD6A5":"Sunset","CF6BA9":"Super pink","A83731":"Sweet Brown","D2B48C":"Tan","D99A6C":"Tan (Crayola)","F28500":"Tangerine","E4717A":"Tango pink","FB4D46":"Tart Orange","483C32":"Taupe","8B8589":"Taupe gray","D0F0C0":"Tea green","F88379":"Tea rose","F4C2C2":"Tea rose","008080":"Teal","367588":"Teal blue","CF3476":"Telemagenta",
"CD5700":"Tenné (tawny)","E2725B":"Terra cotta","D8BFD8":"Thistle","DE6FA1":"Thulian pink","FC89AC":"Tickle Me Pink","0ABAB5":"Tiffany Blue","DBD7D2":"Timberwolf","EEE600":"Titanium yellow","FF6347":"Tomato","00755E":"Tropical rain forest","2D68C4":"True Blue","1C05B3":"Trypan Blue","3E8EDE":"Tufts blue","DEAA88":"Tumbleweed","40E0D0":"Turquoise","00FFEF":"Turquoise blue","A0D6B4":"Turquoise green","8A9A5B":"Turtle green","FAD6A5":"Tuscan","6F4E37":"Tuscan brown","7C4848":"Tuscan red","A67B5B":"Tuscan tan","C09999":"Tuscany","8A496B":"Twilight lavender","66023C":"Tyrian purple","0033AA":"UA blue",
"D9004C":"UA red","3F00FF":"Ultramarine","4166F5":"Ultramarine blue","FF6FFF":"Ultra pink","FC6C85":"Ultra red","635147":"Umber","FFDDCA":"Unbleached silk","5B92E5":"United Nations blue","FFFF66":"Unmellow yellow","014421":"UP Forest green","7B1113":"UP maroon","AE2029":"Upsdell red","AFDBF5":"Uranian blue","004F98":"USAFA blue","664228":"Van Dyke brown","F3E5AB":"Vanilla","F38FA9":"Vanilla ice","C5B358":"Vegas gold","C80815":"Venetian red","43B3AE":"Verdigris","E34234":"Vermilion","D9381E":"Vermilion","A020F0":"Veronica","8F00FF":"Violet","7F00FF":"Violet (color wheel)","963D7F":"Violet (crayola)",
"8601AF":"Violet (RYB)","EE82EE":"Violet (web)","324AB2":"Violet-blue","766EC8":"Violet-blue (Crayola)","F75394":"Violet-red","40826D":"Viridian","009698":"Viridian green","9F1D35":"Vivid burgundy","00CCFF":"Vivid sky blue","FFA089":"Vivid tangerine","9F00FF":"Vivid violet","CEFF00":"Volt","004242":"Warm black","F5DEB3":"Wheat","FFFFFF":"White","A2ADD0":"Wild blue yonder","D470A2":"Wild orchid","FF43A4":"Wild Strawberry","FC6C85":"Wild watermelon","A75502":"Windsor tan","722F37":"Wine","673147":"Wine dregs","FF007C":"Winter Sky","56887D":"Wintergreen Dream","C9A0DC":"Wisteria","C19A6B":"Wood brown",
"EEED09":"Xanthic","738678":"Xanadu","0C020F":"Xiketic","0F4D92":"Yale Blue","FFFF00":"Yellow","FCE883":"Yellow (Crayola)","EFCC00":"Yellow (Munsell)","FFD300":"Yellow (NCS)","FEDF00":"Yellow (Pantone)","FFEF00":"Yellow (process)","FEFE33":"Yellow (RYB)","9ACD32":"Yellow-green","C5E384":"Yellow-green (Crayola)","30B21A":"Yellow-green (Color Wheel)","FFAE42":"Yellow Orange","FF9505":"Yellow Orange (Color Wheel)","FFF700":"Yellow Sunshine","2E5090":"YInMn Blue","0014A8":"Zaffre","39A78E":"Zomp"}
families_dict = { "white":0, "grey":0, "black":0, "red":0, "warm red":0, "orange":0, "warm yellow":0, "yellow":0, "cool yellow":0, "yellow green":0,
"warm green":0, "green":0, "cool green":0, "green cyan":0, "warm cyan":0, "cyan":0, "cool cyan":0, "blue cyan":0, "cool blue":0,
"blue":0, "warm blue":0, "violet":0, "cool magenta":0, "magenta":0, "warm magenta":0, "red magenta":0, "cool red":0}
hex_rgb_colors = list(colors_dict.keys())
plt.style.use("fivethirtyeight")
def HEX2RGB(color):
color = color.lstrip('#')
lv = len(color)
return tuple(int(color[i:i + lv // 3], 16) for i in range(0, lv, lv//3))
def RGB2HSV(color):
r, g, b = HEX2RGB(color)
# Convert RGB values to percentages
r = r / 255
g = g / 255
b = b / 255
# calculate a few basic values; the max of r, g, b,
# the min value, and the difference between the two (chroma)
maxRGB = max(r, g, b)
minRGB = min(r, g, b)
chroma = maxRGB - minRGB
# value (brightness) is easiest to calculate,
# it's simply the highest value among the r, g, b components
# multiply by 100 to turn the decimal into a percent
computedValue = 100 * maxRGB
# there's a special case for hueless (equal parts RGB make black, white, or grey)
# note that hue is technically undefined when chroma is 0
# as attempting to calc it would simply cause a division by 0 error, so most applications
# simply sub a hue of 0
# Saturation will always be 0 in this case
if chroma == 0:
return 0, 0, computedValue
# Saturation is also simple to compute, as it is chroma/value
computedSaturation = 100 * (chroma/maxRGB)
# Calculate hue
# Hue is calculated via "chromacity" represented as a 2D hexagon, divided into six 60-deg sectors
# we calculate the bisecting angle as a value 0 <= x < 6, which represents which protion
# of the sector the line falls on
if r == minRGB:
h = 3 - ((g - b) / chroma)
elif b == minRGB:
h = 1 - ((r - g) / chroma)
else:
h = 5 - ((b - r) / chroma)
# After we have each sector position, we multiply it by the size of each sector's arc to obtain the angle in degrees
computedHue = 60 * h
return computedHue, computedSaturation, computedValue
def determinedColorFamily(hue, sat, val):
if hue == 0 and sat == 0:
if val >= 95:
families_dict["white"] += 1
return "white"
elif 15 <= val < 95:
families_dict["grey"] += 1
return "grey"
else:
families_dict["black"] += 1
return "black"
elif 0 <= val < 15:
families_dict["black"] += 1
return "black"
elif 99 <= val <= 100 and 0 <= sat < 5:
families_dict["white"] += 1
return "white"
elif 5 <= sat <= 100:
if 0 <= hue < 15:
families_dict["red"] += 1
return "red"
elif 15 <= hue < 30:
families_dict["warm red"] += 1
return "warm red"
elif 30 <= hue < 45:
families_dict["orange"] += 1
return "orange"
elif 45 <= hue < 60:
families_dict["warm yellow"] += 1
return "warm yellow"
elif 60 <= hue < 75:
families_dict["yellow"] += 1
return "yellow"
elif 75 <= hue < 90:
families_dict["cool yellow"] += 1
return "cool yellow"
elif 90 <= hue < 105:
families_dict["yellow green"] += 1
return "yellow green"
elif 105 <= hue < 120:
families_dict["warm green"] += 1
return "warm green"
elif 120 <= hue < 135:
families_dict["green"] += 1
return "green"
elif 135 <= hue < 150:
families_dict["cool green"] += 1
return "cool green"
elif 150 <= hue < 165:
families_dict["green cyan"] += 1
return "green cyan"
elif 165 <= hue < 180:
families_dict["warm cyan"] += 1
return "warm cyan"
elif 180 <= hue < 195:
families_dict["cyan"] += 1
return "cyan"
elif 195 <= hue < 210:
families_dict["cool cyan"] += 1
return "cool cyan"
elif 210 <= hue < 225:
families_dict["blue cyan"] += 1
return "blue cyan"
elif 225 <= hue < 240:
families_dict["cool blue"] += 1
return "cool blue"
elif 240 <= hue < 255:
families_dict["blue"] += 1
return "blue"
elif 255 <= hue < 270:
families_dict["warm blue"] += 1
return "warm blue"
elif 270 <= hue < 285:
families_dict["violet"] += 1
return "violet"
elif 285 <= hue < 300:
families_dict["cool magenta"] += 1
return "cool magenta"
elif 300 <= hue < 315:
families_dict["magenta"] += 1
return "magenta"
elif 315 <= hue < 330:
families_dict["warm magenta"] += 1
return "warm magenta"
elif 330 <= hue < 345:
families_dict["red magenta"] += 1
return "red magenta"
elif 345 <= hue <= 360:
families_dict["cool red"] += 1
return "cool red"
elif 0 <= sat < 5:
families_dict["grey"] += 1
return "grey"
def Peak(peaked_color, fname):
r = [int(hex[0:2], 16) for hex in hex_rgb_colors] # Red elements
g = [int(hex[2:4], 16) for hex in hex_rgb_colors] # Green elements
b = [int(hex[4:6], 16) for hex in hex_rgb_colors] # Blue elements
r = np.asarray(r, np.uint8)
g = np.asarray(g, np.uint8)
b = np.asarray(b, np.uint8)
rgb = np.dstack((r, g, b))
lab = rgb2lab(rgb)
peaked_rgb = np.asarray([int(peaked_color[1:3], 16), int(peaked_color[3:5], 16,), int(peaked_color[5:7], 16)], np.uint8)
peaked_rgb = np.dstack((peaked_rgb[0], peaked_rgb[1], peaked_rgb[2]))
peaked_lab = rgb2lab(peaked_rgb)
# Compute Euclidean distance
lab_dist = ((lab[:,:,0] - peaked_lab[:,:,0])**2 + (lab[:,:,1] - peaked_lab[:,:,1])**2 + (lab[:,:,2] - peaked_lab[:,:,2])**2)**0.5
# Get index of min distance
min_index = lab_dist.argmin()
# Get the hex string of the color with the minimum Euclidean distance
peaked_closest_hex = hex_rgb_colors[min_index]
# Get the color name from the dictionary
peaked_color_name = colors_dict[peaked_closest_hex]
peaked_color_rgb = HEX2RGB(peaked_color)
closest_match = HEX2RGB(list(colors_dict.keys())[list(colors_dict.values()).index(peaked_color_name)])
print(f"Peaked color name: {peaked_color_name}")
h, s, v = RGB2HSV(peaked_closest_hex)
print(f"The top color is {peaked_color_name}. Its HSV is {h}, {s}, {v}.")
colorFamily = determinedColorFamily(h, s, v)
print(f"The determined color family of {peaked_color_name} is {colorFamily}")
print(f"R: {peaked_color_rgb[0]}, G: {peaked_color_rgb[1]}, B: {peaked_color_rgb[2]}")
print(f"R: {closest_match[0]}, G: {closest_match[1]}, B: {closest_match[2]}")
fig, ax = plt.subplots(nrows=1, ncols=2)
Z = np.vstack([peaked_color_rgb[0], peaked_color_rgb[1], peaked_color_rgb[2]])
Y = np.vstack([closest_match[0], closest_match[1], closest_match[2]])
ax[0].set_title(f'Color from image: {peaked_color_rgb[0]},{peaked_color_rgb[1]},{peaked_color_rgb[2]}', fontsize=12)
ax[0].imshow(np.dstack(Z), interpolation = 'none', aspect = 'auto')
ax[1].set_title(f'Color matched to {closest_match[0]},{closest_match[1]},{closest_match[2]}', fontsize=12)
ax[1].imshow(np.dstack(Y), interpolation = 'none', aspect = 'auto')
fig.suptitle(f"Peaked color name: {peaked_color_name}", fontsize=16)
ax[0].axis('off')
ax[0].grid(b=None)
ax[1].axis('off')
ax[1].grid(b=None)
plt.savefig(f"./analyzed2/peaks/{fname}.jpg")
plt.close()
# Prints an RGB color in its hex form
def RGB2HEX(color):
return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))
def get_image(image_path):
image = cv2.imread(image_path)
# By default, OpenCV reads image sequence as BGR.
# To view the actual image we need to convert to RGB.
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
return image
def get_colors(image, ncolors, fname):
# Resizing images to lessen pixel count, which reduces the time needed to extract
# colors from image.
modified_image = cv2.resize(image, (600, 400), interpolation = cv2.INTER_AREA)
modified_image = modified_image.reshape(modified_image.shape[0] * modified_image.shape[1], 3)
clf = KMeans(n_clusters = ncolors)
labels = clf.fit_predict(modified_image)
counts = Counter(labels)
center_colors = clf.cluster_centers_
ordered_colors = [center_colors[i] for i in counts.keys()]
hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]
rgb_colors = [ordered_colors[i] for i in counts.keys()]
dictionary = dict(zip(hex_colors, counts.values()))
dictionary = dict(sorted(dictionary.items(), key = operator.itemgetter(1), reverse = True))
for k, v in dictionary.items():
print(f"Color: {k}; Count: {v}")
hexes = list(dictionary.keys())
Peak(hexes[0], fname)
plt.figure(figsize = (8, 6))
plt.pie(counts.values(), labels=hex_colors, colors = hex_colors)
plt.savefig(f"./analyzed2/piecharts/{fname}.jpg")
plt.close()
return rgb_colors
def main():
i = 0
print(os.getcwd())
for filename in os.listdir(image_data_directory):
if filename.endswith(".jpg"):
image = get_image(f'{image_data_directory}/{filename}')
print("------------------------------")
print(f"Input image: {filename}")
print(f"Shape: {image.shape}")
get_colors(image, 10, i)
print("------------------------------")
i+=1
f = open("data.txt", "w")
f.write(str(families_dict))
f.close()
names = list(families_dict.keys())
values = list(families_dict.values())
colors = [(1, 1, 1, 1),
(0.5, 0.5, 0.5, 1),
(0, 0, 0, 1),
(0.941, 0, 0, 1),
(1, 0.26, 0, 1),
(0.969, 0.506, 0, 1),
(0.988, 0.757, 0.02, 1),
(0.996, 1, 0.043, 1),
(0.757, 1, 0, 1),
(0.475, 0.992, 0, 1),
(0.231, 1, 0.02, 1),
(0, 1, 0, 1),
(0, 0.953, 0.239, 1),
(0, 1, 0.506, 1),
(0.024, 1, 0.78, 1),
(0, 0.984, 1, 1),
(0.047, 0.749, 1, 1),
(0, 0.506, 0.961, 1),
(0, 0.263, 0.98, 1),
(0, 0, 1, 1),
(0.255, 0, 0.976, 1),
(0.518, 0, 0.976, 1),
(0.757, 0, 0.957, 1),
(1, 0, 1, 1),
(0.988, 0, 0.733, 1),
(0.988, 0, 0.482, 1),
(0.957, 0, 0.243, 1)]
plt.figure(figsize = (15, 8))
for i in range(len(names)):
plt.bar(i, values[i], tick_label = names[i], color = colors[i], edgecolor = "black")
plt.title("Total number of color schemes that fall into broad color family categories (n = 451)")
plt.xticks(range(len(names)), names, rotation = 45, fontsize = 8)
plt.yticks(fontsize = 8)
ax = plt.gca()
ax.xaxis.grid(True)
ax.yaxis.set_major_locator(MaxNLocator(integer = True))
plt.tight_layout()
plt.savefig("./analyzed2/final_analysis.jpg")
main() | 90.704961 | 679 | 0.649108 |
3bb6adc6277385da20ad1271935be06ff445012a | 7,812 | py | Python | samples/vsphere/contentlibrary/vmtemplate/check_out_vm_template_workflow.py | JKraftman/vsphere-automation-sdk-python | ccc83aa7124fd9aed26ee88ccc16d01adc8af7db | [
"MIT"
] | 589 | 2017-03-09T19:01:22.000Z | 2022-03-23T08:18:32.000Z | samples/vsphere/contentlibrary/vmtemplate/check_out_vm_template_workflow.py | JKraftman/vsphere-automation-sdk-python | ccc83aa7124fd9aed26ee88ccc16d01adc8af7db | [
"MIT"
] | 244 | 2017-03-09T19:37:36.000Z | 2022-03-29T07:14:21.000Z | samples/vsphere/contentlibrary/vmtemplate/check_out_vm_template_workflow.py | JKraftman/vsphere-automation-sdk-python | ccc83aa7124fd9aed26ee88ccc16d01adc8af7db | [
"MIT"
] | 304 | 2017-03-09T19:15:01.000Z | 2022-03-31T04:26:59.000Z | #!/usr/bin/env python
"""
* *******************************************************
* Copyright VMware, Inc. 2019. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""
__author__ = 'VMware, Inc.'
__vcenter_version__ = '7.0.0+'
from pyVmomi import vim
from com.vmware.vcenter.vm_template.library_items_client import CheckOuts
from com.vmware.vcenter.vm_template.library_items_client import Versions
from vmware.vapi.vsphere.client import create_vsphere_client
from samples.vsphere.common.id_generator import rand
from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.ssl_helper import get_unverified_session
from samples.vsphere.common.vim.helpers.vim_utils import get_obj_by_moId
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
from samples.vsphere.vcenter.helper.resource_pool_helper import (
get_resource_pool)
class CheckOutVmTemplateWorkflow(SampleBase):
"""
Demonstrates how to check out a VM from a library item containing a virtual
machine template, check in the VM checked out from the item, and rollback
the item to a previous version.
Prerequisites:
- A library item containing a virtual machine template
- A resource pool
- A datacenter
"""
def __init__(self):
SampleBase.__init__(self, self.__doc__)
self.servicemanager = None
self.client = None
self.helper = None
self.item_name = None
self.vm_name = None
self.datacenter_name = None
self.resource_pool_name = None
def _options(self):
self.argparser.add_argument('-itemname', '--itemname',
required=True,
help='The name of the library item '
'containing the VM template '
'to be checked out')
self.argparser.add_argument('-datacentername', '--datacentername',
required=True,
help='The name of the datacenter in which '
'to check out the VM')
self.argparser.add_argument('-resourcepoolname', '--resourcepoolname',
required=True,
help='The name of the resource pool in '
'the datacenter in which to place '
'the VM')
self.argparser.add_argument('-vmname', '--vmname',
help='The name of the VM to check out of '
'the library item')
def _setup(self):
# Required arguments
self.datacenter_name = self.args.datacentername
self.resource_pool_name = self.args.resourcepoolname
self.item_name = self.args.itemname
# Optional arguments
self.vm_name = (self.args.vmname if self.args.vmname
else rand('checked-out-vm-'))
self.servicemanager = self.get_service_manager()
self.client = ClsApiClient(self.servicemanager)
self.helper = ClsApiHelper(self.client, self.skip_verification)
session = get_unverified_session() if self.skip_verification else None
self.vsphere_client = create_vsphere_client(server=self.server,
username=self.username,
password=self.password,
session=session)
def _execute(self):
# Get the identifiers
item_id = self.helper.get_item_id_by_name(self.item_name)
assert item_id
resource_pool_id = get_resource_pool(self.vsphere_client,
self.datacenter_name,
self.resource_pool_name)
assert resource_pool_id
version_before_check_out = self.client.library_item_service.get(
item_id).content_version
self.print_live_versions(item_id)
# Build the check out spec
check_out_spec = CheckOuts.CheckOutSpec()
placement_spec = CheckOuts.PlacementSpec()
placement_spec.resource_pool = resource_pool_id
check_out_spec.placement = placement_spec
check_out_spec.name = self.vm_name
# Check out VM from item
vm_id = self.client.check_outs_service.check_out(item_id,
check_out_spec)
print("VM (ID: {}) checked out from item".format(vm_id))
# Get library id associated with checked out VM
info = self.vsphere_client.vcenter.vm.LibraryItem.get(
vm_id)
assert info.check_out
print("Library item associated with checked out VM is {}".format(
info.check_out.library_item))
# Check in VM into the library item
check_in_spec = CheckOuts.CheckInSpec()
check_in_spec.message = "Check in message"
version_after_check_in = self.client.check_outs_service.check_in(
item_id, vm_id, check_in_spec)
print("VM (ID: {}) checked into item {}".format(vm_id, item_id))
self.print_live_versions(item_id)
# Rollback to previous version
rollback_message = "Rollback to v{}".format(version_before_check_out)
rollback_spec = Versions.RollbackSpec(rollback_message)
version_after_rollback = self.client.versions_service.rollback(
item_id, version_before_check_out, rollback_spec)
print("Item rolled back to version {}. New item version is {}".format(
version_before_check_out, version_after_rollback))
self.print_live_versions(item_id)
# Delete previous version
self.client.versions_service.delete(item_id, version_after_check_in)
print("Deleted version {} of item".format(version_after_check_in))
self.print_live_versions(item_id)
self.print_change_history(item_id)
def print_live_versions(self, item_id):
# Get and print live versions of the VM template item
versions_info = self.client.versions_service.list(item_id)
print("Live versions of VM template item:")
for version_info in versions_info:
vm_template = get_obj_by_moId(self.servicemanager.content,
[vim.VirtualMachine],
version_info.vm_template)
print("Version: {}, VM template name: {}".format(
version_info.version, vm_template.name))
def print_change_history(self, item_id):
# Get and print change history of the VM template item
changes_summary = self.client.changes_service.list(item_id)
print("Change history of VM template item:")
for change_summary in changes_summary:
print("Change version: {}, Time: {}, User: {}, Message: {}".format(
change_summary.version, change_summary.time,
change_summary.user, change_summary.short_message))
def main():
check_out_workflow_sample = CheckOutVmTemplateWorkflow()
check_out_workflow_sample.main()
if __name__ == '__main__':
main()
| 42.923077 | 79 | 0.619304 |
39d1a3d06e6db8addb879c1388a78f5668398466 | 12,219 | py | Python | test/functional/mining_basic.py | Cminor-pools/bitcoinvg | d47a3cf13e06f4fe03d965826f5309e6d5706470 | [
"MIT"
] | null | null | null | test/functional/mining_basic.py | Cminor-pools/bitcoinvg | d47a3cf13e06f4fe03d965826f5309e6d5706470 | [
"MIT"
] | null | null | null | test/functional/mining_basic.py | Cminor-pools/bitcoinvg | d47a3cf13e06f4fe03d965826f5309e6d5706470 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2014-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mining RPCs
- getmininginfo
- getblocktemplate proposal mode
- submitblock"""
import copy
from decimal import Decimal
from test_framework.blocktools import (
create_coinbase,
NORMAL_GBT_REQUEST_PARAMS,
TIME_GENESIS_BLOCK,
)
from test_framework.messages import (
CBlock,
CBlockHeader,
BLOCK_HEADER_SIZE,
)
from test_framework.p2p import P2PDataStore
from test_framework.test_framework import BitcoinVGTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
)
VERSIONBITS_TOP_BITS = 0x20000000
VERSIONBITS_DEPLOYMENT_TESTDUMMY_BIT = 28
def assert_template(node, block, expect, rehash=True):
if rehash:
block.hashMerkleRoot = block.calc_merkle_root()
rsp = node.getblocktemplate(template_request={
'data': block.serialize().hex(),
'mode': 'proposal',
'rules': ['segwit'],
})
assert_equal(rsp, expect)
class MiningTest(BitcoinVGTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.supports_cli = False
def mine_chain(self):
self.log.info('Create some old blocks')
for t in range(TIME_GENESIS_BLOCK, TIME_GENESIS_BLOCK + 200 * 600, 600):
self.nodes[0].setmocktime(t)
self.nodes[0].generate(1)
mining_info = self.nodes[0].getmininginfo()
assert_equal(mining_info['blocks'], 200)
assert_equal(mining_info['currentblocktx'], 0)
assert_equal(mining_info['currentblockweight'], 4000)
self.log.info('test blockversion')
self.restart_node(0, extra_args=['-mocktime={}'.format(t), '-blockversion=1337'])
self.connect_nodes(0, 1)
assert_equal(1337, self.nodes[0].getblocktemplate(NORMAL_GBT_REQUEST_PARAMS)['version'])
self.restart_node(0, extra_args=['-mocktime={}'.format(t)])
self.connect_nodes(0, 1)
assert_equal(VERSIONBITS_TOP_BITS + (1 << VERSIONBITS_DEPLOYMENT_TESTDUMMY_BIT), self.nodes[0].getblocktemplate(NORMAL_GBT_REQUEST_PARAMS)['version'])
self.restart_node(0)
self.connect_nodes(0, 1)
def run_test(self):
self.mine_chain()
node = self.nodes[0]
def assert_submitblock(block, result_str_1, result_str_2=None):
block.solve()
result_str_2 = result_str_2 or 'duplicate-invalid'
assert_equal(result_str_1, node.submitblock(hexdata=block.serialize().hex()))
assert_equal(result_str_2, node.submitblock(hexdata=block.serialize().hex()))
self.log.info('getmininginfo')
mining_info = node.getmininginfo()
assert_equal(mining_info['blocks'], 200)
assert_equal(mining_info['chain'], self.chain)
assert 'currentblocktx' not in mining_info
assert 'currentblockweight' not in mining_info
assert_equal(mining_info['difficulty'], Decimal('4.656542373906925E-10'))
assert_equal(mining_info['networkhashps'], Decimal('0.003333333333333334'))
assert_equal(mining_info['pooledtx'], 0)
# Mine a block to leave initial block download
node.generatetoaddress(1, node.get_deterministic_priv_key().address)
tmpl = node.getblocktemplate(NORMAL_GBT_REQUEST_PARAMS)
self.log.info("getblocktemplate: Test capability advertised")
assert 'proposal' in tmpl['capabilities']
assert 'coinbasetxn' not in tmpl
next_height = int(tmpl["height"])
coinbase_tx = create_coinbase(height=next_height)
# sequence numbers must not be max for nLockTime to have effect
coinbase_tx.vin[0].nSequence = 2**32 - 2
coinbase_tx.rehash()
block = CBlock()
block.nVersion = tmpl["version"]
block.hashPrevBlock = int(tmpl["previousblockhash"], 16)
block.nTime = tmpl["curtime"]
block.nBits = int(tmpl["bits"], 16)
block.nNonce = 0
block.vtx = [coinbase_tx]
self.log.info("getblocktemplate: segwit rule must be set")
assert_raises_rpc_error(-8, "getblocktemplate must be called with the segwit rule set", node.getblocktemplate)
self.log.info("getblocktemplate: Test valid block")
assert_template(node, block, None)
self.log.info("submitblock: Test block decode failure")
assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, block.serialize()[:-15].hex())
self.log.info("getblocktemplate: Test bad input hash for coinbase transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx[0].vin[0].prevout.hash += 1
bad_block.vtx[0].rehash()
assert_template(node, bad_block, 'bad-cb-missing')
self.log.info("submitblock: Test invalid coinbase transaction")
assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, bad_block.serialize().hex())
self.log.info("getblocktemplate: Test truncated final transaction")
assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {
'data': block.serialize()[:-1].hex(),
'mode': 'proposal',
'rules': ['segwit'],
})
self.log.info("getblocktemplate: Test duplicate transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx.append(bad_block.vtx[0])
assert_template(node, bad_block, 'bad-txns-duplicate')
assert_submitblock(bad_block, 'bad-txns-duplicate', 'bad-txns-duplicate')
self.log.info("getblocktemplate: Test invalid transaction")
bad_block = copy.deepcopy(block)
bad_tx = copy.deepcopy(bad_block.vtx[0])
bad_tx.vin[0].prevout.hash = 255
bad_tx.rehash()
bad_block.vtx.append(bad_tx)
assert_template(node, bad_block, 'bad-txns-inputs-missingorspent')
assert_submitblock(bad_block, 'bad-txns-inputs-missingorspent')
self.log.info("getblocktemplate: Test nonfinal transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx[0].nLockTime = 2**32 - 1
bad_block.vtx[0].rehash()
assert_template(node, bad_block, 'bad-txns-nonfinal')
assert_submitblock(bad_block, 'bad-txns-nonfinal')
self.log.info("getblocktemplate: Test bad tx count")
# The tx count is immediately after the block header
bad_block_sn = bytearray(block.serialize())
assert_equal(bad_block_sn[BLOCK_HEADER_SIZE], 1)
bad_block_sn[BLOCK_HEADER_SIZE] += 1
assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {
'data': bad_block_sn.hex(),
'mode': 'proposal',
'rules': ['segwit'],
})
self.log.info("getblocktemplate: Test bad bits")
bad_block = copy.deepcopy(block)
bad_block.nBits = 469762303 # impossible in the real world
assert_template(node, bad_block, 'bad-diffbits')
self.log.info("getblocktemplate: Test bad merkle root")
bad_block = copy.deepcopy(block)
bad_block.hashMerkleRoot += 1
assert_template(node, bad_block, 'bad-txnmrklroot', False)
assert_submitblock(bad_block, 'bad-txnmrklroot', 'bad-txnmrklroot')
self.log.info("getblocktemplate: Test bad timestamps")
bad_block = copy.deepcopy(block)
bad_block.nTime = 2**31 - 1
assert_template(node, bad_block, 'time-too-new')
assert_submitblock(bad_block, 'time-too-new', 'time-too-new')
bad_block.nTime = 0
assert_template(node, bad_block, 'time-too-old')
assert_submitblock(bad_block, 'time-too-old', 'time-too-old')
self.log.info("getblocktemplate: Test not best block")
bad_block = copy.deepcopy(block)
bad_block.hashPrevBlock = 123
assert_template(node, bad_block, 'inconclusive-not-best-prevblk')
assert_submitblock(bad_block, 'prev-blk-not-found', 'prev-blk-not-found')
self.log.info('submitheader tests')
assert_raises_rpc_error(-22, 'Block header decode failed', lambda: node.submitheader(hexdata='xx' * BLOCK_HEADER_SIZE))
assert_raises_rpc_error(-22, 'Block header decode failed', lambda: node.submitheader(hexdata='ff' * (BLOCK_HEADER_SIZE-2)))
assert_raises_rpc_error(-25, 'Must submit previous header', lambda: node.submitheader(hexdata=super(CBlock, bad_block).serialize().hex()))
block.nTime += 1
block.solve()
def chain_tip(b_hash, *, status='headers-only', branchlen=1):
return {'hash': b_hash, 'height': 202, 'branchlen': branchlen, 'status': status}
assert chain_tip(block.hash) not in node.getchaintips()
node.submitheader(hexdata=block.serialize().hex())
assert chain_tip(block.hash) in node.getchaintips()
node.submitheader(hexdata=CBlockHeader(block).serialize().hex()) # Noop
assert chain_tip(block.hash) in node.getchaintips()
bad_block_root = copy.deepcopy(block)
bad_block_root.hashMerkleRoot += 2
bad_block_root.solve()
assert chain_tip(bad_block_root.hash) not in node.getchaintips()
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert chain_tip(bad_block_root.hash) in node.getchaintips()
# Should still reject invalid blocks, even if we have the header:
assert_equal(node.submitblock(hexdata=bad_block_root.serialize().hex()), 'bad-txnmrklroot')
assert_equal(node.submitblock(hexdata=bad_block_root.serialize().hex()), 'bad-txnmrklroot')
assert chain_tip(bad_block_root.hash) in node.getchaintips()
# We know the header for this invalid block, so should just return early without error:
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert chain_tip(bad_block_root.hash) in node.getchaintips()
bad_block_lock = copy.deepcopy(block)
bad_block_lock.vtx[0].nLockTime = 2**32 - 1
bad_block_lock.vtx[0].rehash()
bad_block_lock.hashMerkleRoot = bad_block_lock.calc_merkle_root()
bad_block_lock.solve()
assert_equal(node.submitblock(hexdata=bad_block_lock.serialize().hex()), 'bad-txns-nonfinal')
assert_equal(node.submitblock(hexdata=bad_block_lock.serialize().hex()), 'duplicate-invalid')
# Build a "good" block on top of the submitted bad block
bad_block2 = copy.deepcopy(block)
bad_block2.hashPrevBlock = bad_block_lock.sha256
bad_block2.solve()
assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex()))
# Should reject invalid header right away
bad_block_time = copy.deepcopy(block)
bad_block_time.nTime = 1
bad_block_time.solve()
assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader(hexdata=CBlockHeader(bad_block_time).serialize().hex()))
# Should ask for the block from a p2p node, if they announce the header as well:
peer = node.add_p2p_connection(P2PDataStore())
peer.wait_for_getheaders(timeout=5) # Drop the first getheaders
peer.send_blocks_and_test(blocks=[block], node=node)
# Must be active now:
assert chain_tip(block.hash, status='active', branchlen=0) in node.getchaintips()
# Building a few blocks should give the same results
node.generatetoaddress(10, node.get_deterministic_priv_key().address)
assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader(hexdata=CBlockHeader(bad_block_time).serialize().hex()))
assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex()))
node.submitheader(hexdata=CBlockHeader(block).serialize().hex())
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert_equal(node.submitblock(hexdata=block.serialize().hex()), 'duplicate') # valid
if __name__ == '__main__':
MiningTest().main()
| 46.109434 | 158 | 0.684753 |
cb7caa9e7e2ad75ce243a7ba2bf1c3ce3a32bd91 | 13,361 | py | Python | tools/gnc_visualizer/scripts/communications/configuration_support.py | nathantsoi/astrobee | bb0fc3e4110a14929bd4cf35c12b3c169bc6c756 | [
"Apache-2.0"
] | 1 | 2021-11-11T17:13:32.000Z | 2021-11-11T17:13:32.000Z | tools/gnc_visualizer/scripts/communications/configuration_support.py | nathantsoi/astrobee | bb0fc3e4110a14929bd4cf35c12b3c169bc6c756 | [
"Apache-2.0"
] | 4 | 2021-08-01T17:13:15.000Z | 2022-03-31T14:23:03.000Z | tools/gnc_visualizer/scripts/communications/configuration_support.py | nathantsoi/astrobee | bb0fc3e4110a14929bd4cf35c12b3c169bc6c756 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
import xml.dom.minidom as minidom
import socket
import string
import datetime
import ConfigParser
from os import path as osPath
from os import remove
from collections import OrderedDict
filepath = osPath.dirname(osPath.realpath(__file__))
BASE_DDS_PROFILE_FILE=filepath + "/dds_types/BaseDDSProfile.xml"
DDS_PROFILE_FILE=filepath + "/dds_types/CurrentDDSProfile.xml"
CONFIG_FILE=filepath + "/config.ini"
class Preferences:
def __init__(self, partition_name = None, given_peer = None, domain = None, public_ip = None):
self.config = ConfigParser.ConfigParser()
self.dom = None
self.partition_name = partition_name
self.initial_peers = dict()
self.given_peer = given_peer
self.domain = domain
self.public_ip = public_ip
self.err = OrderedDict()
self.warn = OrderedDict()
self.info = OrderedDict()
def is_valid_ipv4(self, ip):
if ip != None and ip.count('.') == 3:
try:
socket.inet_aton(ip)
except socket.error:
pass
else:
return True
return False
def validate_initial_peer(self, peer):
dictionary = dict()
# Check if the given peer is a valid IP
if self.is_valid_ipv4(peer):
dictionary[peer] = peer
return dictionary
self.add_warning("The given peer is NOT a valid IP, valid profiles " +
"will be checked")
# Check if input is a valid profile
for key, value in self.initial_peers.items():
if string.lower(peer) == key:
self.add_warning("The given peer IS a valid profile. IP: " +
value + " will be used.")
dictionary[key] = value
return dictionary
self.add_warning("The given peer is NOT a valid profile, IPs from " +
"config file will be used")
return None
def validate_public_ip(self, ip):
if self.is_valid_ipv4(ip):
return ip
else:
return -1
def get_robot_name(self):
if self.partition_name == None: # Robot name not given at start
self.partition_name = self.config.get('RobotName', 'name')
if self.partition_name.strip() == "":
self.partition_name = None
return self.partition_name
def get_initial_peers(self):
if len(self.initial_peers) == 0:
peers_items = self.config.items('DiscoveryPeers')
for key, ip in peers_items:
if key.strip() != "" and ip.strip() != "" and self.is_valid_ipv4(ip):
self.initial_peers[key] = ip
else:
self.add_warning("There are unvalid profile/IPs in the config file")
if self.given_peer != None: # Robot IP was given at start
validated_peer = self.validate_initial_peer(self.given_peer)
if validated_peer != None:
self.initial_peers.clear()
for key, ip in validated_peer.items():
self.initial_peers[key] = ip
else:
# Valdate functions shows a message explaining the value is
# invalid. We proceed to use peers on config file
pass
self.given_peer = None
return self.initial_peers
def get_domain_id(self):
fallback = False
if self.domain == None: # Domain id not given at start
# Read from config file
self.domain = self.config.get('DdsDomain', 'domain')
self.add_warning("Domain ID will be read from config file")
fallback = True
if not self.domain.strip().isdigit():
self.domain = None
if not fallback:
self.add_warning("Argument Domain ID is not valid, we will " +
"fallback to the value in the configuration file")
self.get_domain_id()
return self.domain
def get_public_ip(self):
returnValue = None
# Get ip from config file and put in a temp variable
tmp_ip = self.config.get('TRek', 'public_ip')
if self.public_ip == None: # IP not given at startup
if tmp_ip == None or tmp_ip == "":
pass # No public IP anywhere, ignore quietly
else:
# Validate config file value
returnValue = self.validate_public_ip(tmp_ip)
else:
returnValue = self.validate_public_ip(self.public_ip)
if returnValue == -1:
returnValue = self.validate_public_ip(tmp_ip)
self.public_ip = returnValue
return self.public_ip
def clear_node_list(self, node_list, sub_tag_name):
peers = node_list.getElementsByTagName(sub_tag_name)
for peer in peers:
node_list.removeChild(peer)
peer.unlink()
def write_node_list(self, node_list, sub_tag_name, children):
children = [children] if isinstance(children, basestring) else children
for child in children:
new_node = node_list.ownerDocument.createElement(sub_tag_name)
new_node.appendChild(new_node.ownerDocument.createTextNode(
children[child] if isinstance(children, dict) else child))
node_list.appendChild(new_node)
def override_node_children(self, node_list, sub_tag_name, children):
self.clear_node_list(node_list, sub_tag_name)
self.write_node_list(node_list, sub_tag_name, children)
def write_xml_file(self, file_out):
self.dom.writexml( open(file_out, 'w'),
indent="",
addindent="",
newl='')
def replace_initial_peers(self):
new_peers = self.get_initial_peers()
if new_peers == None or len(new_peers) == 0:
self.add_error("No valid robot IPs were provided from arguments " +
"neither config file. We cannot continue. Please review your " +
"arguments and/or configuration file")
return False
else:
self.override_node_children(self.dom.getElementsByTagName(
'initial_peers')[0],'element', new_peers)
return True
def replace_partition_name(self):
new_name = self.get_robot_name()
if new_name == None:
self.add_error("Robot name is empty. We cannot continue. " +
"Please review your arguments and/or configuration file")
return False
else:
subscriber_partitions = self.dom.getElementsByTagName(
'domain_participant_library')[0].getElementsByTagName('name')
for sub_part in subscriber_partitions:
self.override_node_children(sub_part, 'element', new_name)
return True
def replace_domain_id(self):
new_domain = self.get_domain_id()
if new_domain == None:
self.add_error("Domain is not valid. No valid domain ids were " +
"found in the arguments or config file")
return False
else:
domain_node = self.dom.getElementsByTagName('domain')[0]
domain_node.attributes["domain_id"].value = new_domain
return True
def insert_public_ip(self):
new_public_ip = self.get_public_ip()
if new_public_ip == None:
return True
elif new_public_ip == -1:
self.add_error("Public IP is not a valid IPv4. We cannot continue." +
" Please review your arguments and/or configuration file")
return False
else:
parents = self.dom.getElementsByTagName('qos_library')
for child in parents:
if child.getAttribute("name") == "RapidQosLibrary":
parent = child.getElementsByTagName('property')[0] \
.getElementsByTagName("value")[0]
node_element = parent.ownerDocument.createElement("element")
n_name = node_element.ownerDocument.createElement("name")
n_name.appendChild(n_name.ownerDocument.createTextNode( \
"dds.transport.UDPv4.builtin.public_address"))
n_value = node_element.ownerDocument.createElement("value")
n_value.appendChild(n_value.ownerDocument \
.createTextNode(new_public_ip))
node_element.appendChild(n_name)
node_element.appendChild(n_value)
sibling_node = None
elements = parent.getElementsByTagName("element")
for element in elements:
if element.getElementsByTagName('name')[0].firstChild.nodeValue \
== "dds.transport.UDPv4.builtin.parent.message_size_max":
sibling_node = element
break
parent.insertBefore(node_element, sibling_node)
break
return True
def add_warning(self, text):
self.warn[str(datetime.datetime.now())] = text
def add_error(self, text):
self.err[str(datetime.datetime.now())] = text
def add_info(self, text):
self.info[str(datetime.datetime.now())] = text
def get_warnings(self):
return self.warn
def get_errors(self):
return self.err
def get_info(self):
return self.info
def get_all_warnings(self):
warnings_text = "\nThe configuration proccess produced the following warnings:\n"
for key, value in self.warn.items():
warnings_text += "\n" + key + " : " + value
warnings_text += "\n ----"
return warnings_text
def get_all_errors(self):
errors_text = "\nThe configuration proccess produced the following errors:\n"
for key, value in self.err.items():
errors_text += "\n" + key + " : " + value
errors_text += "\n ----"
return errors_text
def get_all_info(self):
info_text = "\nResume of configuration process:\n"
for key, value in self.info.items():
info_text += "\n" + key + " : " + value
info_text += "\n ----"
return info_text
def validate_config_file(self):
return (
self.config.sections() and
self.config.has_section("RobotName") and
self.config.has_section("DiscoveryPeers") and
self.config.has_section("DdsDomain") and
self.config.has_section("TRek") and
self.config.has_option("RobotName", "name") and
self.config.options("DiscoveryPeers") and
self.config.has_option("DdsDomain", "domain") and
self.config.has_option("TRek", "public_ip")
)
def destroy_dom(self):
if self.dom != None:
self.dom.unlink()
remove(DDS_PROFILE_FILE)
def set_preferences(self, partition_name = None, given_peer = None,
domain = None, public_ip = None):
# Override preferences with argument values
if partition_name != None:
self.partition_name = partition_name
if given_peer != None:
self.given_peer = given_peer
if domain != None:
self.domain = domain
if public_ip != None:
self.public_ip = public_ip
# Read DDS XML config file
try:
self.dom = minidom.parse(BASE_DDS_PROFILE_FILE)
except Exception as e:
self.add_error("DDS profile was NOT found or is corrupted." +
" We cannot continue.")
self.add_info("Configuration process failed. See warnings and errors")
return False
# Read and validate DDS INI config file
self.config.read(CONFIG_FILE)
if not self.validate_config_file():
self.add_error("""Config file was NOT found or is corrupted.
We cannot continue""")
self.add_info("Configuration process failed. See warnings and errors")
return False
if not (self.replace_initial_peers() and
self.replace_partition_name() and
self.replace_domain_id() and
self.insert_public_ip()):
self.add_error("DDS Profile could not be configured." +
" We cannot continue")
self.add_info("Configuration process failed. See warnings and errors")
return False
self.write_xml_file(DDS_PROFILE_FILE)
info_text = "Configuration process was SUCCESSFUL. Following values" + \
" will be used:" + "\n\nRobot Name: " + self.get_robot_name() + \
"\nInitial Peers:\n"
for key, value in self.get_initial_peers().items():
info_text += " - " + value + "\n"
info_text += "\nDDS Domain ID: " + self.domain
if self.public_ip != None:
info_text += "\nATTENTION: Public IP: " + self.public_ip + "\n"
self.add_info(info_text)
return True
# Usage
#config = Preferences()
#config.set_preferences()
#print config.get_all_warnings()
#print config.get_all_errors()
#print config.get_all_info()
| 37.42577 | 98 | 0.591049 |
405a44e50fc5592ee2096d03f0f43533598a8767 | 72,431 | py | Python | pirates/leveleditor/worldData/Rambleshack.py | itsyaboyrocket/pirates | 6ca1e7d571c670b0d976f65e608235707b5737e3 | [
"BSD-3-Clause"
] | 3 | 2021-02-25T06:38:13.000Z | 2022-03-22T07:00:15.000Z | pirates/leveleditor/worldData/Rambleshack.py | itsyaboyrocket/pirates | 6ca1e7d571c670b0d976f65e608235707b5737e3 | [
"BSD-3-Clause"
] | null | null | null | pirates/leveleditor/worldData/Rambleshack.py | itsyaboyrocket/pirates | 6ca1e7d571c670b0d976f65e608235707b5737e3 | [
"BSD-3-Clause"
] | 1 | 2021-02-25T06:38:17.000Z | 2021-02-25T06:38:17.000Z | # uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.leveleditor.worldData.Rambleshack
from pandac.PandaModules import Point3, VBase3, Vec4, Vec3
objectStruct = {'Locator Links': [], 'Objects': {'1115838800a.3jubutler': {'Type': 'Island', 'Name': 'Rambleshack', 'File': '', 'Environment': 'OpenSky', 'Minimap': False, 'Objects': {'1121212983.08Shochet': {'Type': 'Building Exterior', 'File': 'tutorial_interior_withPit', 'ExtUid': '1159905354.84jubutler', 'Hpr': VBase3(-82.958, 0.0, 0.0), 'Objects': {'1202153999.87kmuller': {'Type': 'Door Locator Node', 'Name': 'door_locator', 'Hpr': VBase3(-179.829, 0.0, 0.0), 'Pos': Point3(-0.498, -4.914, 0.952), 'Scale': VBase3(1.0, 1.0, 1.0), 'TargetUIDs': []}, '1202154001.04kmuller': {'Type': 'Door Locator Node', 'Name': 'door_locator_2', 'Hpr': VBase3(0.0, 0.0, 0.0), 'Pos': Point3(-6.626, 20.947, 1.006), 'Scale': VBase3(1.0, 1.0, 1.0)}}, 'Pos': Point3(-15.216, 12.252, 47.468), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Name': '', 'Color': (0.5, 0.5, 0.5, 1.0), 'Door': 'models/buildings/shanty_guildhall_door', 'Interior': 'models/buildings/interior_tavern_c', 'Model': 'models/buildings/shanty_tavern_exterior', 'SignFrame': 'models/buildings/sign1_shanty_a_frame', 'SignImage': 'models/buildings/sign1_eng_a_icon_storage'}}, '1154414027.23sdnaik': {'Type': 'Locator Node', 'Name': 'portal_exterior_1', 'Hpr': VBase3(0.0, 0.0, 0.0), 'Pos': Point3(-0.365, -5.213, 0.955), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1158178138.25dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(38.251, -0.171, -22.174), 'Pos': Point3(-119.688, -29.579, 33.914), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158178301.77dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(50.952, 1.626, -8.073), 'Pos': Point3(-105.482, -18.303, 41.219), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158178482.34dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(43.228, 2.896, -7.308), 'Pos': Point3(-92.985, -2.876, 43.499), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158178679.34dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(19.132, 3.621, -4.984), 'Pos': Point3(-78.472, 10.573, 45.07), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158178832.82dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(12.488, 1.897, -0.375), 'Pos': Point3(-59.957, 16.919, 46.421), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158179872.54dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(4.689, 0.126, -0.006), 'Pos': Point3(-40.695, 21.197, 46.496), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.4000000059604645, 0.4000000059604645, 0.4000000059604645, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158180177.05dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-147.141, 11.055, -19.283), 'Pos': Point3(26.212, 59.025, 34.729), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158180215.64dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-115.456, -0.098, -19.197), 'Pos': Point3(9.864, 49.791, 40.831), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158180294.83dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-171.432, 12.916, -7.013), 'Pos': Point3(104.41, 98.38, 2.834), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158180399.71dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-169.104, 12.69, -12.226), 'Pos': Point3(84.733, 96.196, 5.48), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158180430.77dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-144.419, 2.959, -23.311), 'Pos': Point3(65.244, 93.403, 9.503), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158180465.4dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-130.534, -0.989, -29.19), 'Pos': Point3(50.502, 83.217, 17.496), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158180513.62dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-137.972, 6.193, -26.774), 'Pos': Point3(39.919, 70.367, 26.755), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158181050.17dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(130.142, 6.409, -8.356), 'Pos': Point3(83.488, -32.107, 32.294), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158181145.4dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(158.398, 5.428, -6.892), 'Pos': Point3(60.489, -1.045, 36.639), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158181200.79dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(124.876, 5.946, -5.365), 'Pos': Point3(71.035, -16.773, 34.644), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.4000000059604645, 0.4000000059604645, 0.4000000059604645, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158181789.25dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(-51.181, -3.602, 1.739), 'Objects': {}, 'Pos': Point3(14.771, 1.952, 45.781), 'Scale': VBase3(1.674, 1.674, 1.674), 'VisSize': '', 'Visual': {'Model': 'models/props/zz_dont_use_rocks_Dk_group_2F'}}, '1158182008.13dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(25.967, 12.018, 17.094), 'Objects': {}, 'Pos': Point3(41.369, -3.636, 38.07), 'Scale': VBase3(1.685, 1.685, 1.685), 'VisSize': '', 'Visual': {'Model': 'models/props/zz_dont_use_rocks_Dk_group_2F'}}, '1158182366.55dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(162.715, 4.028, -11.348), 'Pos': Point3(-3.143, 45.706, 43.839), 'Scale': VBase3(1.459, 1.459, 1.459), 'VisSize': '', 'Visual': {'Model': 'models/props/zz_dont_use_rocks_Dk_group_2F'}}, '1158182417.68dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(92.494, 1.594, -5.938), 'Pos': Point3(84.353, -51.751, 30.174), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158182570.85dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(90.156, 1.965, -8.98), 'Pos': Point3(84.153, -64.697, 28.222), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158182686.93dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(153.234, 2.597, -10.195), 'Pos': Point3(101.233, -73.694, 24.831), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158182693.19dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(156.902, -4.583, -3.047), 'Pos': Point3(119.164, -80.652, 23.541), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158182821.26dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-134.658, -4.629, -4.351), 'Pos': Point3(146.689, -53.621, 18.933), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158182848.76dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-137.917, -4.375, -4.607), 'Pos': Point3(132.948, -67.034, 20.877), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158182932.7dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-82.409, -7.221, -8.478), 'Pos': Point3(143.743, -35.104, 15.639), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158183065.03dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-90.621, -5.901, -6.868), 'Pos': Point3(143.742, -14.913, 13.897), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.4000000059604645, 0.4000000059604645, 0.4000000059604645, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158183071.86dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-93.058, -2.87, 7.284), 'Pos': Point3(145.036, 5.236, 16.42), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158183118.53dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-88.399, -3.288, -5.001), 'Pos': Point3(144.473, 24.609, 14.84), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158183138.39dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-88.044, -3.4, -17.551), 'Pos': Point3(143.788, 43.337, 9.331), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158183168.96dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-88.044, -3.4, -17.551), 'Pos': Point3(142.705, 63.041, 4.48), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158183179.52dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-46.406, -13.312, 3.063), 'Pos': Point3(129.257, 77.997, 5.763), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158183194.62dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-52.05, -11.225, -9.435), 'Pos': Point3(116.997, 92.984, 2.929), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158183484.87dxschafe': {'Type': 'Building Exterior', 'File': '', 'ExtUid': '1158183484.87dxschafe0', 'Hpr': VBase3(50.046, -1.396, 19.648), 'Pos': Point3(103.869, -7.343, 25.461), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Name': '', 'Door': 'models/buildings/shanty_guildhall_door', 'Interior': 'models/buildings/interior_shanty_guildhall', 'Model': 'models/buildings/burned_gate', 'SignImage': 'models/buildings/sign1_eng_a_icon_barber'}}, '1158183512.32dxschafe': {'Type': 'Building Exterior', 'File': '', 'ExtUid': '1158183512.32dxschafe0', 'Hpr': VBase3(150.633, 22.141, 0.0), 'Pos': Point3(117.969, 6.942, 21.198), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Name': '', 'Door': 'models/buildings/shanty_guildhall_door', 'Interior': 'models/buildings/interior_shanty_guildhall', 'Model': 'models/buildings/burned_woods', 'SignImage': 'models/buildings/sign1_eng_a_icon_barber'}}, '1158183534.96dxschafe': {'Type': 'Building Exterior', 'File': '', 'ExtUid': '1158183534.96dxschafe0', 'Hpr': VBase3(33.787, 1.963, 7.428), 'Pos': Point3(95.43, -28.861, 25.58), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Name': '', 'Door': 'models/buildings/shanty_guildhall_door', 'Interior': 'models/buildings/interior_shanty_guildhall', 'Model': 'models/buildings/burned_house', 'SignImage': 'models/buildings/sign1_eng_a_icon_blacksmith'}}, '1158183538.68dxschafe': {'Type': 'Building Exterior', 'File': '', 'ExtUid': '1158183538.68dxschafe0', 'Hpr': VBase3(-117.358, -2.523, -6.109), 'Pos': Point3(116.235, 8.24, 21.963), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Name': '', 'Door': 'models/buildings/shanty_guildhall_door', 'Interior': 'models/buildings/interior_shanty_guildhall', 'Model': 'models/buildings/burned_gate'}}, '1158183539.56dxschafe': {'Type': 'Building Exterior', 'File': '', 'ExtUid': '1158183539.56dxschafe0', 'Hpr': VBase3(-30.026, -10.013, 0.0), 'Pos': Point3(125.381, 28.952, 17.997), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Name': '', 'Door': 'models/buildings/shanty_guildhall_door', 'Interior': 'models/buildings/interior_shanty_guildhall', 'Model': 'models/buildings/burned_half_house'}}, '1158184101.57dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(66.552, 0.603, -3.255), 'Pos': Point3(-23.842, -7.354, 46.115), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158184229.68dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(58.251, 0.898, -2.128), 'Pos': Point3(-33.795, -23.811, 46.463), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158184324.46dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(32.578, 3.296, -4.655), 'Pos': Point3(-50.003, -34.148, 44.903), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.4000000059604645, 0.4000000059604645, 0.4000000059604645, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158184357.18dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(36.275, 4.993, -6.774), 'Pos': Point3(-65.718, -45.641, 43.274), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.4000000059604645, 0.4000000059604645, 0.4000000059604645, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158184364.29dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(68.4, -5.497, -9.495), 'Pos': Point3(-72.35, -64.077, 40.017), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158184370.08dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(1.248, 2.241, -13.03), 'Pos': Point3(-91.712, -64.748, 35.605), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158184372.85dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-33.717, -0.183, -3.235), 'Pos': Point3(-108.033, -54.118, 34.481), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158184560.85dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-177.764, 5.433, -6.696), 'Pos': Point3(-166.229, -58.604, 26.114), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158184591.92dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(174.03, 5.685, 2.176), 'Pos': Point3(-185.057, -59.119, 28.147), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158184647.42dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-133.247, 1.658, -4.986), 'Pos': Point3(-204.953, -57.073, 26.623), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158184686.31dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-133.749, 1.84, -19.979), 'Pos': Point3(-218.87, -71.733, 28.223), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158184711.85dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-110.552, 0.958, 1.398), 'Pos': Point3(-231.492, -84.253, 34.507), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158185082.54dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-84.958, -1.451, -19.529), 'Pos': Point3(-162.469, -71.482, 26.205), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158185128.07dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-118.069, -3.839, -1.236), 'Pos': Point3(-161.047, -89.369, 32.759), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158185452.34dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-136.036, -4.62, -0.573), 'Pos': Point3(-170.675, -107.017, 33.25), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158185475.99dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-137.239, -4.607, 2.323), 'Pos': Point3(-185.137, -120.885, 33.154), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158185535.42dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(-93.254, -32.462, 18.756), 'Pos': Point3(-206.007, -162.295, 24.052), 'Scale': VBase3(0.906, 0.906, 0.906), 'Visual': {'Color': (0.49000000953674316, 0.47999998927116394, 0.4000000059604645, 1.0), 'Model': 'models/props/rock_group_2_sphere'}}, '1158185590.31dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(178.107, -35.944, -12.028), 'Objects': {}, 'Pos': Point3(-229.422, -177.548, 25.35), 'Scale': VBase3(1.289, 1.289, 1.289), 'Visual': {'Color': (0.49000000953674316, 0.47999998927116394, 0.4000000059604645, 1.0), 'Model': 'models/props/rock_group_4_sphere'}}, '1158185665.78dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(137.66, -2.15, -28.739), 'Pos': Point3(-197.04, -146.065, 27.435), 'Scale': VBase3(0.855, 0.855, 0.855), 'Visual': {'Color': (0.49000000953674316, 0.47999998927116394, 0.4000000059604645, 1.0), 'Model': 'models/props/rock_group_2_sphere'}}, '1158186142.53dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(108.366, 18.255, 8.648), 'Objects': {}, 'Pos': Point3(129.615, 60.135, 8.395), 'Scale': VBase3(2.339, 2.339, 2.339), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/props/zz_dont_use_rocks_Dk_group_2F'}}, '1158186163.4dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(47.463, 3.011, -2.995), 'Pos': Point3(-6.028, -14.775, 45.847), 'Scale': VBase3(2.49, 2.49, 2.49), 'VisSize': '', 'Visual': {'Model': 'models/props/zz_dont_use_rocks_Dk_group_2F'}}, '1158186238.08dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(39.572, -13.474, 4.915), 'Pos': Point3(-214.378, -55.909, 23.133), 'Scale': VBase3(2.366, 2.366, 2.366), 'Visual': {'Model': 'models/props/zz_dont_use_rocks_Dk_group_2F'}}, '1158186353.71dxschafe': {'Type': 'Building Exterior', 'File': '', 'ExtUid': '1158186353.71dxschafe0', 'Hpr': VBase3(76.967, 6.852, -1.277), 'Pos': Point3(62.248, -26.58, 34.28), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Name': '', 'Door': 'models/buildings/shanty_guildhall_door', 'Interior': 'models/buildings/interior_shanty_guildhall', 'Model': 'models/buildings/burned_house', 'SignImage': 'models/buildings/sign1_eng_a_icon_blacksmith'}}, '1158186720.88dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(31.139, -1.639, 12.318), 'Pos': Point3(131.005, -43.462, 17.549), 'Scale': VBase3(1.689, 1.689, 1.689), 'Visual': {'Color': (0.4000000059604645, 0.4000000059604645, 0.4000000059604645, 1.0), 'Model': 'models/props/zz_dont_use_rocks_Dk_group_2F'}}, '1158186804.71dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(-74.164, -13.433, -6.231), 'Pos': Point3(121.709, 42.732, 15.856), 'Scale': VBase3(1.211, 1.211, 1.645), 'Visual': {'Model': 'models/props/rock_group_3_sphere'}}, '1158186853.05dxschafe': {'Type': 'Tree - Animated', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(0.0, -8.424, 0.0), 'Pos': Point3(-10.743, 44.639, 45.335), 'Scale': VBase3(1.224, 1.224, 1.224), 'SubObjs': {'Top Model': {'Visual': {'Animate': 'models/vegetation/palm_leaf_a_idle', 'Attach': ['trunk', 'def_trunk_attach'], 'Holiday': '', 'Model': 'models/vegetation/palm_leaf_a_hi', 'PartName': 'leaf', 'VisSize': ''}}}, 'VisSize': '', 'Visual': {'Animate': 'models/vegetation/palm_trunk_a_idle', 'Model': 'models/vegetation/palm_trunk_a_hi', 'PartName': 'trunk'}}, '1158186866.38dxschafe': {'Type': 'Tree - Animated', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(143.125, 8.549, 7.558), 'Pos': Point3(-13.389, 50.685, 45.175), 'Scale': VBase3(0.788, 0.788, 0.788), 'SubObjs': {'Top Model': {'Visual': {'Animate': 'models/vegetation/palm_leaf_a_idle', 'Attach': ['trunk', 'def_trunk_attach'], 'Holiday': '', 'Model': 'models/vegetation/palm_leaf_a_hi', 'PartName': 'leaf', 'VisSize': ''}}}, 'VisSize': '', 'Visual': {'Animate': 'models/vegetation/palm_trunk_a_idle', 'Model': 'models/vegetation/palm_trunk_a_hi', 'PartName': 'trunk'}}, '1158186918.12dxschafe': {'Type': 'Tree - Animated', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(104.108, 0.0, 0.0), 'Pos': Point3(41.25, 5.834, 36.428), 'Scale': VBase3(0.494, 0.494, 0.494), 'SubObjs': {'Top Model': {'Visual': {'Animate': 'models/vegetation/palm_leaf_a_idle', 'Attach': ['trunk', 'def_trunk_attach'], 'Holiday': '', 'Model': 'models/vegetation/palm_leaf_b_hi', 'PartName': 'leaf', 'Scale': VBase3(4.036, 4.036, 4.036), 'VisSize': ''}}}, 'VisSize': '', 'Visual': {'Animate': 'models/vegetation/palm_trunk_a_idle', 'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/vegetation/palm_trunk_b_hi', 'PartName': 'trunk'}}, '1158187287.35dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(-156.602, 9.305, -17.53), 'Objects': {}, 'Pos': Point3(123.293, 92.568, 0.94), 'Scale': VBase3(1.737, 1.737, 1.737), 'Visual': {'Model': 'models/props/rock_group_3_sphere'}}, '1158187411.06dxschafe': {'Type': 'Tree - Animated', 'DisableCollision': False, 'Hpr': VBase3(-49.77, 0.0, 0.0), 'Pos': Point3(124.089, -46.527, 19.916), 'Scale': VBase3(0.413, 0.413, 0.413), 'SubObjs': {'Top Model': {'Visual': {'Animate': 'models/vegetation/palm_leaf_a_idle', 'Attach': ['trunk', 'def_trunk_attach'], 'Model': 'models/vegetation/palm_leaf_b_hi', 'PartName': 'leaf', 'Scale': VBase3(4.739, 4.739, 4.739)}}}, 'Visual': {'Animate': 'models/vegetation/palm_trunk_a_idle', 'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/vegetation/palm_trunk_b_hi', 'PartName': 'trunk'}}, '1158187451.92dxschafe': {'Type': 'Tree - Animated', 'DisableCollision': True, 'Hpr': VBase3(0.0, -8.424, 19.152), 'Pos': Point3(136.264, 82.951, 1.485), 'Scale': VBase3(1.223, 1.223, 1.223), 'SubObjs': {'Top Model': {'Visual': {'Animate': 'models/vegetation/palm_leaf_a_idle', 'Attach': ['trunk', 'def_trunk_attach'], 'Model': 'models/vegetation/palm_leaf_a_hi', 'PartName': 'leaf'}}}, 'Visual': {'Animate': 'models/vegetation/palm_trunk_a_idle', 'Model': 'models/vegetation/palm_trunk_a_hi', 'PartName': 'trunk'}}, '1158187487.14dxschafe': {'Type': 'Tree - Animated', 'DisableCollision': True, 'Hpr': VBase3(-166.968, -0.605, 7.515), 'Pos': Point3(-32.527, 34.158, 46.733), 'Scale': VBase3(0.296, 0.296, 0.296), 'SubObjs': {'Top Model': {'Visual': {'Animate': 'models/vegetation/palm_leaf_a_idle', 'Attach': ['trunk', 'def_trunk_attach'], 'Model': 'models/vegetation/palm_leaf_b_hi', 'PartName': 'leaf', 'Scale': VBase3(4.623, 4.623, 4.623)}}}, 'Visual': {'Animate': 'models/vegetation/palm_trunk_a_idle', 'Color': (1.0, 1.0, 1.0, 1.0), 'Model': 'models/vegetation/palm_trunk_b_hi', 'PartName': 'trunk'}}, '1158187506.48dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(90.703, -4.348, 1.581), 'Pos': Point3(-38.436, 38.193, 45.35), 'Scale': VBase3(2.25, 2.25, 2.25), 'VisSize': '', 'Visual': {'Model': 'models/props/zz_dont_use_rocks_Dk_group_2F'}}, '1158187636.42dxschafe': {'Type': 'Tree - Animated', 'DisableCollision': False, 'Hpr': VBase3(34.133, -6.989, 4.715), 'Pos': Point3(-213.649, -61.776, 24.76), 'Scale': VBase3(1.223, 1.223, 1.223), 'SubObjs': {'Top Model': {'Visual': {'Animate': 'models/vegetation/palm_leaf_a_idle', 'Attach': ['trunk', 'def_trunk_attach'], 'Model': 'models/vegetation/palm_leaf_a_hi', 'PartName': 'leaf'}}}, 'Visual': {'Animate': 'models/vegetation/palm_trunk_a_idle', 'Model': 'models/vegetation/palm_trunk_a_hi', 'PartName': 'trunk'}}, '1158187645.45dxschafe': {'Type': 'Tree - Animated', 'DisableCollision': True, 'Hpr': VBase3(93.317, -0.368, -4.252), 'Pos': Point3(-222.546, -167.819, 32.379), 'Scale': VBase3(1.223, 1.223, 1.223), 'SubObjs': {'Top Model': {'Visual': {'Animate': 'models/vegetation/palm_leaf_a_idle', 'Attach': ['trunk', 'def_trunk_attach'], 'Model': 'models/vegetation/palm_leaf_a_hi', 'PartName': 'leaf'}}}, 'Visual': {'Animate': 'models/vegetation/palm_trunk_a_idle', 'Model': 'models/vegetation/palm_trunk_a_hi', 'PartName': 'trunk'}}, '1158187648.86dxschafe': {'Type': 'Tree - Animated', 'DisableCollision': True, 'Hpr': VBase3(-111.436, -2.489, 11.076), 'Pos': Point3(-225.882, -172.068, 29.339), 'Scale': VBase3(1.017, 1.017, 1.017), 'SubObjs': {'Top Model': {'Visual': {'Animate': 'models/vegetation/palm_leaf_a_idle', 'Attach': ['trunk', 'def_trunk_attach'], 'Model': 'models/vegetation/palm_leaf_a_hi', 'PartName': 'leaf'}}}, 'Visual': {'Animate': 'models/vegetation/palm_trunk_a_idle', 'Model': 'models/vegetation/palm_trunk_a_hi', 'PartName': 'trunk'}}, '1158187693.43dxschafe': {'Type': 'Tree - Animated', 'DisableCollision': True, 'Hpr': VBase3(5.872, 6.98, 20.452), 'Pos': Point3(-208.288, -159.109, 26.968), 'Scale': VBase3(0.864, 0.864, 0.864), 'SubObjs': {'Top Model': {'Visual': {'Animate': 'models/vegetation/palm_leaf_a_idle', 'Attach': ['trunk', 'def_trunk_attach'], 'Model': 'models/vegetation/palm_leaf_a_hi', 'PartName': 'leaf'}}}, 'Visual': {'Animate': 'models/vegetation/palm_trunk_a_idle', 'Model': 'models/vegetation/palm_trunk_a_hi', 'PartName': 'trunk'}}, '1158187774.44dxschafe': {'Type': 'Bush', 'DisableCollision': True, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-144.263, -38.516, 14.53), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1158187777.83dxschafe': {'Type': 'Bush', 'DisableCollision': True, 'Hpr': VBase3(-125.644, 28.397, 13.135), 'Pos': Point3(-151.104, -29.302, 11.076), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1158187797.23dxschafe': {'Type': 'Bush', 'DisableCollision': True, 'Hpr': VBase3(177.079, -5.197, 19.736), 'Pos': Point3(-125.012, -29.662, 31.875), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_d'}}, '1158188841.99dxschafe': {'Type': 'Bush', 'DisableCollision': True, 'Hpr': VBase3(89.315, -2.48, 17.515), 'Pos': Point3(-198.382, -54.49, 26.033), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_d'}}, '1158188928.14dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(104.718, -2.336, -2.367), 'Pos': Point3(-227.575, -99.03, 31.948), 'Scale': VBase3(1.775, 1.775, 1.775), 'Visual': {'Model': 'models/props/zz_dont_use_rocks_Dk_group_2F'}}, '1158188977.06dxschafe': {'Type': 'Tree', 'DisableCollision': True, 'Hpr': VBase3(0.0, 0.0, 3.741), 'Pos': Point3(-224.441, -101.879, 33.947), 'Scale': VBase3(0.602, 0.602, 0.602), 'Visual': {'Model': 'models/vegetation/fern_tree_d'}}, '1158189044.97dxschafe': {'Type': 'Tree', 'DisableCollision': True, 'Hpr': VBase3(-19.504, 2.161, -6.075), 'Pos': Point3(-109.39, -62.866, 33.486), 'Scale': VBase3(0.801, 0.801, 0.801), 'Visual': {'Model': 'models/vegetation/fern_tree_d'}}, '1158189074.85dxschafe': {'Type': 'Bush', 'DisableCollision': True, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-137.677, -65.205, 7.624), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1158189077.15dxschafe': {'Type': 'Bush', 'DisableCollision': True, 'Hpr': VBase3(73.77, 3.693, -4.246), 'Pos': Point3(-128.352, -76.87, 4.674), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1158189129.4dxschafe': {'Type': 'Bush', 'DisableCollision': True, 'Hpr': VBase3(154.082, 14.322, 0.0), 'Pos': Point3(-152.849, -76.926, 26.204), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1158189159.3dxschafe': {'Type': 'Bush', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(-143.574, -0.299, -0.909), 'Pos': Point3(6.796, -5.839, 47.075), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/vegetation/bush_a'}}, '1158189208.92dxschafe': {'Type': 'Bush', 'DisableCollision': True, 'Hpr': VBase3(-159.486, 2.54, 3.222), 'Pos': Point3(-23.867, 28.119, 46.685), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_d'}}, '1158189382.81dxschafe': {'Type': 'Bush', 'DisableCollision': True, 'Hpr': VBase3(46.93, -7.243, -15.141), 'Pos': Point3(-114.24, -58.856, 31.57), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_d'}}, '1158189494.97dxschafe': {'Type': 'Tree - Animated', 'DisableCollision': True, 'Hpr': VBase3(64.734, 5.356, 20.644), 'Pos': Point3(130.584, 88.645, 0.839), 'Scale': VBase3(0.86, 0.86, 0.86), 'SubObjs': {'Top Model': {'Visual': {'Animate': 'models/vegetation/palm_leaf_a_idle', 'Attach': ['trunk', 'def_trunk_attach'], 'Model': 'models/vegetation/palm_leaf_a_hi', 'PartName': 'leaf'}}}, 'Visual': {'Animate': 'models/vegetation/palm_trunk_a_idle', 'Model': 'models/vegetation/palm_trunk_a_hi', 'PartName': 'trunk'}}, '1158195990.71jubutler': {'Type': 'Building Exterior', 'File': 'RambleshackJailInt', 'ExtUid': '1156204132.41sdnaik', 'Hpr': VBase3(134.576, 0.0, 0.0), 'Objects': {'1202154005.44kmuller': {'Type': 'Door Locator Node', 'Name': 'door_locator', 'Hpr': VBase3(-180.0, 0.0, 0.0), 'Pos': Point3(12.899, -22.494, 0.283), 'Scale': VBase3(1.0, 1.0, 1.0)}}, 'Pos': Point3(-226.151, -141.619, 33.194), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Name': '', 'Door': 'models/buildings/shanty_guildhall_door', 'Interior': 'models/buildings/navy_jail_interior', 'Model': 'models/buildings/jail_exterior', 'SignImage': 'models/buildings/sign1_eng_a_icon_blacksmith'}}, '1158343582.31dxschafe': {'Type': 'Wall', 'DisableCollision': False, 'Hpr': VBase3(-137.239, -4.607, 2.323), 'Pos': Point3(-199.337, -133.858, 32.883), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pir_m_prp_fnc_wood20'}}, '1158343998.69dxschafe': {'Type': 'Rock', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(0.263, 17.689, -8.803), 'Objects': {'1158344100.99dxschafe': {'Type': 'Tree', 'DisableCollision': True, 'GridPos': Point3(-86.516, -55.35, 38.91), 'Hpr': VBase3(1.988, -12.069, 5.299), 'Pos': Point3(-3.445, -0.083, 0.611), 'Scale': VBase3(0.402, 0.402, 0.402), 'Visual': {'Model': 'models/vegetation/fern_tree_b'}}}, 'Pos': Point3(-77.806, -55.5, 38.651), 'Scale': VBase3(2.49, 2.49, 2.49), 'VisSize': '', 'Visual': {'Model': 'models/props/zz_dont_use_rocks_Dk_group_2F'}}, '1158344139.1dxschafe': {'Type': 'Tree', 'DisableCollision': True, 'GridPos': Point3(-86.516, -55.35, 38.91), 'Hpr': VBase3(0.656, 2.429, 5.186), 'Pos': Point3(-70.189, -62.915, 40.479), 'Scale': VBase3(0.649, 0.649, 0.649), 'Visual': {'Model': 'models/vegetation/fern_tree_b'}}, '1158344184.88dxschafe': {'Type': 'Tree', 'DisableCollision': True, 'GridPos': Point3(-86.516, -55.35, 38.91), 'Hpr': VBase3(2.295, -15.269, 5.372), 'Pos': Point3(-199.599, -53.093, 25.232), 'Scale': VBase3(0.88, 0.88, 0.88), 'Visual': {'Model': 'models/vegetation/fern_tree_b'}}, '1158344251.57dxschafe': {'Type': 'Tree', 'DisableCollision': True, 'GridPos': Point3(-86.516, -55.35, 38.91), 'Holiday': '', 'Hpr': VBase3(-21.985, 2.547, 6.676), 'Pos': Point3(14.442, -7.676, 46.484), 'Scale': VBase3(1.003, 1.003, 1.003), 'VisSize': '', 'Visual': {'Model': 'models/vegetation/fern_tree_b'}}, '1158344349.98dxschafe': {'Type': 'Tree', 'DisableCollision': True, 'GridPos': Point3(111.176, 50.565, 16.694), 'Hpr': VBase3(0.0, -10.132, 5.265), 'Pos': Point3(127.808, 40.905, 12.262), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/fern_tree_b'}}, '1158344412.95dxschafe': {'Type': 'Barrel', 'DisableCollision': True, 'Hpr': VBase3(0.476, -5.922, 6.302), 'Pos': Point3(94.652, 94.698, 4.667), 'Scale': VBase3(0.747, 0.747, 0.747), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/props/barrel_group_3'}}, '1158344423.45dxschafe': {'Type': 'Cart', 'DisableCollision': True, 'Hpr': VBase3(21.526, -8.437, 8.754), 'Pos': Point3(83.491, 92.022, 6.354), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0), 'Model': 'models/props/cart_reg'}}, '1158344555.81dxschafe': {'Type': 'Crate', 'DisableCollision': True, 'Hpr': VBase3(-30.724, -11.087, -0.77), 'Pos': Point3(89.217, 90.471, 5.895), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/props/crate'}}, '1165537475.41fxlara': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(-116.63, 5.707, -23.802), 'Pos': Point3(106.99, 100.228, 0.675), 'Scale': VBase3(1.129, 1.129, 1.129), 'Visual': {'Model': 'models/props/rock_group_5_sphere'}}, '1165623607.38darren': {'Type': 'Effect Node', 'EffectName': 'bonfire_effect', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-28.802, 75.769, 40.482), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1165627325.38darren': {'Type': 'Effect Node', 'EffectName': 'bonfire_effect', 'GridPos': Point3(21.523, -5.618, 46.733), 'Hpr': VBase3(37.072, 13.956, 8.869), 'Pos': Point3(27.126, -6.266, 49.233), 'Scale': VBase3(1.001, 1.001, 1.001), 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1165628953.92darren': {'Type': 'Effect Node', 'EffectName': 'bonfire_effect', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(154.963, 31.206, 10.01), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1166059404.52darren': {'Type': 'Effect Node', 'EffectName': 'bonfire_effect', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-194.279, -48.81, 24.718), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1173229521.39kmuller': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(0.0, 0.0, 15.541), 'Pos': Point3(25.677, -4.888, 43.949), 'Scale': VBase3(1.995, 1.995, 1.995), 'Visual': {'Color': (0.49000000953674316, 0.47999998927116394, 0.4000000059604645, 1.0), 'Model': 'models/props/rock_2_sphere'}}, '1173229567.69kmuller': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(112.651, 13.131, 0.0), 'Pos': Point3(27.237, 2.249, 44.441), 'Scale': VBase3(3.405, 3.405, 3.405), 'Visual': {'Color': (0.7099999785423279, 0.6700000166893005, 0.6000000238418579, 1.0), 'Model': 'models/props/rock_3_sphere'}}, '1173229671.59kmuller': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(-16.672, -5.627, 18.129), 'Pos': Point3(23.578, 7.987, 45.917), 'Scale': VBase3(1.543, 1.543, 1.543), 'Visual': {'Color': (0.7099999785423279, 0.6700000166893005, 0.6000000238418579, 1.0), 'Model': 'models/props/rock_2_sphere'}}, '1173230223.73kmuller': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(1.563, -9.175, 9.711), 'Pos': Point3(-235.824, -167.026, 30.722), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5899999737739563, 0.5899999737739563, 0.49000000953674316, 1.0), 'Model': 'models/props/rock_group_5_sphere'}}, '1173230369.33kmuller': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(-0.974, 23.502, 21.298), 'Pos': Point3(-220.688, -168.605, 25.886), 'Scale': VBase3(1.272, 1.272, 1.272), 'Visual': {'Color': (0.7900000214576721, 0.7799999713897705, 0.699999988079071, 1.0), 'Model': 'models/props/rock_group_4_sphere'}}, '1173463985.56kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(-40.029, 0.0, 0.0), 'Pos': Point3(-22.099, 5.563, 47.153), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/torch'}}, '1173463999.64kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(-109.996, 0.0, 0.0), 'Pos': Point3(-23.908, 15.826, 47.677), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/torch'}}, '1173464070.8kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(-46.545, 0.0, -9.75), 'Pos': Point3(108.138, 98.549, 2.728), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/torch'}}, '1173464100.87kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(0.0, -8.66, 0.0), 'Pos': Point3(116.599, 92.389, 3.181), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/torch'}}, '1173464157.41kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(14.113, -8.58, 0.0), 'Pos': Point3(-113.044, -48.601, 32.171), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/torch'}}, '1173464182.53kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(175.62, 0.0, 0.0), 'Pos': Point3(-115.16, -35.877, 31.233), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/torch'}}, '1173464199.89kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(-104.375, 0.0, 0.0), 'Pos': Point3(-170.003, -60.845, 27.128), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/torch'}}, '1173464218.62kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(-30.066, -16.41, -7.275), 'Pos': Point3(-163.476, -72.553, 26.965), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/torch'}}, '1173847187.11MAsaduzz': {'Type': 'Light - Dynamic', 'Attenuation': '0.005', 'ConeAngle': '60.0000', 'DropOff': '0.0000', 'FlickRate': 0.5, 'Flickering': True, 'Hpr': Point3(0.0, 0.0, 0.0), 'Intensity': '0.2273', 'LightType': 'POINT', 'Pos': Point3(-23.074, 3.925, 55.442), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/props/light_tool_bulb'}}, '1173847246.41MAsaduzz': {'Type': 'Light - Dynamic', 'Attenuation': '0.005', 'ConeAngle': '60.0000', 'DropOff': '0.0000', 'FlickRate': 0.5, 'Flickering': True, 'Hpr': Point3(0.0, 0.0, 0.0), 'Intensity': '0.2424', 'LightType': 'POINT', 'Pos': Point3(-25.561, 16.532, 55.688), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1), 'Model': 'models/props/light_tool_bulb'}}, '1175286835.45kmuller': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(-23.882, 0.0, 0.0), 'Pos': Point3(12.719, 12.219, 46.577), 'Scale': VBase3(2.36, 2.36, 2.36), 'Visual': {'Model': 'models/props/rock_3_sphere'}}, '1185558037.1kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(121.269, 0.0, 0.0), 'Pos': Point3(-227.045, -86.799, 32.378), 'Scale': VBase3(1.0, 1.0, 1.848), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185558089.04kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-93.425, 0.0, 0.0), 'Pos': Point3(-223.993, -99.899, 30.785), 'Scale': VBase3(3.654, 2.379, 2.379), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}}, '1185558130.63kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(43.583, 0.0, 0.0), 'Pos': Point3(-220.75, -110.425, 32.449), 'Scale': VBase3(0.459, 1.0, 2.05), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185558177.77kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-172.769, 0.0, 0.0), 'Pos': Point3(-198.936, -132.022, 32.761), 'Scale': VBase3(0.606, 1.0, 2.44), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185558217.46kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-95.658, 0.0, 0.0), 'Pos': Point3(-161.957, -87.622, 30.82), 'Scale': VBase3(1.049, 1.0, 3.006), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185558288.27kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-158.994, 0.0, 0.0), 'Pos': Point3(-161.121, -68.763, 26.255), 'Scale': VBase3(0.366, 1.0, 4.007), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185558346.82kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-108.455, 0.0, 0.0), 'Pos': Point3(-95.123, -52.037, 35.015), 'Scale': VBase3(2.479, 1.702, 2.898), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185559934.46kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-178.133, 0.0, 0.0), 'Pos': Point3(-84.267, -40.367, 39.656), 'Scale': VBase3(1.393, 1.503, 1.955), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185559985.48kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(154.38, 0.0, 0.0), 'Pos': Point3(-67.462, -44.995, 39.765), 'Scale': VBase3(2.288, 1.764, 1.912), 'VisSize': '', 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185560136.51kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(31.92, 0.0, 0.0), 'Pos': Point3(35.992, -4.396, 39.347), 'Scale': VBase3(2.75, 1.858, 4.122), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185560262.56kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(17.952, -11.471, 45.002), 'Scale': VBase3(1.393, 1.602, 3.089), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185560641.42kmuller': {'Type': 'Bush', 'DisableCollision': True, 'Hpr': VBase3(68.388, 0.0, 0.0), 'Pos': Point3(-29.672, 46.547, 45.194), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_b'}}, '1185560910.95kmuller': {'Type': 'Bush', 'DisableCollision': True, 'Hpr': VBase3(-112.233, 0.0, 0.0), 'Pos': Point3(-40.502, 27.121, 46.113), 'Scale': VBase3(0.595, 0.595, 0.595), 'Visual': {'Model': 'models/vegetation/bush_f'}}, '1185561940.49kmuller': {'Type': 'Rock', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(114.775, 0.0, 0.0), 'Pos': Point3(-8.539, 55.621, 43.035), 'Scale': VBase3(2.975, 2.975, 3.785), 'VisSize': '', 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/rock_4_sphere'}}, '1185562015.71kmuller': {'Type': 'Bush', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(115.448, 0.0, 0.0), 'Pos': Point3(-23.314, 55.899, 44.134), 'Scale': VBase3(0.77, 0.77, 0.77), 'VisSize': '', 'Visual': {'Model': 'models/vegetation/bush_b'}}, '1185568481.4kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-157.893, 0.0, 0.0), 'Pos': Point3(-21.851, 58.897, 43.756), 'Scale': VBase3(1.772, 1.0, 1.6), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185568513.93kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(149.954, 0.0, 0.0), 'Pos': Point3(-2.532, 55.514, 43.634), 'Scale': VBase3(2.697, 1.0, 1.687), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185568547.6kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(65.912, 0.0, 0.0), 'Pos': Point3(5.701, 41.286, 43.723), 'Scale': VBase3(1.671, 1.0, 1.993), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185568598.81kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(176.972, 0.0, 0.0), 'Pos': Point3(22.465, 17.779, 37.59), 'Scale': VBase3(3.879, 1.41, 3.117), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185568716.62kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(68.858, 0.0, 0.0), 'Pos': Point3(49.512, 6.518, 35.742), 'Scale': VBase3(1.0, 1.0, 2.915), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185568738.67kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(149.137, 0.0, 0.0), 'Pos': Point3(46.38, 14.059, 35.679), 'Scale': VBase3(1.198, 1.0, 3.085), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185568820.96kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(130.847, -43.277, 18.288), 'Scale': VBase3(1.094, 1.094, 1.094), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_sphere'}}, '1185568896.48kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(81.923, 87.748, 5.317), 'Scale': VBase3(1.787, 1.0, 2.402), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185568933.01kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(31.828, 0.0, 0.0), 'Pos': Point3(97.437, 92.509, 2.621), 'Scale': VBase3(1.665, 1.0, 2.891), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185568959.85kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-68.995, 0.0, 0.0), 'Pos': Point3(72.082, 91.108, 8.67), 'Scale': VBase3(0.774, 1.0, 1.743), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1187113409.44akelts': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(-117.376, -26.74, -59.876), 'Pos': Point3(6.958, 14.904, 49.425), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0), 'Model': 'models/props/rock_1_floor'}}, '1190757402.45joswilso': {'Type': 'Quest Node', 'At': '6', 'Hpr': Point3(0.0, 0.0, 0.0), 'Near': '145', 'NearOffsetX': '-24', 'NearOffsetY': '-90', 'NearOffsetZ': '0', 'NearVisX': '-153', 'NearVisY': '-116', 'NearVisZ': '40', 'Pos': Point3(129.149, 127.066, 8.087), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (1.0, 1.0, 0, 1.0), 'Model': 'models/misc/sphere'}}, '1192217827.01MAsaduzz': {'Type': 'Cutscene Origin Node', 'CutsceneId': '1.3: Jolly Roger', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(672.532, 405.492, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1202154006.23kmuller': {'Type': 'Door Locator Node', 'Name': 'door_locator', 'Hpr': VBase3(-180.0, 0.0, 0.0), 'Pos': Point3(12.899, -22.494, 0.283), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1202154006.26kmuller': {'Type': 'Door Locator Node', 'Name': 'door_locator_2', 'Hpr': VBase3(0.0, 0.0, 0.0), 'Pos': Point3(-6.626, 20.947, 1.006), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1202161377.6kmuller': {'Type': 'Bush', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(58.062, 0.0, 0.0), 'Pos': Point3(-22.326, -30.235, 40.368), 'Scale': VBase3(1.0, 1.0, 0.698), 'VisSize': '', 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/vegetation/bush_i'}}, '1202161413.51kmuller': {'Type': 'Rock', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(78.67, -0.494, -5.685), 'Pos': Point3(-39.025, -40.55, 44.009), 'Scale': VBase3(1.83, 1.83, 1.83), 'VisSize': '', 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/props/rock_group_2_floor'}}, '1202161534.07kmuller': {'Type': 'Rock', 'DisableCollision': True, 'Hpr': VBase3(45.028, -9.13, -14.836), 'Objects': {'1202161860.73kmuller': {'Type': 'Tree', 'DisableCollision': False, 'GridPos': Point3(-107.566, -15.082, 40.041), 'Hpr': VBase3(-45.6, -4.171, 16.873), 'Pos': Point3(-1.894, -2.571, 0.065), 'Scale': VBase3(0.607, 0.607, 0.607), 'Visual': {'Model': 'models/vegetation/fern_tree_b'}}}, 'Pos': Point3(-108.451, -9.895, 40.054), 'Scale': VBase3(1.647, 1.647, 1.647), 'Visual': {'Model': 'models/props/rock_group_2_floor'}}, '1202161588.49kmuller': {'Type': 'Bush', 'DisableCollision': True, 'Hpr': VBase3(-38.927, 16.884, -15.009), 'Pos': Point3(-117.211, -23.548, 36.325), 'Scale': VBase3(0.743, 0.743, 0.743), 'Visual': {'Model': 'models/vegetation/bush_c'}}, '1202161746.02kmuller': {'Type': 'Bush', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(28.114, 0.0, 0.0), 'Pos': Point3(-19.452, -3.022, 46.647), 'Scale': VBase3(1.0, 1.0, 0.778), 'VisSize': '', 'Visual': {'Model': 'models/vegetation/bush_b'}}, '1202161775.05kmuller': {'Type': 'Bush', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(13.9, 0.0, 0.0), 'Pos': Point3(-33.174, -30.107, 44.437), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/vegetation/bush_b'}}, '1202161796.07kmuller': {'Type': 'Bush', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(153.512, 0.0, 0.0), 'Pos': Point3(-27.138, -22.098, 45.615), 'Scale': VBase3(1.0, 1.0, 0.779), 'VisSize': '', 'Visual': {'Model': 'models/vegetation/bush_f'}}, '1202168756.79kmuller': {'Type': 'Bush', 'DisableCollision': False, 'Hpr': VBase3(63.009, 12.051, 0.0), 'Pos': Point3(30.485, 4.737, 42.584), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/vegetation/bush_f'}}, '1202169076.35kmuller': {'Type': 'Building Exterior', 'File': '', 'ExtUid': '1202169076.35kmuller0', 'Hpr': VBase3(177.072, 10.506, -9.12), 'Pos': Point3(103.989, -8.079, 24.339), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Door': 'models/buildings/shanty_guildhall_door', 'Model': 'models/buildings/burned_woods', 'SignImage': 'models/buildings/sign1_eng_a_icon_barber'}}, '1202171181.34kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-110.159, 0.0, 0.0), 'Pos': Point3(120.782, 66.238, 3.792), 'Scale': VBase3(3.806, 0.683, 4.483), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1202171254.79kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-80.073, 0.0, 0.0), 'Pos': Point3(115.102, 43.888, 15.137), 'Scale': VBase3(1.0, 1.0, 2.335), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1205367808.78kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-110.809, 0.0, 0.0), 'Pos': Point3(116.349, 9.154, 21.087), 'Scale': VBase3(0.621, 1.0, 2.345), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1224631808.0masad1': {'Type': 'Skeleton', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AvId': 0, 'AvTrack': 1, 'Boss': False, 'DNA': '1224631808.0masad1', 'Hpr': VBase3(131.322, 0.0, 0.0), 'Level': 1, 'Patrol Radius': '1.0000', 'Pos': Point3(25.822, 39.926, 38.94), 'PoseAnim': '', 'PoseFrame': '', 'PropLeft': 'None', 'PropRight': 'None', 'Respawns': False, 'Scale': VBase3(1.0, 1.0, 1.0), 'Start State': 'Idle', 'StartFrame': '0', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': ''}, '1224631936.0masad': {'Type': 'Skeleton', 'Aggro Radius': '12.0000', 'AnimSet': 'default', 'AvId': 1, 'AvTrack': 1, 'Boss': False, 'DNA': '1224631936.0masad', 'Hpr': VBase3(108.225, 0.0, 0.0), 'Level': 1, 'Patrol Radius': '1.0000', 'Pos': Point3(26.243, 30.862, 41.753), 'PoseAnim': '', 'PoseFrame': '', 'PropLeft': 'None', 'PropRight': 'None', 'Respawns': False, 'Scale': VBase3(1.0, 1.0, 1.0), 'Start State': 'Idle', 'StartFrame': '0', 'TrailFX': 'None', 'TrailLeft': 'None', 'TrailRight': 'None', 'VisSize': ''}, '1232044484.61akelts': {'Type': 'Rock', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(-120.394, -1.396, 5.534), 'Pos': Point3(-69.535, -46.647, 42.941), 'Scale': VBase3(2.676, 2.676, 2.676), 'VisSize': '', 'Visual': {'Color': (0.6000000238418579, 0.6000000238418579, 0.6000000238418579, 1.0), 'Model': 'models/props/rock_4_sphere'}}, '1232044553.83akelts': {'Type': 'Bush', 'DisableCollision': True, 'Holiday': '', 'Hpr': VBase3(69.727, 0.0, 0.0), 'Pos': Point3(-74.265, -45.928, 42.924), 'Scale': VBase3(1.0, 1.0, 0.779), 'VisSize': '', 'Visual': {'Model': 'models/vegetation/bush_f'}}}, 'Undockable': False, 'VisSize': '', 'Visibility': 'Grid', 'Visual': {'Model': 'models/islands/pir_m_are_isl_rambleshack'}}}, 'Node Links': [], 'Layers': {'Collisions': ['1184008208.59kmuller', '1184016064.62kmuller', '1184013852.84kmuller', '1185822696.06kmuller', '1184006140.32kmuller', '1184002350.98kmuller', '1184007573.29kmuller', '1184021176.59kmuller', '1184005963.59kmuller', '1188324241.31akelts', '1184006537.34kmuller', '1184006605.81kmuller', '1187139568.33kmuller', '1188324186.98akelts', '1184006730.66kmuller', '1184007538.51kmuller', '1184006188.41kmuller', '1184021084.27kmuller', '1185824396.94kmuller', '1185824250.16kmuller', '1185823630.52kmuller', '1185823760.23kmuller', '1185824497.83kmuller', '1185824751.45kmuller', '1187739103.34akelts', '1188323993.34akelts', '1184016538.29kmuller', '1185822200.97kmuller', '1184016225.99kmuller', '1195241421.34akelts', '1195242796.08akelts', '1184020642.13kmuller', '1195237994.63akelts', '1184020756.88kmuller', '1184020833.4kmuller', '1185820992.97kmuller', '1185821053.83kmuller', '1184015068.54kmuller', '1184014935.82kmuller', '1185821432.88kmuller', '1185821701.86kmuller', '1195240137.55akelts', '1195241539.38akelts', '1195238422.3akelts', '1195238473.22akelts', '1185821453.17kmuller', '1184021269.96kmuller', '1185821310.89kmuller', '1185821165.59kmuller', '1185821199.36kmuller', '1185822035.98kmuller', '1184015806.59kmuller', '1185822059.48kmuller', '1185920461.76kmuller', '1194984449.66akelts', '1185824206.22kmuller', '1184003446.23kmuller', '1184003254.85kmuller', '1184003218.74kmuller', '1184002700.44kmuller', '1186705073.11kmuller', '1187658531.86akelts', '1186705214.3kmuller', '1185824927.28kmuller', '1184014204.54kmuller', '1184014152.84kmuller']}, 'ObjectIds': {'1115838800a.3jubutler': '["Objects"]["1115838800a.3jubutler"]', '1121212983.08Shochet': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1121212983.08Shochet"]', '1154414027.23sdnaik': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1154414027.23sdnaik"]', '1156204132.41sdnaik': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158195990.71jubutler"]', '1158178138.25dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158178138.25dxschafe"]', '1158178301.77dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158178301.77dxschafe"]', '1158178482.34dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158178482.34dxschafe"]', '1158178679.34dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158178679.34dxschafe"]', '1158178832.82dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158178832.82dxschafe"]', '1158179872.54dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158179872.54dxschafe"]', '1158180177.05dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158180177.05dxschafe"]', '1158180215.64dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158180215.64dxschafe"]', '1158180294.83dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158180294.83dxschafe"]', '1158180399.71dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158180399.71dxschafe"]', '1158180430.77dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158180430.77dxschafe"]', '1158180465.4dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158180465.4dxschafe"]', '1158180513.62dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158180513.62dxschafe"]', '1158181050.17dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158181050.17dxschafe"]', '1158181145.4dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158181145.4dxschafe"]', '1158181200.79dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158181200.79dxschafe"]', '1158181789.25dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158181789.25dxschafe"]', '1158182008.13dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158182008.13dxschafe"]', '1158182366.55dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158182366.55dxschafe"]', '1158182417.68dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158182417.68dxschafe"]', '1158182570.85dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158182570.85dxschafe"]', '1158182686.93dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158182686.93dxschafe"]', '1158182693.19dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158182693.19dxschafe"]', '1158182821.26dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158182821.26dxschafe"]', '1158182848.76dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158182848.76dxschafe"]', '1158182932.7dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158182932.7dxschafe"]', '1158183065.03dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183065.03dxschafe"]', '1158183071.86dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183071.86dxschafe"]', '1158183118.53dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183118.53dxschafe"]', '1158183138.39dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183138.39dxschafe"]', '1158183168.96dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183168.96dxschafe"]', '1158183179.52dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183179.52dxschafe"]', '1158183194.62dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183194.62dxschafe"]', '1158183484.87dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183484.87dxschafe"]', '1158183484.87dxschafe0': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183484.87dxschafe"]', '1158183512.32dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183512.32dxschafe"]', '1158183512.32dxschafe0': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183512.32dxschafe"]', '1158183534.96dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183534.96dxschafe"]', '1158183534.96dxschafe0': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183534.96dxschafe"]', '1158183538.68dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183538.68dxschafe"]', '1158183538.68dxschafe0': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183538.68dxschafe"]', '1158183539.56dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183539.56dxschafe"]', '1158183539.56dxschafe0': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158183539.56dxschafe"]', '1158184101.57dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158184101.57dxschafe"]', '1158184229.68dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158184229.68dxschafe"]', '1158184324.46dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158184324.46dxschafe"]', '1158184357.18dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158184357.18dxschafe"]', '1158184364.29dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158184364.29dxschafe"]', '1158184370.08dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158184370.08dxschafe"]', '1158184372.85dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158184372.85dxschafe"]', '1158184560.85dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158184560.85dxschafe"]', '1158184591.92dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158184591.92dxschafe"]', '1158184647.42dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158184647.42dxschafe"]', '1158184686.31dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158184686.31dxschafe"]', '1158184711.85dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158184711.85dxschafe"]', '1158185082.54dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158185082.54dxschafe"]', '1158185128.07dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158185128.07dxschafe"]', '1158185452.34dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158185452.34dxschafe"]', '1158185475.99dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158185475.99dxschafe"]', '1158185535.42dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158185535.42dxschafe"]', '1158185590.31dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158185590.31dxschafe"]', '1158185665.78dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158185665.78dxschafe"]', '1158186142.53dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158186142.53dxschafe"]', '1158186163.4dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158186163.4dxschafe"]', '1158186238.08dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158186238.08dxschafe"]', '1158186353.71dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158186353.71dxschafe"]', '1158186353.71dxschafe0': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158186353.71dxschafe"]', '1158186720.88dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158186720.88dxschafe"]', '1158186804.71dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158186804.71dxschafe"]', '1158186853.05dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158186853.05dxschafe"]', '1158186866.38dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158186866.38dxschafe"]', '1158186918.12dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158186918.12dxschafe"]', '1158187287.35dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158187287.35dxschafe"]', '1158187411.06dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158187411.06dxschafe"]', '1158187451.92dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158187451.92dxschafe"]', '1158187487.14dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158187487.14dxschafe"]', '1158187506.48dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158187506.48dxschafe"]', '1158187636.42dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158187636.42dxschafe"]', '1158187645.45dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158187645.45dxschafe"]', '1158187648.86dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158187648.86dxschafe"]', '1158187693.43dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158187693.43dxschafe"]', '1158187774.44dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158187774.44dxschafe"]', '1158187777.83dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158187777.83dxschafe"]', '1158187797.23dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158187797.23dxschafe"]', '1158188841.99dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158188841.99dxschafe"]', '1158188928.14dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158188928.14dxschafe"]', '1158188977.06dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158188977.06dxschafe"]', '1158189044.97dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158189044.97dxschafe"]', '1158189074.85dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158189074.85dxschafe"]', '1158189077.15dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158189077.15dxschafe"]', '1158189129.4dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158189129.4dxschafe"]', '1158189159.3dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158189159.3dxschafe"]', '1158189208.92dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158189208.92dxschafe"]', '1158189382.81dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158189382.81dxschafe"]', '1158189494.97dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158189494.97dxschafe"]', '1158195990.71jubutler': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158195990.71jubutler"]', '1158343582.31dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158343582.31dxschafe"]', '1158343998.69dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158343998.69dxschafe"]', '1158344100.99dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158343998.69dxschafe"]["Objects"]["1158344100.99dxschafe"]', '1158344139.1dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158344139.1dxschafe"]', '1158344184.88dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158344184.88dxschafe"]', '1158344251.57dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158344251.57dxschafe"]', '1158344349.98dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158344349.98dxschafe"]', '1158344412.95dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158344412.95dxschafe"]', '1158344423.45dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158344423.45dxschafe"]', '1158344555.81dxschafe': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158344555.81dxschafe"]', '1159905354.84jubutler': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1121212983.08Shochet"]', '1165537475.41fxlara': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1165537475.41fxlara"]', '1165623607.38darren': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1165623607.38darren"]', '1165627325.38darren': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1165627325.38darren"]', '1165628953.92darren': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1165628953.92darren"]', '1166059404.52darren': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1166059404.52darren"]', '1173229521.39kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173229521.39kmuller"]', '1173229567.69kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173229567.69kmuller"]', '1173229671.59kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173229671.59kmuller"]', '1173230223.73kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173230223.73kmuller"]', '1173230369.33kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173230369.33kmuller"]', '1173463985.56kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173463985.56kmuller"]', '1173463999.64kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173463999.64kmuller"]', '1173464070.8kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173464070.8kmuller"]', '1173464100.87kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173464100.87kmuller"]', '1173464157.41kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173464157.41kmuller"]', '1173464182.53kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173464182.53kmuller"]', '1173464199.89kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173464199.89kmuller"]', '1173464218.62kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173464218.62kmuller"]', '1173847187.11MAsaduzz': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173847187.11MAsaduzz"]', '1173847246.41MAsaduzz': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1173847246.41MAsaduzz"]', '1175286835.45kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1175286835.45kmuller"]', '1185558037.1kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185558037.1kmuller"]', '1185558089.04kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185558089.04kmuller"]', '1185558130.63kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185558130.63kmuller"]', '1185558177.77kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185558177.77kmuller"]', '1185558217.46kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185558217.46kmuller"]', '1185558288.27kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185558288.27kmuller"]', '1185558346.82kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185558346.82kmuller"]', '1185559934.46kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185559934.46kmuller"]', '1185559985.48kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185559985.48kmuller"]', '1185560136.51kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185560136.51kmuller"]', '1185560262.56kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185560262.56kmuller"]', '1185560641.42kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185560641.42kmuller"]', '1185560910.95kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185560910.95kmuller"]', '1185561940.49kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185561940.49kmuller"]', '1185562015.71kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185562015.71kmuller"]', '1185568481.4kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185568481.4kmuller"]', '1185568513.93kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185568513.93kmuller"]', '1185568547.6kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185568547.6kmuller"]', '1185568598.81kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185568598.81kmuller"]', '1185568716.62kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185568716.62kmuller"]', '1185568738.67kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185568738.67kmuller"]', '1185568820.96kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185568820.96kmuller"]', '1185568896.48kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185568896.48kmuller"]', '1185568933.01kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185568933.01kmuller"]', '1185568959.85kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1185568959.85kmuller"]', '1187113409.44akelts': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1187113409.44akelts"]', '1190757402.45joswilso': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1190757402.45joswilso"]', '1192217827.01MAsaduzz': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1192217827.01MAsaduzz"]', '1202153999.87kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1121212983.08Shochet"]["Objects"]["1202153999.87kmuller"]', '1202154001.04kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1121212983.08Shochet"]["Objects"]["1202154001.04kmuller"]', '1202154005.44kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1158195990.71jubutler"]["Objects"]["1202154005.44kmuller"]', '1202154006.23kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202154006.23kmuller"]', '1202154006.26kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202154006.26kmuller"]', '1202161377.6kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202161377.6kmuller"]', '1202161413.51kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202161413.51kmuller"]', '1202161534.07kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202161534.07kmuller"]', '1202161588.49kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202161588.49kmuller"]', '1202161746.02kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202161746.02kmuller"]', '1202161775.05kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202161775.05kmuller"]', '1202161796.07kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202161796.07kmuller"]', '1202161860.73kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202161534.07kmuller"]["Objects"]["1202161860.73kmuller"]', '1202168756.79kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202168756.79kmuller"]', '1202169076.35kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202169076.35kmuller"]', '1202169076.35kmuller0': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202169076.35kmuller"]', '1202171181.34kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202171181.34kmuller"]', '1202171254.79kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1202171254.79kmuller"]', '1205367808.78kmuller': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1205367808.78kmuller"]', '1224631808.0masad1': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1224631808.0masad1"]', '1224631936.0masad': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1224631936.0masad"]', '1232044484.61akelts': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1232044484.61akelts"]', '1232044553.83akelts': '["Objects"]["1115838800a.3jubutler"]["Objects"]["1232044553.83akelts"]'}}
extraInfo = {'camPos': Point3(0, -14, 0), 'camHpr': VBase3(0, 0, 0), 'focalLength': 0.852999985218, 'skyState': 2, 'fog': 0} | 10,347.285714 | 72,021 | 0.675871 |
9c79c896e8dbcb605956fd91fba71201a76633db | 1,207 | py | Python | dreamer/envs/one_hot.py | rainwangphy/dreamer-pytorch | 0adc589a10dab1ff414c42865018443561978c4d | [
"MIT"
] | null | null | null | dreamer/envs/one_hot.py | rainwangphy/dreamer-pytorch | 0adc589a10dab1ff414c42865018443561978c4d | [
"MIT"
] | null | null | null | dreamer/envs/one_hot.py | rainwangphy/dreamer-pytorch | 0adc589a10dab1ff414c42865018443561978c4d | [
"MIT"
] | null | null | null | import gym
import numpy as np
from rlpyt.spaces.float_box import FloatBox
from rlpyt.spaces.int_box import IntBox
from dreamer.envs.wrapper import EnvWrapper
class OneHotAction(EnvWrapper):
def __init__(self, env):
assert isinstance(env.action_space, gym.spaces.Discrete) or isinstance(env.action_space, IntBox)
super().__init__(env)
self._dtype = np.float32
@property
def action_space(self):
shape = (self.env.action_space.n,)
space = FloatBox(low=0, high=1, shape=shape, dtype=self._dtype)
space.sample = self._sample_action
return space
def step(self, action):
index = np.argmax(action).astype(int)
reference = np.zeros_like(action)
reference[index] = 1
if not np.allclose(reference, action, atol=1e6):
raise ValueError(f'Invalid one-hot action:\n{action}')
return self.env.step(index)
def reset(self):
return self.env.reset()
def _sample_action(self):
actions = self.env.action_space.n
index = self.random.randint(0, actions)
reference = np.zeros(actions, dtype=self._dtype)
reference[index] = 1.0
return reference
| 30.175 | 104 | 0.661972 |
4a2b2c183a702c69692ddb9e1292d23f983879e8 | 3,590 | py | Python | reinforcement_learning.py | AshitakaLax/CS5890-smart-thermostat | 33c5e3e0a6fc012f03bd49a1a2639cf28bd55166 | [
"MIT"
] | 4 | 2019-02-01T12:43:16.000Z | 2020-06-18T12:37:26.000Z | reinforcement_learning.py | AshitakaLax/CS5890-smart-thermostat | 33c5e3e0a6fc012f03bd49a1a2639cf28bd55166 | [
"MIT"
] | null | null | null | reinforcement_learning.py | AshitakaLax/CS5890-smart-thermostat | 33c5e3e0a6fc012f03bd49a1a2639cf28bd55166 | [
"MIT"
] | 2 | 2019-10-02T16:48:41.000Z | 2021-07-05T18:06:43.000Z | from models import HVAC
from models import HvacBuilding
from environments import HvacBuildingEnvironment
from util import HvacBuildingTracker
import numpy as np
from tensorforce.agents import PPOAgent
from tensorforce.execution import Runner
from tensorforce.contrib.openai_gym import OpenAIGym
# Create an instance of HVAC to simulate the Furnance
# use any parameters specific for your furnace
hvac = HVAC()
# Create the hvac building tracker to keep track of the simulation over time
tracker = HvacBuildingTracker()
# create the building model with the hvac and the tracker
conditioned_floor_area = 100
hvacBuilding = HvacBuilding(
hvac,
heat_mass_capacity=16500 * conditioned_floor_area,
heat_transmission=200,
initial_building_temperature=18,
conditioned_floor_area=conditioned_floor_area,
hvacBuildingTracker = tracker
)
environment = HvacBuildingEnvironment(hvacBuilding)
# a set of temperatures in Northern Utah, USA for one day
loganOutsideTemperatures = [1.11, 2.22, 1.67, 1.67, 2.22, 1.11, 1.11, 2.78, 4.44, 4.44, 5.56, 6.67, 6.67, 7.22, 6.67, 2.22, 2.22, 1.67, 1.11, 1.11, 0.56, 1.11, 0.00, 0.00]
print()
print("Starting Hvac Building Example")
print()
# simulate one day
numberOfHeatingOn = 0
# for outsideTemperature in loganOutsideTemperatures:
# # iterate through one hour with the same temperature
# for i in range(3600):
# hvacBuilding.step(outsideTemperature)
# if not hvac.HeatingIsShuttingDown and hvac.HeatingIsOn and hvacBuilding.current_temperature > 18.8889:#21:
# #print("Turning the Heater Off")
# hvac.TurnHeatingOff()
# if hvac.HeatingIsOn == False and hvacBuilding.current_temperature < 17.7778:#17:
# #print("Turning the Heater On")
# numberOfHeatingOn = numberOfHeatingOn + 1
# hvac.TurnHeatingOn()
#hvacBuilding.PrintSummary()
# todo run a loop with various parameters for the set points to determine the optimal temperature in terms of the delta
# Create a Proximal Policy Optimization agent
agent = PPOAgent(
states=dict(type='float', shape=(3,)),
actions=dict(type='bool', num_actions=1),
network=[
dict(type='dense', size=64),
dict(type='dense', size=64)
],
batching_capacity=1000,
step_optimizer=dict(
type='adam',
learning_rate=1e-4
)
)
def episode_finished(r):
if r.episode % 10 == 0:
print("Finished episode {ep} after {ts} timesteps".format(ep=r.episode + 1, ts=r.timestep + 1))
print("Episode reward: {}".format(r.episode_rewards[-1]))
print("Average of last 10 rewards: {}".format(np.mean(r.episode_rewards[-10:])))
return True
runner = Runner(agent, environment)
runner.run(num_timesteps=3600, num_episodes=3, episode_finished= episode_finished)
# Poll new state from client
#for outsideTemperature in loganOutsideTemperatures:
for i in range(2):
outsideTemperature = 1.1
# iterate through one hour with the same temperature
for i in range(3600):
state = hvacBuilding.get_state(outsideTemperature)
action = agent.act(state, True)
reward = hvacBuilding.Act(action)
agent.observe(reward=reward, terminal=False)
hvacBuilding.step(outsideTemperature)
#currently the only state is to turn on cooling or turn off
# if not hvac.HeatingIsShuttingDown and hvac.HeatingIsOn and hvacBuilding.current_temperature > 18.8889:#21:
# #print("Turning the Heater Off")
# hvac.TurnHeatingOff()
# if hvac.HeatingIsOn == False and hvacBuilding.current_temperature < 17.7778:#17:
# #print("Turning the Heater On")
# numberOfHeatingOn = numberOfHeatingOn + 1
# hvac.TurnHeatingOn()
| 34.854369 | 171 | 0.739554 |
723b95800dd491bd4eb1a288b635e6becc898e15 | 9,847 | py | Python | docs/conf.py | wildlifeai/wai_data_tools | 1e448361dadec769ad4cfedcd556b81f0eceb768 | [
"MIT"
] | null | null | null | docs/conf.py | wildlifeai/wai_data_tools | 1e448361dadec769ad4cfedcd556b81f0eceb768 | [
"MIT"
] | 1 | 2022-03-14T20:25:57.000Z | 2022-03-14T20:25:57.000Z | docs/conf.py | wildlifeai/wai_data_tools | 1e448361dadec769ad4cfedcd556b81f0eceb768 | [
"MIT"
] | null | null | null | # This file is execfile()d with the current directory set to its containing dir.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
#
# All configuration values have a default; values that are commented out
# serve to show the default.
"""Configuration file for sphinx."""
import os
import shutil
import sys
# -- Path setup --------------------------------------------------------------
__location__ = os.path.dirname(__file__)
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.join(__location__, "../src"))
# -- Run sphinx-apidoc -------------------------------------------------------
# This hack is necessary since RTD does not issue `sphinx-apidoc` before running
# `sphinx-build -b html . _build/html`. See Issue:
# https://github.com/readthedocs/readthedocs.org/issues/1139
# DON'T FORGET: Check the box "Install your project inside a virtualenv using
# setup.py install" in the RTD Advanced Settings.
# Additionally it helps us to avoid running apidoc manually
try: # for Sphinx >= 1.7
from sphinx.ext import apidoc
except ImportError:
from sphinx import apidoc
output_dir = os.path.join(__location__, "api")
module_dir = os.path.join(__location__, "../src/wai_data_tools")
try:
shutil.rmtree(output_dir)
except FileNotFoundError:
pass
try:
import sphinx
cmd_line = f"sphinx-apidoc --implicit-namespaces -f -o {output_dir} {module_dir}"
args = cmd_line.split(" ")
if tuple(sphinx.__version__.split(".")) >= ("1", "7"):
# This is a rudimentary parse_version to avoid external dependencies
args = args[1:]
apidoc.main(args)
except Exception as e:
print("Running `sphinx-apidoc` failed!\n{}".format(e))
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.todo",
"sphinx.ext.autosummary",
"sphinx.ext.viewcode",
"sphinx.ext.coverage",
"sphinx.ext.doctest",
"sphinx.ext.ifconfig",
"sphinx.ext.mathjax",
"sphinx.ext.napoleon",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = ".rst"
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "wai_data_tools"
copyright = "2022, David Andersson"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# version: The short X.Y version.
# release: The full version, including alpha/beta/rc tags.
# If you don’t need the separation provided between version and release,
# just set them both to the same value.
try:
from wai_data_tools import __version__ as version
except ImportError:
version = ""
if not version or version.lower() == "unknown":
version = os.getenv("READTHEDOCS_VERSION", "unknown") # automatically set by RTD
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".venv"]
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If this is True, todo emits a warning for each TODO entries. The default is False.
todo_emit_warnings = True
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "alabaster"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {"sidebar_width": "300px", "page_width": "1200px"}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = ""
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = "wai_data_tools-doc"
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ("letterpaper" or "a4paper").
# "papersize": "letterpaper",
# The font size ("10pt", "11pt" or "12pt").
# "pointsize": "10pt",
# Additional stuff for the LaTeX preamble.
# "preamble": "",
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
(
"index",
"user_guide.tex",
"wai_data_tools Documentation",
"David Andersson",
"manual",
)
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = ""
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- External mapping --------------------------------------------------------
python_version = ".".join(map(str, sys.version_info[0:2]))
intersphinx_mapping = {
"sphinx": ("https://www.sphinx-doc.org/en/master", None),
"python": ("https://docs.python.org/" + python_version, None),
"matplotlib": ("https://matplotlib.org", None),
"numpy": ("https://numpy.org/doc/stable", None),
"sklearn": ("https://scikit-learn.org/stable", None),
"pandas": ("https://pandas.pydata.org/pandas-docs/stable", None),
"scipy": ("https://docs.scipy.org/doc/scipy/reference", None),
"setuptools": ("https://setuptools.pypa.io/en/stable/", None),
"pyscaffold": ("https://pyscaffold.org/en/stable", None),
}
print(f"loading configurations for {project} {version} ...", file=sys.stderr)
| 33.838488 | 85 | 0.696354 |
7e2a006f8a48c7ec0b86a23e51af12a2eb348bdb | 4,004 | py | Python | examples/basic_operations/add_expanded_text_ads.py | ale180192/google-ads-python | d20b5882ae97e9951b24979ac312219eaea58d58 | [
"Apache-2.0"
] | null | null | null | examples/basic_operations/add_expanded_text_ads.py | ale180192/google-ads-python | d20b5882ae97e9951b24979ac312219eaea58d58 | [
"Apache-2.0"
] | null | null | null | examples/basic_operations/add_expanded_text_ads.py | ale180192/google-ads-python | d20b5882ae97e9951b24979ac312219eaea58d58 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example adds an expanded text ad.
To get expanded text ads, run get_expanded_text_ads.py.
"""
from __future__ import absolute_import
import argparse
import six
import sys
import uuid
import google.ads.google_ads.client
def main(client, customer_id, ad_group_id, number_of_ads):
ad_group_ad_service = client.get_service('AdGroupAdService', version='v2')
ad_group_service = client.get_service('AdGroupService', version='v2')
ad_group_ad_operations = []
for i in range(number_of_ads):
# Create ad group ad.
ad_group_ad_operation = client.get_type('AdGroupAdOperation', version='v2')
ad_group_ad = ad_group_ad_operation.create
ad_group_ad.ad_group.value = ad_group_service.ad_group_path(
customer_id, ad_group_id)
ad_group_ad.status = client.get_type('AdGroupAdStatusEnum',
version='v2').PAUSED
# Set expanded text ad info
final_url = ad_group_ad.ad.final_urls.add()
final_url.value = 'http://www.example.com'
ad_group_ad.ad.expanded_text_ad.description.value = 'Buy your tickets now!'
ad_group_ad.ad.expanded_text_ad.headline_part1.value = (
'Cruise {} to Mars {}'.format(i, str(uuid.uuid4())[:8]))
ad_group_ad.ad.expanded_text_ad.headline_part2.value = (
'Best space cruise line')
ad_group_ad.ad.expanded_text_ad.path1.value = 'all-inclusive'
ad_group_ad.ad.expanded_text_ad.path2.value = 'deals'
ad_group_ad_operations.append(ad_group_ad_operation)
try:
ad_group_ad_response = ad_group_ad_service.mutate_ad_group_ads(
customer_id, ad_group_ad_operations)
except google.ads.google_ads.errors.GoogleAdsException as ex:
print('Request with ID "{}" failed with status "{}" and includes the '
'following errors:'.format(ex.request_id, ex.error.code().name))
for error in ex.failure.errors:
print('\tError with message "{}".'.format(error.message))
if error.location:
for field_path_element in error.location.field_path_elements:
print('\t\tOn field: {}'.format(field_path_element.field_name))
sys.exit(1)
for result in ad_group_ad_response.results:
print('Created ad group ad {}.'.format(result.resource_name))
if __name__ == '__main__':
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
google_ads_client = (google.ads.google_ads.client.GoogleAdsClient
.load_from_storage())
parser = argparse.ArgumentParser(
description=('Adds an expanded text ad to the specified ad group ID, '
'for the given customer ID.'))
# The following argument(s) should be provided to run the example.
parser.add_argument('-c', '--customer_id', type=six.text_type,
required=True, help='The Google Ads customer ID.')
parser.add_argument('-a', '--ad_group_id', type=six.text_type,
required=True, help='The ad group ID.')
parser.add_argument('-n', '--number_of_ads', type=int,
required=False, default=1, help='The number of ads.')
args = parser.parse_args()
main(google_ads_client, args.customer_id, args.ad_group_id, args.number_of_ads)
| 42.147368 | 83 | 0.680569 |
870b8949db2e0065da208da74ded1d90c6d97e7e | 381 | py | Python | src/random_book_names/__main__.py | vgoehler/python-random-book-names | b802e4e15ce59c692698a0437deb2f72989fd8b1 | [
"BSD-3-Clause"
] | null | null | null | src/random_book_names/__main__.py | vgoehler/python-random-book-names | b802e4e15ce59c692698a0437deb2f72989fd8b1 | [
"BSD-3-Clause"
] | 1 | 2020-03-02T10:13:52.000Z | 2020-03-02T10:13:52.000Z | src/random_book_names/__main__.py | vgoehler/python-random-book-names | b802e4e15ce59c692698a0437deb2f72989fd8b1 | [
"BSD-3-Clause"
] | null | null | null | """
Entrypoint module, in case you use `python -mrandom_book_names`.
Why does this file exist, and why __main__? For more info, read:
- https://www.python.org/dev/peps/pep-0338/
- https://docs.python.org/2/using/cmdline.html#cmdoption-m
- https://docs.python.org/3/using/cmdline.html#cmdoption-m
"""
from random_book_names.cli import main
if __name__ == "__main__":
main()
| 25.4 | 64 | 0.729659 |
94269a460bb2c615cbcf9d8b3fac000425fc99b8 | 5,760 | py | Python | tests/unit/test_galera.py | ovaistariq/proxysql-tools | f775fe5de908756da8522092450aec7171fbdbb3 | [
"Apache-2.0"
] | null | null | null | tests/unit/test_galera.py | ovaistariq/proxysql-tools | f775fe5de908756da8522092450aec7171fbdbb3 | [
"Apache-2.0"
] | null | null | null | tests/unit/test_galera.py | ovaistariq/proxysql-tools | f775fe5de908756da8522092450aec7171fbdbb3 | [
"Apache-2.0"
] | 1 | 2021-11-20T08:37:48.000Z | 2021-11-20T08:37:48.000Z | import pytest
from doubles import allow, expect
from proxysql_tools.entities.galera import (
GaleraConfig,
GaleraNode,
LOCAL_STATE_SYNCED,
LOCAL_STATE_DONOR_DESYNCED
)
from proxysql_tools.entities.proxysql import (
ProxySQLMySQLBackend,
BACKEND_STATUS_ONLINE,
BACKEND_STATUS_OFFLINE_SOFT
)
from proxysql_tools.galera import (
fetch_galera_manager,
deregister_unhealthy_backends,
fetch_nodes_blacklisted_for_writers
)
from proxysql_tools.managers.proxysql_manager import ProxySQLManager
def test__fetch_galera_manager_can_create_galera_manager_object_with_valid_config(mocker): # NOQA
galera_config = GaleraConfig({
'writer_hostgroup_id': 10,
'reader_hostgroup_id': 11,
'cluster_host': '192.168.30.51:3306',
'cluster_username': 'cluster_user',
'cluster_password': 'cluster_password',
'load_balancing_mode': 'singlewriter'
})
mock_func = mocker.patch('proxysql_tools.galera.GaleraManager').discover_cluster_nodes # NOQA
mock_func.return_value = True
assert fetch_galera_manager(galera_config)
def test__fetch_galera_manager_raises_exception_on_incorrect_cluster_host_config(): # NOQA
galera_config = GaleraConfig({
'writer_hostgroup_id': 10,
'reader_hostgroup_id': 11,
'cluster_host': '192.168.30.51_3306',
'cluster_username': 'cluster_user',
'cluster_password': 'cluster_password',
'load_balancing_mode': 'singlewriter'
})
with pytest.raises(ValueError):
fetch_galera_manager(galera_config)
def test__deregister_unhealthy_backends_deregisters_unhealthy_backends():
healthy_node = GaleraNode({
'host': '192.168.10.1',
'port': 3306,
'local_state': LOCAL_STATE_SYNCED
})
unhealthy_node = GaleraNode({
'host': '192.168.10.2',
'port': 3306,
'local_state': LOCAL_STATE_DONOR_DESYNCED
})
healthy_backend = ProxySQLMySQLBackend({
'status': BACKEND_STATUS_ONLINE,
'hostname': '192.168.10.1',
'port': 3306
})
unhealthy_backend = ProxySQLMySQLBackend({
'status': BACKEND_STATUS_ONLINE,
'hostname': '192.168.10.2',
'port': 3306
})
galera_nodes = [healthy_node, unhealthy_node]
backends = [healthy_backend, unhealthy_backend]
hostgroup_id = 11
proxysql_man = ProxySQLManager('127.0.0.1', 6032, 'username', 'password')
(allow(proxysql_man)
.fetch_backends
.with_args(hostgroup_id)
.and_return(backends))
(expect(proxysql_man)
.update_mysql_backend_status
.with_args(hostgroup_id, unhealthy_backend.hostname,
unhealthy_backend.port, BACKEND_STATUS_OFFLINE_SOFT)
.and_return(True))
backends_list = deregister_unhealthy_backends(proxysql_man, galera_nodes,
hostgroup_id,
[LOCAL_STATE_SYNCED])
assert len(backends_list) == 1
assert healthy_backend in backends_list
assert unhealthy_backend not in backends_list
def test__deregister_unhealthy_backends_deregisters_blacklisted_backends():
healthy_node = GaleraNode({
'host': '192.168.10.1',
'port': 3306,
'local_state': LOCAL_STATE_SYNCED
})
blacklisted_node = GaleraNode({
'host': '192.168.10.2',
'port': 3306,
'local_state': LOCAL_STATE_SYNCED
})
healthy_backend = ProxySQLMySQLBackend({
'status': BACKEND_STATUS_ONLINE,
'hostname': '192.168.10.1',
'port': 3306
})
blacklisted_backend = ProxySQLMySQLBackend({
'status': BACKEND_STATUS_ONLINE,
'hostname': '192.168.10.2',
'port': 3306
})
galera_nodes = [healthy_node, blacklisted_node]
backends = [healthy_backend, blacklisted_backend]
hostgroup_id = 11
proxysql_man = ProxySQLManager('127.0.0.1', 6032, 'username', 'password')
(allow(proxysql_man)
.fetch_backends
.with_args(hostgroup_id)
.and_return(backends))
(expect(proxysql_man)
.deregister_backend
.with_args(hostgroup_id, blacklisted_backend.hostname,
blacklisted_backend.port)
.and_return(True))
backends_list = deregister_unhealthy_backends(proxysql_man, galera_nodes,
hostgroup_id,
[LOCAL_STATE_SYNCED],
[blacklisted_node])
assert len(backends_list) == 1
assert healthy_backend in backends_list
assert blacklisted_backend not in backends_list
def test__fetch_nodes_blacklisted_for_writers_returns_correct_nodes_list():
galera_config = GaleraConfig({
'writer_hostgroup_id': 10,
'reader_hostgroup_id': 11,
'cluster_host': '192.168.30.51:3306,192.168.30.52:3306',
'cluster_username': 'cluster_user',
'cluster_password': 'cluster_password',
'load_balancing_mode': 'singlewriter',
'writer_blacklist': '192.168.30.52:3306'
})
regular_node = GaleraNode({
'host': '192.168.30.51',
'port': 3306,
'local_state': LOCAL_STATE_SYNCED
})
blacklist_node = GaleraNode({
'host': '192.168.30.52',
'port': 3306,
'local_state': LOCAL_STATE_SYNCED
})
galera_nodes = [regular_node, blacklist_node]
blacklist_nodes = fetch_nodes_blacklisted_for_writers(galera_config,
galera_nodes)
assert len(blacklist_nodes) == 1
assert regular_node not in blacklist_nodes
assert blacklist_node in blacklist_nodes
| 30.638298 | 98 | 0.650521 |
f24cd86844b8308919c86938d6a5de9fdf0a021f | 1,103 | py | Python | var/spack/repos/builtin/packages/libtiff/package.py | adrianjhpc/spack | 0a9e4fcee57911f2db586aa50c8873d9cca8de92 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | 2 | 2020-10-15T01:08:42.000Z | 2021-10-18T01:28:18.000Z | var/spack/repos/builtin/packages/libtiff/package.py | adrianjhpc/spack | 0a9e4fcee57911f2db586aa50c8873d9cca8de92 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | 2 | 2019-07-30T10:12:28.000Z | 2019-12-17T09:02:27.000Z | var/spack/repos/builtin/packages/libtiff/package.py | adrianjhpc/spack | 0a9e4fcee57911f2db586aa50c8873d9cca8de92 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | 5 | 2019-07-30T09:42:14.000Z | 2021-01-25T05:39:20.000Z | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libtiff(AutotoolsPackage):
"""LibTIFF - Tag Image File Format (TIFF) Library and Utilities."""
homepage = "http://www.simplesystems.org/libtiff/"
url = "https://download.osgeo.org/libtiff/tiff-4.0.10.tar.gz"
version('4.0.10', sha256='2c52d11ccaf767457db0c46795d9c7d1a8d8f76f68b0b800a3dfe45786b996e4')
version('4.0.9', sha256='6e7bdeec2c310734e734d19aae3a71ebe37a4d842e0e23dbb1b8921c0026cfcd')
version('4.0.8', sha256='59d7a5a8ccd92059913f246877db95a2918e6c04fb9d43fd74e5c3390dac2910')
version('4.0.7', sha256='9f43a2cfb9589e5cecaa66e16bf87f814c945f22df7ba600d63aac4632c4f019')
version('4.0.6', sha256='4d57a50907b510e3049a4bba0d7888930fdfc16ce49f1bf693e5b6247370d68c')
version('3.9.7', sha256='f5d64dd4ce61c55f5e9f6dc3920fbe5a41e02c2e607da7117a35eb5c320cef6a')
depends_on('jpeg')
depends_on('zlib')
depends_on('xz')
| 44.12 | 96 | 0.768812 |
8757db846c4a13fae2c42d7417c1d2862f7fba5c | 6,869 | py | Python | conda_build_prepare/prepare.py | hdl/conda-build-prepare | d0902ec36c147b23e660f1cddb2c06047c47476b | [
"Apache-2.0"
] | 3 | 2021-01-16T23:28:31.000Z | 2022-03-25T13:48:51.000Z | conda_build_prepare/prepare.py | hdl/conda-build-prepare | d0902ec36c147b23e660f1cddb2c06047c47476b | [
"Apache-2.0"
] | 5 | 2021-02-05T15:56:07.000Z | 2022-03-25T09:39:38.000Z | conda_build_prepare/prepare.py | hdl/conda-build-prepare | d0902ec36c147b23e660f1cddb2c06047c47476b | [
"Apache-2.0"
] | 1 | 2022-03-23T08:14:04.000Z | 2022-03-23T08:14:04.000Z | #!/usr/bin/env python3
import json
import os
import re
import shutil
import subprocess
import sys
from collections import OrderedDict
from datetime import datetime, timezone
# Conda's `pip` doesn't install `ruamel.yaml` because it finds it is already
# installed but the one from Conda has to be imported with `ruamel_yaml`
try:
from ruamel.yaml import YAML
except ModuleNotFoundError:
from ruamel_yaml import YAML
from .git_helpers import remotes, extract_github_user, _call_custom_git_cmd, \
git_get_head_time, is_inside_git_repo
from .travis import get_travis_slug
def get_local_channels():
local_channels = OrderedDict()
travis_slug = get_travis_slug()
if travis_slug:
user = extract_github_user(travis_slug)
assert user, travis_slug
local_channels[user] = None
for url in remotes('fetch').values():
user = extract_github_user(url)
if user:
local_channels[user] = None
return tuple(local_channels.keys())
# condarc_$OS has precedence, if exists and '$OS' matches the current OS
# (it can be condarc_linux, condarc_macos or condarc_windows)
def get_package_condarc(recipe_dir):
if sys.platform.startswith('linux'):
cur_os = 'linux'
elif sys.platform == 'darwin':
cur_os = 'macos'
elif sys.platform in ['cygwin', 'msys', 'win32']:
cur_os = 'windows'
else:
return None
condarc = os.path.join(recipe_dir, 'condarc')
condarc_os = condarc + '_' + cur_os
if os.path.exists(condarc_os):
return condarc_os
elif os.path.exists(condarc):
return condarc
else:
return None
def write_metadata(new_recipe_dir, original_recipe_dir):
metadata_file = os.path.join(new_recipe_dir, 'recipe_append.yaml')
metadata = {
'extra': {
'build_type': 'local'
}
}
def _try_to_get_git_output(cmd_string):
try:
return _call_custom_git_cmd(original_recipe_dir, cmd_string,
quiet=True)
except subprocess.CalledProcessError:
return 'GIT_ERROR'
# Get details of the repository containing the recipe
metadata['extra']['recipe_source'] = {
'repo': _try_to_get_git_output('remote get-url origin'),
'branch': _try_to_get_git_output('rev-parse --abbrev-ref HEAD'),
'commit': _try_to_get_git_output('rev-parse HEAD'),
'describe': _try_to_get_git_output('describe --long'),
'date': datetime.utcnow().strftime('%Y%m%d_%H%M%S'),
}
# Fill in metadata from travis environment
if os.environ.get('TRAVIS', 'false') == 'true':
metadata['extra']['build_type'] = 'travis'
metadata['extra']['travis'] = {
'job_id': int(os.environ.get('TRAVIS_JOB_ID', repr(-1))),
'job_num': os.environ.get('TRAVIS_JOB_NUMBER', repr(-1)),
'event': os.environ.get('TRAVIS_EVENT_TYPE'),
}
# Override details from git with data from travis
metadata['extra']['recipe_source'] = {
'repo': 'https://github.com/' + get_travis_slug(),
'branch': os.environ.get('TRAVIS_BRANCH', '?'),
'commit': os.environ.get('TRAVIS_COMMIT', '?'),
# Leave those two as they were before
'describe': metadata['extra']['recipe_source']['describe'],
'date': metadata['extra']['recipe_source']['date'],
}
# Fill in metadata from github_actions environment
if os.environ.get('GITHUB_ACTIONS', 'false') == 'true':
metadata['extra']['build_type'] = 'github_actions'
metadata['extra']['github_actions'] = {
'action_id': os.environ.get('GITHUB_ACTION'),
'run_id': os.environ.get('GITHUB_RUN_ID'),
'run_num': os.environ.get('GITHUB_RUN_NUMBER'),
'event': os.environ.get('GITHUB_EVENT_NAME'),
}
# Override details from git with data from github_actions
metadata['extra']['recipe_source'] = {
'repo': 'https://github.com/' + os.environ.get('GITHUB_REPOSITORY'),
'branch': os.environ.get('GITHUB_REF', '?'),
'commit': os.environ.get('GITHUB_SHA'),
# Leave those two as they were before
'describe': metadata['extra']['recipe_source']['describe'],
'date': metadata['extra']['recipe_source']['date'],
}
toolchain_arch = os.environ.get('TOOLCHAIN_ARCH')
if toolchain_arch is not None:
metadata['extra']['toolchain_arch'] = toolchain_arch
package_condarc = get_package_condarc(new_recipe_dir)
if package_condarc is not None:
with open(package_condarc, 'r') as condarc_file:
condarc = YAML().load(condarc_file)
metadata['extra']['condarc'] = condarc
with open(metadata_file, "w") as meta:
YAML().dump(metadata, meta)
def _get_latest_mtime_in_dir(directory):
all_dir_mtimes = []
for _dir,_,files in os.walk(directory):
for f in files:
file_mtime = os.path.getmtime(os.path.join(_dir, f))
all_dir_mtimes.append(file_mtime)
latest_timestamp = max(all_dir_mtimes)
return datetime.fromtimestamp(latest_timestamp, timezone.utc)
def _set_date_env_vars(recipe_dir):
def _set_env_var(name, value):
print(f"Setting environment variable: {name} = {value}")
os.environ[name] = value
if 'DATE_STR' not in os.environ:
if is_inside_git_repo(recipe_dir):
datetime = git_get_head_time(recipe_dir)
else:
datetime = _get_latest_mtime_in_dir(recipe_dir)
date_str = datetime.strftime('%Y%m%d_%H%M%S')
_set_env_var('DATE_STR', date_str)
# Make sure `DATE_NUM` is always a digit-only version of `DATE_STR`
date_num = re.sub(r"[^0-9]", "", os.environ['DATE_STR'])
if 'DATE_NUM' not in os.environ or os.environ['DATE_NUM'] != date_num:
_set_env_var('DATE_NUM', date_num)
print()
def prepare_directory(recipe_dir, dest_dir):
assert os.path.exists(recipe_dir)
assert not os.path.exists(dest_dir)
# Set DATE_NUM and DATE_STR environment variables used by many recipes
_set_date_env_vars(recipe_dir)
shutil.copytree(recipe_dir, dest_dir)
# Prescript
prescript_name = f"prescript.{os.environ.get('TOOLCHAIN_ARCH') or ''}.sh"
prescript_path = os.path.join(dest_dir, prescript_name)
if os.path.exists(prescript_path):
print('\nPrescript file found! Executing...\n')
subprocess.check_call(['bash', prescript_path], env=os.environ, cwd=dest_dir,
# shell=True only on Windows
shell=sys.platform in ['cygwin', 'msys', 'win32'])
print('\nFinished executing prescript.\n')
write_metadata(dest_dir, recipe_dir)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 35.045918 | 85 | 0.643907 |
69413e9e7bdd7da56a66da6494670de39136b740 | 828 | py | Python | app/core/admin.py | JoaoAPS/BugTracker | 5bb2db85227201c18e50e0fa07822b0623289ec4 | [
"MIT"
] | null | null | null | app/core/admin.py | JoaoAPS/BugTracker | 5bb2db85227201c18e50e0fa07822b0623289ec4 | [
"MIT"
] | null | null | null | app/core/admin.py | JoaoAPS/BugTracker | 5bb2db85227201c18e50e0fa07822b0623289ec4 | [
"MIT"
] | null | null | null | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from members.models import Member
from projects.models import Project
from bugs.models import Bug
class UserAdmin(BaseUserAdmin):
list_display = ('name', 'email', 'is_superuser')
list_filter = ('is_superuser',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('name',)}),
('Permissions', {'fields': ('is_superuser', 'is_staff')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('name', 'email', 'password1', 'password2'),
}),
)
search_fields = ('name', 'email')
ordering = ('name',)
admin.site.register(Member, UserAdmin)
admin.site.register(Project)
admin.site.register(Bug)
| 27.6 | 66 | 0.618357 |
e1a602b68187bf4e5e00d11130517f3c3744d57e | 9,443 | py | Python | simplemaps/BasemapUtils.py | calebrob6/simple-maps | 2e84fe8d2297eb054855bdd5d6760f4ae1a3711a | [
"MIT"
] | 4 | 2017-02-24T01:31:28.000Z | 2019-06-02T04:59:16.000Z | simplemaps/BasemapUtils.py | calebrob6/simple-maps | 2e84fe8d2297eb054855bdd5d6760f4ae1a3711a | [
"MIT"
] | null | null | null | simplemaps/BasemapUtils.py | calebrob6/simple-maps | 2e84fe8d2297eb054855bdd5d6760f4ae1a3711a | [
"MIT"
] | 1 | 2021-06-14T08:45:08.000Z | 2021-06-14T08:45:08.000Z | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 Caleb Robinson <calebrob6@gmail.com>
#
# Distributed under terms of the MIT license.
import os
import pickle
import hashlib
from mpl_toolkits.basemap import Basemap
import time
import numpy as np
import matplotlib
import fiona
import shapely
import shapely.geometry
import shapely.ops
KWARGS_IGNORE = ["cacheDir","verbose"]
DEFAULT_CACHE_LOCATION = os.path.join(os.path.expanduser("~"), ".BasemapUtilsCache/")
def getBounds(fn):
'''Takes the filename of a shapefile as input, returns the lat/lon bounds in the form:
(minLatitude,maxLatitude), (minLongitude,maxLongitude)
'''
f = fiona.open(fn)
bounds = f.bounds # In the format (w, s, e, n)
f.close()
return (bounds[1],bounds[3]),(bounds[0],bounds[2])
def getShapefileColumnHeaders(fn):
'''Returns all of the column headers from a given shapefile
'''
f = fiona.open(fn)
headers = f[0]["properties"].keys()
f.close()
return headers
def getShapefileColumn(fn, dataHeader, primaryKeyHeader=None):
'''Takes the filename of a shapefile, the name of the column of data to extract, and optionally the name of the column of data to use as keys.abs
If primaryKey is None, then this method will return the a list of all the values in the "dataHeader" column.
If primaryKey is defined, then this method will return a dict where key=>value pairs are primaryKeyValue=>dataValue for each row.
'''
f = fiona.open(fn)
# Check to make sure the column headers are in the file
headers = f[0]["properties"].keys()
assert dataHeader in headers, "dataHeader %s not in %s" % (dataHeader, headers)
if primaryKeyHeader is not None:
assert primaryKeyHeader in headers, "primaryKeyHeader %s not in %s" % (primaryKeyHeader, headers)
if primaryKeyHeader is not None:
data = {}
for row in f:
primaryKey = row["properties"][primaryKeyHeader]
if primaryKey not in data:
data[primaryKey] = row["properties"][dataHeader]
else:
raise ValueError("Primary key column is not unique (duplicate value found: %r)" % (primaryKey))
else:
data = []
for row in f:
data.append(row["properties"][dataHeader])
f.close()
return data
def getBasemapWrapperHash(*args, **kwargs):
newKwargs = {}
for k,v in kwargs.items():
if k not in KWARGS_IGNORE:
newKwargs[k] = v
uniqueRepr = str(set(tuple(newKwargs.items()))).encode('utf-8')
hashed = str(hashlib.sha224(uniqueRepr).hexdigest())
return hashed
def getCacheDir(cacheDir,verbose=False):
if cacheDir is None:
cacheDir = DEFAULT_CACHE_LOCATION
if verbose:
print("cacheDir was not set, using the default location: %s" % (cacheDir))
outputBase = os.path.dirname(cacheDir)
if outputBase!='' and not os.path.exists(outputBase):
if verbose:
print("Output directory does not exist, making output dirs: %s" % (outputBase))
os.makedirs(outputBase)
return outputBase
def shapelyTransformIdentityFunction(x, y, z=None):
return tuple(filter(None, [x, y, z]))
def getPolygonPatches(transformer, shapefileFn, shapefileKey, filterList=None):
if transformer is None:
transformer = shapelyTransformIdentityFunction
sf = fiona.open(shapefileFn)
rows = []
for row in sf:
rows.append(row)
sf.close()
shapes = []
keys = []
for i,entry in enumerate(rows):
geo = entry["geometry"]
primaryKey = entry["properties"][shapefileKey]
if filterList is not None:
if primaryKey not in filterList:
continue
if geo["type"]=="MultiPolygon":
#we need to split each MultiPolygon up into individual ones
for coordList in entry["geometry"]["coordinates"]:
newGeo = {
"type" : "Polygon",
"coordinates" : coordList
}
shape = shapely.geometry.shape(newGeo)
shapes.append(shape)
keys.append(primaryKey)
elif geo["type"]=="Polygon":
shape = shapely.geometry.shape(geo)
shapes.append(shape)
keys.append(primaryKey)
else:
raise ValueError("There is some kind of weird shape in shapefile?")
patches = []
xMax, xMin = float('-inf'), float('inf')
yMax, yMin = float('-inf'), float('inf')
for i in range(len(keys)):
shape = shapes[i]
newShape = shapely.ops.transform(transformer, shape)
x,y = newShape.exterior.xy
tXmin, tXmax = min(x),max(x)
tYmin, tYmax = min(y),max(y)
xMax = max(xMax, tXmax)
xMin = min(xMin, tXmin)
yMax = max(yMax, tYmax)
yMin = min(yMin, tYmin)
polygon = matplotlib.patches.Polygon(np.array([x,y]).T, closed=True, facecolor='grey', zorder=0, alpha=1, linewidth=1)
patches.append(polygon)
return patches, keys, [(xMin,xMax), (yMin, yMax)]
def PolygonPatchesWrapper(transformer, shapefileFn, shapefileKey, filterList=None, cacheDir=None, basemapArgs=None, verbose=False):
'''Wrapper around the getPolygonPatches method that will cache the results as a pickled file to reduce long loading times.
As there isn't a good way to get a general hash of the transformer function, you need to pass the basemapArgs dict to this function
so it can differentiate between shapefiles loaded with different transformers.
'''
outputBase = getCacheDir(cacheDir,verbose=verbose)
basemapHash = getBasemapWrapperHash(**basemapArgs)
hashedRepresentation = {
"basemapHash" : basemapHash,
"shapefileFn" : shapefileFn,
"shapefileKey" : shapefileKey,
"filterList" : ','.join(map(str,filterList)) if filterList is not None else "None"
}
uniqueRepr = str(set(tuple(hashedRepresentation.items()))).encode('utf-8')
hashedFn = str(hashlib.sha224(uniqueRepr).hexdigest()) + ".p"
newFn = os.path.join(outputBase,hashedFn)
if os.path.isfile(newFn):
startTime = float(time.time())
if verbose:
print("Loading from file: %s" % (newFn))
patches, keys, bounds = pickle.load(open(newFn,'rb'))
if verbose:
print("Finished loading from file in %0.4f seconds" % (time.time()-startTime))
else:
startTime = float(time.time())
if verbose:
print("Creating object and saving to file: %s" % (newFn))
patches, keys, bounds = getPolygonPatches(transformer, shapefileFn, shapefileKey, filterList=filterList)
pickle.dump([patches, keys, bounds],open(newFn,'wb'),-1)
if verbose:
print("Finished creating object and saving to file in %0.4f seconds" % (time.time()-startTime))
return patches, keys, bounds
def BasemapWrapper(*args, **kwargs):
'''Wrapper around Matplotlib's Basemap class that caches instantiated Basemap objects with pickle to avoid the longer waittimes
from creating an object with any of the higher resolution settings (resolution="f" can take minutes to load).
You should be able to call this method in the same way as a normal Basemap object. For example:
basemapArgs = {
"projection":'merc',
"llcrnrlat":lats[0],
"urcrnrlat":lats[1],
"llcrnrlon":lons[0],
"urcrnrlon":lons[1],
"resolution":None,
"fix_aspect":True,
"suppress_ticks":True,
# Extra arguments -----------------------------
"cahceDir="/home/user/.BasemapUtilCache/",
"verbose":verbose
}
m = BasemapWrapper(**basemapArgs)
Set cacheDir="/absolute/path/to/cache/" as a keyword argument to specify where the pickled objects will be saved.
Set verbose=True to see what is going on
'''
assert len(args)==0, "Shouldn't be calling Basemap with any positional arguments..."
verbose = False
if "verbose" not in kwargs:
verbose = False
else:
verbose = kwargs["verbose"]
assert type(verbose) == bool
if verbose:
print("Starting BasemapWrapper")
cacheDir = kwargs["cacheDir"] if "cacheDir" in kwargs else None
outputBase = getCacheDir(cacheDir,verbose=verbose)
newKwargs = {}
for k,v in kwargs.items():
if k not in KWARGS_IGNORE:
newKwargs[k] = v
hashedFn = getBasemapWrapperHash(**kwargs)
newFn = os.path.join(outputBase,hashedFn)
if os.path.isfile(newFn):
startTime = float(time.time())
if verbose:
print("Loading from file: %s" % (newFn))
m = pickle.load(open(newFn,'rb'))
if verbose:
print("Finished loading from file in %0.4f seconds" % (time.time()-startTime))
else:
startTime = float(time.time())
if verbose:
print("Creating object and saving to file: %s" % (newFn))
m = Basemap(*args, **newKwargs)
pickle.dump(m,open(newFn,'wb'),-1)
if verbose:
print("Finished creating object and saving to file in %0.4f seconds" % (time.time()-startTime))
return m
if __name__ == "__main__":
import matplotlib.pyplot as plt
getShapefileColumn("examples/cb_2015_us_county_500k/cb_2015_us_county_500k.shp","GEOID") | 33.725 | 149 | 0.635603 |
064a847b180b69a93788007e037ffbe50b21a55c | 1,542 | py | Python | app.py | jesseinit/flask_libreoffice_api | cc3b2cda12e18a43498b4bf9990e5fd867f5bab1 | [
"MIT"
] | null | null | null | app.py | jesseinit/flask_libreoffice_api | cc3b2cda12e18a43498b4bf9990e5fd867f5bab1 | [
"MIT"
] | null | null | null | app.py | jesseinit/flask_libreoffice_api | cc3b2cda12e18a43498b4bf9990e5fd867f5bab1 | [
"MIT"
] | null | null | null | import subprocess
import os
from pathlib import Path
from uuid import uuid4
from flask import Flask, request, send_from_directory, g
UPLOAD_DIRECTORY = str(Path.home())
MAX_FILE_SIZE = int(os.getenv('MAX_FILE_SIZE', 30)) #In Megabyte
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_DIRECTORY
app.config['MAX_CONTENT_LENGTH'] = MAX_FILE_SIZE * 1000 * 1000
@app.route("/health", methods=['GET'])
def health():
return {"message": "up like a murtherrrr "}, 200
@app.route("/", methods=['GET'])
def index():
return {"message": "hello"}, 200
@app.route("/forms/libreoffice/convert", methods=['POST'])
def conversion_view():
file = request.files.get('files')
if not file:
return {"error": "ensure file is passing in the request"}, 422
ext = file.filename.split('.')[-1]
filename = uuid4().hex+'.'+ext
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
source_file = f'{UPLOAD_DIRECTORY}/{filename}'
subprocess.call(['libreoffice', '--headless', '--convert-to', 'pdf', source_file, "--outdir", UPLOAD_DIRECTORY])
Path(source_file).unlink(missing_ok=True)
new_name = f"{filename.split('.')[0]}.pdf"
g.dest_file = f'{UPLOAD_DIRECTORY}/{new_name}'
return send_from_directory(app.config["UPLOAD_FOLDER"], new_name, as_attachment=True)
@app.after_request
def after_request_func(response):
if hasattr(g, 'dest_file'):
Path(g.dest_file).unlink(missing_ok=True)
return response
if __name__ == '__main__':
app.run()
| 28.555556 | 116 | 0.67834 |
7aa03c9f3efc616efdc1e75366fc8c8bd99756d7 | 250 | py | Python | remove-element/remove-element.py | Atri10/Leet-code---Atri_Patel | 49fc59b9147a44ab04a66128fbb2ef259b5f7b7c | [
"MIT"
] | 1 | 2021-10-10T20:21:18.000Z | 2021-10-10T20:21:18.000Z | remove-element/remove-element.py | Atri10/Leet-code---Atri_Patel | 49fc59b9147a44ab04a66128fbb2ef259b5f7b7c | [
"MIT"
] | null | null | null | remove-element/remove-element.py | Atri10/Leet-code---Atri_Patel | 49fc59b9147a44ab04a66128fbb2ef259b5f7b7c | [
"MIT"
] | null | null | null | class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
c = 0
l = len(nums)
for i in range(l):
if nums[i] == val : c += 1
else : nums[i-c] = nums[i];
return l - c | 27.777778 | 62 | 0.44 |
89936ff44e9c897e5ba3a62ec7f079395348df6a | 2,356 | py | Python | ged4py/algorithm/abstract_graph_edit_dist.py | xpspectre/graph-distance | 5d8dee32bebde662c0ea1de026ecc2a1dbbe21ed | [
"MIT"
] | null | null | null | ged4py/algorithm/abstract_graph_edit_dist.py | xpspectre/graph-distance | 5d8dee32bebde662c0ea1de026ecc2a1dbbe21ed | [
"MIT"
] | null | null | null | ged4py/algorithm/abstract_graph_edit_dist.py | xpspectre/graph-distance | 5d8dee32bebde662c0ea1de026ecc2a1dbbe21ed | [
"MIT"
] | null | null | null | from scipy.optimize import linear_sum_assignment
import sys
import numpy as np
class AbstractGraphEditDistance(object):
def __init__(self, g1, g2):
self.g1 = g1
self.g2 = g2
def normalized_distance(self):
"""
Returns the graph edit distance between graph g1 & g2
The distance is normalized on the size of the two graphs.
This is done to avoid favorisation towards smaller graphs
"""
avg_graphlen = (len(self.g1) + len(self.g2)) / 2
return self.distance() / avg_graphlen
def distance(self):
return sum(self.edit_costs())
def edit_costs(self):
cost_matrix = self.create_cost_matrix()
row_ind,col_ind = linear_sum_assignment(cost_matrix)
return [cost_matrix[row_ind[i]][col_ind[i]] for i in range(len(row_ind))]
def create_cost_matrix(self):
"""
Creates a |N+M| X |N+M| cost matrix between all nodes in
graphs g1 and g2
Each cost represents the cost of substituting,
deleting or inserting a node
The cost matrix consists of four regions:
substitute | insert costs
-------------------------------
delete | delete -> delete
The delete -> delete region is filled with zeros
"""
n = len(self.g1)
m = len(self.g2)
cost_matrix = np.zeros((n+m, n+m))
nodes1 = self.g1.nodes()
nodes2 = self.g2.nodes()
for i, node1 in enumerate(nodes1):
for j, node2 in enumerate(nodes2):
cost_matrix[i,j] = self.substitute_cost(node1, node2)
for i in range(m):
for j in range(m):
cost_matrix[i+n,j] = self.insert_cost(i, j, nodes2)
for i in range(n):
for j in range(n):
cost_matrix[j,i+m] = self.delete_cost(i, j, nodes1)
self.cost_matrix = cost_matrix
return cost_matrix
def insert_cost(self, i, j, nodes1):
raise NotImplementedError
def delete_cost(self, i, j, nodes2):
raise NotImplementedError
def substitute_cost(self, nodes1, nodes2):
raise NotImplementedError
def print_matrix(self):
print("cost matrix:")
cost_mat = self.create_cost_matrix()
np.place(cost_mat, cost_mat==sys.maxsize, np.inf)
print(cost_mat)
| 30.597403 | 81 | 0.599321 |
47ed9e617cb268f922989f0e7cd707e7964b3e6e | 2,570 | py | Python | tensorflow/python/kernel_tests/unpack_op_test.py | miyataken999/tensorflow | a5d8217c4ed90041bea2616c14a8ddcf11ec8c03 | [
"Apache-2.0"
] | 1 | 2015-12-08T16:17:37.000Z | 2015-12-08T16:17:37.000Z | tensorflow/python/kernel_tests/unpack_op_test.py | mrax714/nearme | 4be56f381cd000e91f79209aaf150636db6fb840 | [
"Apache-2.0"
] | null | null | null | tensorflow/python/kernel_tests/unpack_op_test.py | mrax714/nearme | 4be56f381cd000e91f79209aaf150636db6fb840 | [
"Apache-2.0"
] | 1 | 2019-10-15T03:55:21.000Z | 2019-10-15T03:55:21.000Z | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functional tests for Unpack Op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
class UnpackOpTest(tf.test.TestCase):
def testSimple(self):
np.random.seed(7)
for use_gpu in False, True:
with self.test_session(use_gpu=use_gpu):
for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2):
data = np.random.randn(*shape)
# Convert data to a single tensorflow tensor
x = tf.constant(data)
# Unpack into a list of tensors
cs = tf.unpack(x, num=shape[0])
self.assertEqual(type(cs), list)
self.assertEqual(len(cs), shape[0])
cs = [c.eval() for c in cs]
self.assertAllEqual(cs, data)
def testGradients(self):
for use_gpu in False, True:
for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2):
data = np.random.randn(*shape)
shapes = [shape[1:]] * shape[0]
for i in xrange(shape[0]):
with self.test_session(use_gpu=use_gpu):
x = tf.constant(data)
cs = tf.unpack(x, num=shape[0])
err = tf.test.compute_gradient_error(x, shape, cs[i], shapes[i])
self.assertLess(err, 1e-6)
def testInferNum(self):
with self.test_session():
for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2):
x = tf.placeholder(np.float32, shape=shape)
cs = tf.unpack(x)
self.assertEqual(type(cs), list)
self.assertEqual(len(cs), shape[0])
def testCannotInferNum(self):
x = tf.placeholder(np.float32)
with self.assertRaisesRegexp(
ValueError, r'Cannot infer num from shape TensorShape\(None\)'):
tf.unpack(x)
if __name__ == '__main__':
tf.test.main()
| 34.72973 | 80 | 0.624514 |
b30643d634534b48b0b226c1b4f4aaf229748214 | 2,173 | py | Python | NALU-pytorch/models/nalu.py | mikimaus78/ml_monorepo | b2c2627ff0e86e27f6829170d0dac168d8e5783b | [
"BSD-3-Clause"
] | 51 | 2019-02-01T19:43:37.000Z | 2022-03-16T09:07:03.000Z | NALU-pytorch/models/nalu.py | mikimaus78/ml_monorepo | b2c2627ff0e86e27f6829170d0dac168d8e5783b | [
"BSD-3-Clause"
] | 3 | 2021-08-04T09:54:07.000Z | 2022-01-24T00:02:01.000Z | NALU-pytorch/models/nalu.py | mikimaus78/ml_monorepo | b2c2627ff0e86e27f6829170d0dac168d8e5783b | [
"BSD-3-Clause"
] | 35 | 2019-02-08T02:00:31.000Z | 2022-03-01T23:17:00.000Z | import math
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from .nac import NeuralAccumulatorCell
from torch.nn.parameter import Parameter
class NeuralArithmeticLogicUnitCell(nn.Module):
"""A Neural Arithmetic Logic Unit (NALU) cell [1].
Attributes:
in_dim: size of the input sample.
out_dim: size of the output sample.
Sources:
[1]: https://arxiv.org/abs/1808.00508
"""
def __init__(self, in_dim, out_dim):
super().__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.eps = 1e-10
self.G = Parameter(torch.Tensor(out_dim, in_dim))
self.nac = NeuralAccumulatorCell(in_dim, out_dim)
self.register_parameter('bias', None)
init.kaiming_uniform_(self.G, a=math.sqrt(5))
def forward(self, input):
a = self.nac(input)
g = torch.sigmoid(F.linear(input, self.G, self.bias))
add_sub = g * a
log_input = torch.log(torch.abs(input) + self.eps)
m = torch.exp(self.nac(log_input))
mul_div = (1 - g) * m
y = add_sub + mul_div
return y
def extra_repr(self):
return 'in_dim={}, out_dim={}'.format(
self.in_dim, self.out_dim
)
class NALU(nn.Module):
"""A stack of NAC layers.
Attributes:
num_layers: the number of NAC layers.
in_dim: the size of the input sample.
hidden_dim: the size of the hidden layers.
out_dim: the size of the output.
"""
def __init__(self, num_layers, in_dim, hidden_dim, out_dim):
super().__init__()
self.num_layers = num_layers
self.in_dim = in_dim
self.hidden_dim = hidden_dim
self.out_dim = out_dim
layers = []
for i in range(num_layers):
layers.append(
NeuralArithmeticLogicUnitCell(
hidden_dim if i > 0 else in_dim,
hidden_dim if i < num_layers - 1 else out_dim,
)
)
self.model = nn.Sequential(*layers)
def forward(self, x):
out = self.model(x)
return out
| 27.858974 | 66 | 0.59457 |
2ad8cb6d1a3a74098bf692e1749eb4550b4452de | 2,719 | py | Python | leetcode.com/python/979_Distribute_Coins_in_Binary_Tree.py | vansh-tiwari/coding-interview-gym | 68345725dee0007f52b7ea3550adda35ddcf1955 | [
"MIT"
] | 713 | 2019-11-19T16:11:25.000Z | 2022-03-31T02:27:52.000Z | leetcode.com/python/979_Distribute_Coins_in_Binary_Tree.py | arunsank/coding-interview-gym | 8131e3a82795707e144fe55d765b6c15bdb97306 | [
"MIT"
] | 7 | 2020-01-16T17:07:18.000Z | 2021-11-15T18:24:39.000Z | leetcode.com/python/979_Distribute_Coins_in_Binary_Tree.py | arunsank/coding-interview-gym | 8131e3a82795707e144fe55d765b6c15bdb97306 | [
"MIT"
] | 393 | 2019-11-18T17:55:45.000Z | 2022-03-28T20:26:32.000Z | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Some notes:
# The reason why it is post-order is,
# you will never know how many coins to move to your parents until you figure out the number of your left & right branches' needed coins.
# # Uses global variable
# class Solution(object):
# def distributeCoins(self, root):
# """
# :type root: TreeNode
# :rtype: int
# """
# self.transactionCount = 0
# self.distributeCoinsHelper(root)
# return self.transactionCount
#
# def distributeCoinsHelper(self, root):
# if not root:
# return 0
# leftTreeCoin = self.distributeCoinsHelper(root.left) # Coin balance from left tree
# rightTreeCoin = self.distributeCoinsHelper(root.right) # Coin balance from right tree
# self.transactionCount += abs(leftTreeCoin) + abs(rightTreeCoin)
# return root.val + leftTreeCoin + rightTreeCoin - 1 # returning own coin balance to it's parent that is being given
# Give the parent node so we can move the coins to the parent directly. But it mutates the input tree, which is not great. But this one is very intuitive
class Solution(object):
def distributeCoins(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.distributeCoinsHelper(root, parentNode=None)
def distributeCoinsHelper(self, root, parentNode):
if not root:
return 0
transactionCount = self.distributeCoinsHelper(root.left, root) + self.distributeCoinsHelper(root.right, root)
if parentNode:
parentNode.val += root.val - 1
return transactionCount + abs(root.val - 1) # returning own coin balance to it's parent that is being given
# From: https://tinyurl.com/s62fws7
class Solution(object):
def distributeCoins(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.distributeCoinsHelper(root)[1]
def distributeCoinsHelper(self, root):
if not root:
return (0, 0)
leftBalance, leftMoveCount = self.distributeCoinsHelper(root.left)
rightBalance, rightMoveCount = self.distributeCoinsHelper(root.right)
nodeBalance = root.val + leftBalance + rightBalance - 1
nodeMoveCountThusFar = leftMoveCount + rightMoveCount + abs(nodeBalance)
return (nodeBalance, nodeMoveCountThusFar)
sol = Solution()
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(0)
root.left.right = TreeNode(3)
output = sol.distributeCoins(root)
print("Res: ", output) | 34.858974 | 154 | 0.658698 |
798951e4f74a0a76c1348883a1df4c0799d1b9ab | 8,819 | py | Python | tools/pykitti_eval/utils/buildtools/command.py | ZhuokunYao/smoke | d524fbe43b1aba6078c25d9aca7924b71a635e1d | [
"MIT"
] | 5 | 2021-01-29T08:35:23.000Z | 2022-03-07T02:05:14.000Z | tools/pykitti_eval/utils/buildtools/command.py | ZhuokunYao/smoke | d524fbe43b1aba6078c25d9aca7924b71a635e1d | [
"MIT"
] | 1 | 2021-12-08T05:55:56.000Z | 2021-12-08T05:55:56.000Z | tools/pykitti_eval/utils/buildtools/command.py | ZhuokunYao/smoke | d524fbe43b1aba6078c25d9aca7924b71a635e1d | [
"MIT"
] | 1 | 2021-08-08T07:08:47.000Z | 2021-08-08T07:08:47.000Z | import multiprocessing
import os
import re
import subprocess
from concurrent.futures import ProcessPoolExecutor
from enum import Enum
from functools import partial
from pathlib import Path
import fire
from tools.pykitti_eval.utils.find import find_cuda, find_cuda_device_arch
class Gpp:
def __init__(self,
sources,
target,
std="c++11",
includes: list = None,
defines: dict = None,
cflags: str = None,
compiler="g++",
link=False,
libraries: dict = None,
lflags: str = None,
extra_cflags: str = None,
extra_lflags: str = None,
build_directory: str = None):
if not isinstance(sources, (list, tuple)):
sources = [sources]
if build_directory is not None:
build_directory = Path(build_directory)
new_sources = []
for p in sources:
if not Path(p).is_absolute():
new_sources.append(str(build_directory / p))
else:
new_sources.append(p)
sources = new_sources
target = Path(target)
if not target.is_absolute():
target = str(build_directory / target)
self.sources = [str(p) for p in sources]
self.target = str(target)
self.std = std
self.includes = includes or []
self.cflags = cflags or '-fPIC -O3'
self.defines = defines or {}
self.compiler = compiler
self.link = link
self.libraries = libraries or {}
self.lflags = lflags or ''
self.extra_cflags = extra_cflags or ''
self.extra_lflags = extra_lflags or ''
def shell(self, target: str = None, compiler: str = None):
defines = [f"-D {n}={v}" for n, v in self.defines.items()]
includes = [f"-I{inc}" for inc in self.includes]
libraries = [
f"-L{n} {' '.join(['-l' + l for l in v])}"
for n, v in self.libraries.items()
]
compiler = compiler or self.compiler
string = f"{compiler} -std={self.std} "
if self.link:
string += " -shared "
else:
string += " -c "
target = target or self.target
string += (f"-o {target} {' '.join(self.sources)} "
f"{' '.join(defines)} "
f"{' '.join(includes)} "
f"{self.cflags} {self.extra_cflags}"
f"{' '.join(libraries)} "
f"{self.lflags} {self.extra_lflags}")
return re.sub(r" +", r" ", string)
class Link:
def __init__(self, outs, target, compiler="ld", build_directory: str = None):
if not isinstance(outs, (list, tuple)):
outs = [outs]
if build_directory is not None:
build_directory = Path(build_directory)
new_outs = []
for p in outs:
if not Path(p).is_absolute():
new_outs.append(str(build_directory / p))
else:
new_outs.append(p)
outs = new_outs
target = Path(target)
if target.is_absolute():
target = str(build_directory / target)
self.outs = [str(p) for p in outs]
self.target = str(target)
self.compiler = compiler
def shell(self, target: str = None):
string = f"{self.compiler} -r "
if target is None:
target = self.target
string += (f"-o {target} {' '.join(self.outs)} ")
return string
class Nvcc(Gpp):
def __init__(self,
sources,
target,
arch=None,
std="c++11",
includes: list = None,
defines: dict = None,
cflags: str = None,
extra_cflags: str = None,
extra_lflags: str = None,
build_directory: str = None):
if arch is None:
arch = find_cuda_device_arch()
if arch is None:
raise ValueError("you must specify arch if use cuda.")
cflags = cflags or f"-x cu -Xcompiler -fPIC -arch={arch} --expt-relaxed-constexpr"
try:
cuda_home = find_cuda()
except:
cuda_home = None
if cuda_home is not None:
cuda_include = Path(cuda_home) / "include"
includes = includes or []
includes += [str(cuda_include)]
super().__init__(
sources,
target,
std,
includes,
defines,
cflags,
compiler="nvcc",
extra_cflags=extra_cflags,
extra_lflags=extra_lflags,
build_directory=build_directory)
class CUDALink(Gpp):
def __init__(self,
sources,
target,
std="c++11",
includes: list = None,
defines: dict = None,
cflags: str = None,
libraries: dict = None,
lflags: str = None,
extra_cflags: str = None,
extra_lflags: str = None,
build_directory: str = None):
includes = includes or []
defines = defines or {}
libraries = libraries or {}
cflags = cflags or "-fPIC -O3"
try:
cuda_home = find_cuda()
except:
cuda_home = None
if cuda_home is not None:
cuda_include = Path(cuda_home) / "include"
includes += [str(cuda_include)]
cuda_lib_path = Path(cuda_home) / "lib64"
cuda_libs = {str(cuda_lib_path): ["cublas", "cudart"]}
libraries = {**libraries, **cuda_libs}
super().__init__(
sources,
target,
std,
includes,
defines,
cflags,
link=True,
libraries=libraries,
lflags=lflags,
extra_cflags=extra_cflags,
extra_lflags=extra_lflags,
build_directory=build_directory)
class NodeState(Enum):
Evaled = "evaled"
Normal = "normal"
Error = "error"
class Node:
def __init__(self, name=None):
self.name = name
self.prev = []
self.next = []
self.state = NodeState.Normal
def __call__(self, *nodes):
for node in nodes:
self.prev.append(node)
node.next.append(self)
return self
def _eval(self, *args, **kw):
return True
def eval(self, *args, **kw):
for p in self.prev:
if not p.eval(*args, **kw):
self.state = NodeState.Error
return False
if self.state == NodeState.Normal:
if self._eval(*args, **kw):
self.state = NodeState.Evaled
else:
self.state = NodeState.Error
return True
return True
def reset(self):
self.state = NodeState.Normal
self.prev = []
self.next = []
for node in self.prev:
node.reset()
class TargetNode(Node):
def __init__(self, srcs, hdrs, deps, copts, name=None):
super().__init__(name)
self.srcs = srcs
self.hdrs = hdrs
self.deps = deps
self.copts = copts
def _eval(self, executor):
pass
def compile_func(cmd, code_folder, compiler):
if not isinstance(cmd, (Link, Nvcc)):
shell = cmd.shell(compiler=compiler)
else:
shell = cmd.shell()
print(shell)
cwd = None
if code_folder is not None:
cwd = str(code_folder)
ret = subprocess.run(shell, shell=True, cwd=cwd)
if ret.returncode != 0:
raise RuntimeError("compile failed with retcode", ret.returncode)
return ret
def compile_libraries(cmds,
code_folder=None,
compiler: str = None,
num_workers=-1):
if num_workers == -1:
num_workers = min(len(cmds), multiprocessing.cpu_count())
# for cmd in cmds:
# print(cmd.shell())
if num_workers == 0:
rets = map(
partial(compile_func, code_folder=code_folder, compiler=compiler),
cmds)
else:
with ProcessPoolExecutor(num_workers) as pool:
func = partial(
compile_func, code_folder=code_folder, compiler=compiler)
rets = pool.map(func, cmds)
if any([r.returncode != 0 for r in rets]):
cmds.clear()
return False
cmds.clear()
return True
def out(path):
return Path(path).parent / (Path(path).stem + ".o")
| 30.835664 | 90 | 0.51321 |
6f59efa0b0ba0dad7ececa99af1b5aeaf91fca58 | 12,624 | py | Python | oidc_example/op2/venvOidc/Lib/site-packages/Cryptodome/Signature/pss.py | State-xyz/pyoidc | cfbe40e43b7acb0004900520d50ede60858208d4 | [
"Apache-2.0"
] | null | null | null | oidc_example/op2/venvOidc/Lib/site-packages/Cryptodome/Signature/pss.py | State-xyz/pyoidc | cfbe40e43b7acb0004900520d50ede60858208d4 | [
"Apache-2.0"
] | null | null | null | oidc_example/op2/venvOidc/Lib/site-packages/Cryptodome/Signature/pss.py | State-xyz/pyoidc | cfbe40e43b7acb0004900520d50ede60858208d4 | [
"Apache-2.0"
] | null | null | null | # ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
from Cryptodome.Util.py3compat import bchr, bord, iter_range
import Cryptodome.Util.number
from Cryptodome.Util.number import (ceil_div,
long_to_bytes,
bytes_to_long
)
from Cryptodome.Util.strxor import strxor
from Cryptodome import Random
class PSS_SigScheme:
"""A signature object for ``RSASSA-PSS``.
Do not instantiate directly.
Use :func:`Cryptodome.Signature.pss.new`.
"""
def __init__(self, key, mgfunc, saltLen, randfunc):
"""Initialize this PKCS#1 PSS signature scheme object.
:Parameters:
key : an RSA key object
If a private half is given, both signature and
verification are possible.
If a public half is given, only verification is possible.
mgfunc : callable
A mask generation function that accepts two parameters:
a string to use as seed, and the lenth of the mask to
generate, in bytes.
saltLen : integer
Length of the salt, in bytes.
randfunc : callable
A function that returns random bytes.
"""
self._key = key
self._saltLen = saltLen
self._mgfunc = mgfunc
self._randfunc = randfunc
def can_sign(self):
"""Return ``True`` if this object can be used to sign messages."""
return self._key.has_private()
def sign(self, msg_hash):
"""Create the PKCS#1 PSS signature of a message.
This function is also called ``RSASSA-PSS-SIGN`` and
it is specified in
`section 8.1.1 of RFC8017 <https://tools.ietf.org/html/rfc8017#section-8.1.1>`_.
:parameter msg_hash:
This is an object from the :mod:`Cryptodome.Hash` package.
It has been used to digest the message to sign.
:type msg_hash: hash object
:return: the signature encoded as a *byte string*.
:raise ValueError: if the RSA key is not long enough for the given hash algorithm.
:raise TypeError: if the RSA key has no private half.
"""
# Set defaults for salt length and mask generation function
if self._saltLen is None:
sLen = msg_hash.digest_size
else:
sLen = self._saltLen
if self._mgfunc is None:
mgf = lambda x, y: MGF1(x, y, msg_hash)
else:
mgf = self._mgfunc
modBits = Cryptodome.Util.number.size(self._key.n)
# See 8.1.1 in RFC3447
k = ceil_div(modBits, 8) # k is length in bytes of the modulus
# Step 1
em = _EMSA_PSS_ENCODE(msg_hash, modBits-1, self._randfunc, mgf, sLen)
# Step 2a (OS2IP)
em_int = bytes_to_long(em)
# Step 2b (RSASP1)
m_int = self._key._decrypt(em_int)
# Step 2c (I2OSP)
signature = long_to_bytes(m_int, k)
return signature
def verify(self, msg_hash, signature):
"""Check if the PKCS#1 PSS signature over a message is valid.
This function is also called ``RSASSA-PSS-VERIFY`` and
it is specified in
`section 8.1.2 of RFC8037 <https://tools.ietf.org/html/rfc8017#section-8.1.2>`_.
:parameter msg_hash:
The hash that was carried out over the message. This is an object
belonging to the :mod:`Cryptodome.Hash` module.
:type parameter: hash object
:parameter signature:
The signature that needs to be validated.
:type signature: bytes
:raise ValueError: if the signature is not valid.
"""
# Set defaults for salt length and mask generation function
if self._saltLen is None:
sLen = msg_hash.digest_size
else:
sLen = self._saltLen
if self._mgfunc:
mgf = self._mgfunc
else:
mgf = lambda x, y: MGF1(x, y, msg_hash)
modBits = Cryptodome.Util.number.size(self._key.n)
# See 8.1.2 in RFC3447
k = ceil_div(modBits, 8) # Convert from bits to bytes
# Step 1
if len(signature) != k:
raise ValueError("Incorrect signature")
# Step 2a (O2SIP)
signature_int = bytes_to_long(signature)
# Step 2b (RSAVP1)
em_int = self._key._encrypt(signature_int)
# Step 2c (I2OSP)
emLen = ceil_div(modBits - 1, 8)
em = long_to_bytes(em_int, emLen)
# Step 3/4
_EMSA_PSS_VERIFY(msg_hash, em, modBits-1, mgf, sLen)
def MGF1(mgfSeed, maskLen, hash_gen):
"""Mask Generation Function, described in `B.2.1 of RFC8017
<https://tools.ietf.org/html/rfc8017>`_.
:param mfgSeed:
seed from which the mask is generated
:type mfgSeed: byte string
:param maskLen:
intended length in bytes of the mask
:type maskLen: integer
:param hash_gen:
A module or a hash object from :mod:`Cryptodome.Hash`
:type hash_object:
:return: the mask, as a *byte string*
"""
T = b""
for counter in iter_range(ceil_div(maskLen, hash_gen.digest_size)):
c = long_to_bytes(counter, 4)
hobj = hash_gen.new()
hobj.update(mgfSeed + c)
T = T + hobj.digest()
assert(len(T) >= maskLen)
return T[:maskLen]
def _EMSA_PSS_ENCODE(mhash, emBits, randFunc, mgf, sLen):
"""
Implement the ``EMSA-PSS-ENCODE`` function, as defined
in PKCS#1 v2.1 (RFC3447, 9.1.1).
The original ``EMSA-PSS-ENCODE`` actually accepts the message ``M``
as input, and hash it internally. Here, we expect that the message
has already been hashed instead.
:Parameters:
mhash : hash object
The hash object that holds the digest of the message being signed.
emBits : int
Maximum length of the final encoding, in bits.
randFunc : callable
An RNG function that accepts as only parameter an int, and returns
a string of random bytes, to be used as salt.
mgf : callable
A mask generation function that accepts two parameters: a string to
use as seed, and the lenth of the mask to generate, in bytes.
sLen : int
Length of the salt, in bytes.
:Return: An ``emLen`` byte long string that encodes the hash
(with ``emLen = \ceil(emBits/8)``).
:Raise ValueError:
When digest or salt length are too big.
"""
emLen = ceil_div(emBits, 8)
# Bitmask of digits that fill up
lmask = 0
for i in iter_range(8*emLen-emBits):
lmask = lmask >> 1 | 0x80
# Step 1 and 2 have been already done
# Step 3
if emLen < mhash.digest_size+sLen+2:
raise ValueError("Digest or salt length are too long"
" for given key size.")
# Step 4
salt = randFunc(sLen)
# Step 5
m_prime = bchr(0)*8 + mhash.digest() + salt
# Step 6
h = mhash.new()
h.update(m_prime)
# Step 7
ps = bchr(0)*(emLen-sLen-mhash.digest_size-2)
# Step 8
db = ps + bchr(1) + salt
# Step 9
dbMask = mgf(h.digest(), emLen-mhash.digest_size-1)
# Step 10
maskedDB = strxor(db, dbMask)
# Step 11
maskedDB = bchr(bord(maskedDB[0]) & ~lmask) + maskedDB[1:]
# Step 12
em = maskedDB + h.digest() + bchr(0xBC)
return em
def _EMSA_PSS_VERIFY(mhash, em, emBits, mgf, sLen):
"""
Implement the ``EMSA-PSS-VERIFY`` function, as defined
in PKCS#1 v2.1 (RFC3447, 9.1.2).
``EMSA-PSS-VERIFY`` actually accepts the message ``M`` as input,
and hash it internally. Here, we expect that the message has already
been hashed instead.
:Parameters:
mhash : hash object
The hash object that holds the digest of the message to be verified.
em : string
The signature to verify, therefore proving that the sender really
signed the message that was received.
emBits : int
Length of the final encoding (em), in bits.
mgf : callable
A mask generation function that accepts two parameters: a string to
use as seed, and the lenth of the mask to generate, in bytes.
sLen : int
Length of the salt, in bytes.
:Raise ValueError:
When the encoding is inconsistent, or the digest or salt lengths
are too big.
"""
emLen = ceil_div(emBits, 8)
# Bitmask of digits that fill up
lmask = 0
for i in iter_range(8*emLen-emBits):
lmask = lmask >> 1 | 0x80
# Step 1 and 2 have been already done
# Step 3
if emLen < mhash.digest_size+sLen+2:
raise ValueError("Incorrect signature")
# Step 4
if ord(em[-1:]) != 0xBC:
raise ValueError("Incorrect signature")
# Step 5
maskedDB = em[:emLen-mhash.digest_size-1]
h = em[emLen-mhash.digest_size-1:-1]
# Step 6
if lmask & bord(em[0]):
raise ValueError("Incorrect signature")
# Step 7
dbMask = mgf(h, emLen-mhash.digest_size-1)
# Step 8
db = strxor(maskedDB, dbMask)
# Step 9
db = bchr(bord(db[0]) & ~lmask) + db[1:]
# Step 10
if not db.startswith(bchr(0)*(emLen-mhash.digest_size-sLen-2) + bchr(1)):
raise ValueError("Incorrect signature")
# Step 11
if sLen > 0:
salt = db[-sLen:]
else:
salt = b""
# Step 12
m_prime = bchr(0)*8 + mhash.digest() + salt
# Step 13
hobj = mhash.new()
hobj.update(m_prime)
hp = hobj.digest()
# Step 14
if h != hp:
raise ValueError("Incorrect signature")
def new(rsa_key, **kwargs):
"""Create an object for making or verifying PKCS#1 PSS signatures.
:parameter rsa_key:
The RSA key to use for signing or verifying the message.
This is a :class:`Cryptodome.PublicKey.RSA` object.
Signing is only possible when ``rsa_key`` is a **private** RSA key.
:type rsa_key: RSA object
:Keyword Arguments:
* *mask_func* (``callable``) --
A mask generation function that accepts two parameters: ``bytes`` to
use as seed, and the amount of ``bytes`` to return (i.e. the mask).
If not specified, the standard :func:`MGF1` function is used,
based on the same hash algorithm applied to the message.
* *salt_bytes* (``integer``) --
Length of the salt, in bytes.
If not specified, it matches the digest of the hash algorithm
applied to the message.
If zero, the signature scheme becomes deterministic.
* *rand_func* (``callable``) --
A function that returns random ``bytes``, of the desired length.
The default is :func:`Cryptodome.Random.get_random_bytes`.
:return: a :class:`PSS_SigScheme` signature object
"""
mask_func = kwargs.pop("mask_func", None)
salt_len = kwargs.pop("salt_bytes", None)
rand_func = kwargs.pop("rand_func", None)
if rand_func is None:
rand_func = Random.get_random_bytes
if kwargs:
raise ValueError("Unknown keywords: " + str(kwargs.keys()))
return PSS_SigScheme(rsa_key, mask_func, salt_len, rand_func)
| 34.39782 | 90 | 0.620802 |
239b367fdecee494ff2496cbe39a4e5e516aa27b | 789 | py | Python | dive_site_site/dive_sites/migrations/0001_initial.py | Scuba-Chris/django_model | 56777506667995c732fd817219f2bce0d238e56b | [
"MIT"
] | null | null | null | dive_site_site/dive_sites/migrations/0001_initial.py | Scuba-Chris/django_model | 56777506667995c732fd817219f2bce0d238e56b | [
"MIT"
] | 5 | 2020-06-05T20:38:30.000Z | 2021-09-22T18:34:51.000Z | dive_site_site/dive_sites/migrations/0001_initial.py | Scuba-Chris/django_model | 56777506667995c732fd817219f2bce0d238e56b | [
"MIT"
] | null | null | null | # Generated by Django 3.0.2 on 2020-01-16 01:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='DiveSite',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('body', models.TextField()),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| 29.222222 | 120 | 0.627376 |
800ca35536e3903dd6a90457b4cdcdd8937f8f05 | 2,443 | py | Python | setup.py | cwza/deep_t2i | 22877fdd28ad407984ddc3bc4d57109c54c22fc0 | [
"Apache-2.0"
] | null | null | null | setup.py | cwza/deep_t2i | 22877fdd28ad407984ddc3bc4d57109c54c22fc0 | [
"Apache-2.0"
] | null | null | null | setup.py | cwza/deep_t2i | 22877fdd28ad407984ddc3bc4d57109c54c22fc0 | [
"Apache-2.0"
] | 1 | 2020-11-30T06:11:02.000Z | 2020-11-30T06:11:02.000Z | from pkg_resources import parse_version
from configparser import ConfigParser
import setuptools
assert parse_version(setuptools.__version__)>=parse_version('36.2')
# note: all settings are in settings.ini; edit there, not here
config = ConfigParser(delimiters=['='])
config.read('settings.ini')
cfg = config['DEFAULT']
cfg_keys = 'version description keywords author author_email'.split()
expected = cfg_keys + "lib_name user branch license status min_python audience language".split()
for o in expected: assert o in cfg, "missing expected setting: {}".format(o)
setup_cfg = {o:cfg[o] for o in cfg_keys}
licenses = {
'apache2': ('Apache Software License 2.0','OSI Approved :: Apache Software License'),
}
statuses = [ '1 - Planning', '2 - Pre-Alpha', '3 - Alpha',
'4 - Beta', '5 - Production/Stable', '6 - Mature', '7 - Inactive' ]
py_versions = '2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 3.0 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8'.split()
# requirements = cfg.get('requirements','').split()
lic = licenses[cfg['license']]
min_python = cfg['min_python']
setuptools.setup(
name = cfg['lib_name'],
license = lic[0],
classifiers = [
'Development Status :: ' + statuses[int(cfg['status'])],
'Intended Audience :: ' + cfg['audience'].title(),
'License :: ' + lic[1],
'Natural Language :: ' + cfg['language'].title(),
] + ['Programming Language :: Python :: '+o for o in py_versions[py_versions.index(min_python):]],
url = cfg['git_url'],
packages = setuptools.find_packages(),
include_package_data = True,
# install_requires = requirements,
dependency_links = cfg.get('dep_links','').split(),
python_requires = '>=' + cfg['min_python'],
long_description = open('README.md').read(),
long_description_content_type = 'text/markdown',
zip_safe = False,
entry_points = { 'console_scripts': cfg.get('console_scripts','').split() },
install_requires = [
'matplotlib==3.2.2', 'pandas==1.0.5', 'pillow==7.0.0',
'kornia==0.3.1', 'transformers==2.9.1', 'scikit-learn==0.22.2',
'fastcore==0.1.17', 'scipy==1.3.1',
],
extras_require={
'dev': [
'gdown==3.6.4', 'twine==3.1.1',
'nbdev==0.2.18',
'torch @ https://download.pytorch.org/whl/cu101/torch-1.5.0%2Bcu101-cp36-cp36m-linux_x86_64.whl',
# 'fastai2 @ git+https://github.com/fastai/fastai2.git',
]
},
**setup_cfg)
| 40.04918 | 109 | 0.63201 |
fd2b70c92de5b297a5e9ce388f635e6da52b67c6 | 1,078 | py | Python | vial/utils.py | martastain/vial | 421373e5821ff45f1e1c7313e2be28641f309955 | [
"MIT"
] | null | null | null | vial/utils.py | martastain/vial | 421373e5821ff45f1e1c7313e2be28641f309955 | [
"MIT"
] | null | null | null | vial/utils.py | martastain/vial | 421373e5821ff45f1e1c7313e2be28641f309955 | [
"MIT"
] | null | null | null | from http import HTTPStatus
def status_phrase(status):
return HTTPStatus(status).phrase
def status_description(status):
return HTTPStatus(status).description
def format_status(status):
return f"{status} {status_phrase(status)}"
class CaseInsensitiveDict(dict):
"""Basic case insensitive dict with strings only keys."""
proxy = {}
def __init__(self, data={}):
self.proxy = dict((k.lower(), k) for k in data)
for k in data:
self[k] = data[k]
def __contains__(self, k):
return k.lower() in self.proxy
def __delitem__(self, k):
key = self.proxy[k.lower()]
super(CaseInsensitiveDict, self).__delitem__(key)
del self.proxy[k.lower()]
def __getitem__(self, k):
key = self.proxy[k.lower()]
return super(CaseInsensitiveDict, self).__getitem__(key)
def get(self, k, default=None):
return self[k] if k in self else default
def __setitem__(self, k, v):
super(CaseInsensitiveDict, self).__setitem__(k, v)
self.proxy[k.lower()] = k
| 23.955556 | 64 | 0.638219 |
44930439d5f772c9610b5283adff95f366529428 | 23,192 | bzl | Python | haskell/repl.bzl | pompon0/rules_haskell | 6bff155511917a8b462132600bb2c0ebfa076a30 | [
"Apache-2.0"
] | null | null | null | haskell/repl.bzl | pompon0/rules_haskell | 6bff155511917a8b462132600bb2c0ebfa076a30 | [
"Apache-2.0"
] | null | null | null | haskell/repl.bzl | pompon0/rules_haskell | 6bff155511917a8b462132600bb2c0ebfa076a30 | [
"Apache-2.0"
] | null | null | null | """Multi target Haskell REPL."""
load("@bazel_skylib//lib:dicts.bzl", "dicts")
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_skylib//lib:shell.bzl", "shell")
load(":cc.bzl", "ghc_cc_program_args")
load(":private/context.bzl", "haskell_context", "render_env")
load(":private/expansions.bzl", "expand_make_variables")
load(
":private/path_utils.bzl",
"ln",
"match_label",
"parse_pattern",
"target_unique_name",
)
load(
":providers.bzl",
"HaskellCcLibrariesInfo",
"HaskellInfo",
"HaskellLibraryInfo",
"HaskellToolchainLibraryInfo",
"all_package_ids",
)
load(
":private/cc_libraries.bzl",
"deps_HaskellCcLibrariesInfo",
"get_cc_libraries",
"get_ghci_library_files",
"get_library_files",
"haskell_cc_libraries_aspect",
"link_libraries",
"merge_HaskellCcLibrariesInfo",
)
load(":private/set.bzl", "set")
HaskellReplLoadInfo = provider(
doc = """Haskell REPL target information.
Information to a Haskell target to load into the REPL as source.
""",
fields = {
"source_files": "Set of files that contain Haskell modules.",
"import_dirs": "Set of Haskell import directories.",
"cc_libraries_info": "HaskellCcLibrariesInfo of transitive C dependencies.",
"cc_info": "CcInfo of transitive C dependencies.",
"compiler_flags": "Flags to pass to the Haskell compiler.",
"repl_ghci_args": "Arbitrary extra arguments to pass to GHCi. This extends `compiler_flags` and `repl_ghci_args` from the toolchain",
"data_runfiles": "Runtime data dependencies of this target, i.e. the files and runfiles of the `data` attribute.",
},
)
HaskellReplDepInfo = provider(
doc = """Haskell REPL dependency information.
Information to a Haskell target to load into the REPL as a built package.
""",
fields = {
"package_ids": "Set of workspace unique package identifiers.",
"package_databases": "Set of package cache files.",
"interface_dirs": "Set of interface dirs for all the dependencies",
"cc_libraries_info": "HaskellCcLibrariesInfo of transitive C dependencies.",
"cc_info": "CcInfo of the package itself (includes its transitive dependencies).",
"runfiles": "Runfiles of this target.",
},
)
HaskellReplCollectInfo = provider(
doc = """Collect Haskell REPL information.
Holds information to generate a REPL that loads some targets as source
and some targets as built packages.
""",
fields = {
"load_infos": "Dictionary from labels to HaskellReplLoadInfo.",
"dep_infos": "Dictionary from labels to HaskellReplDepInfo.",
},
)
HaskellReplInfo = provider(
doc = """Haskell REPL information.
Holds information to generate a REPL that loads a specific set of targets
from source or as built packages.
""",
fields = {
"load_info": "Combined HaskellReplLoadInfo.",
"dep_info": "Combined HaskellReplDepInfo.",
},
)
def _merge_runfiles(runfiles_list):
result = None
for runfiles in runfiles_list:
if result == None:
result = runfiles
elif runfiles != None:
result = result.merge(runfiles)
return result
def _data_runfiles(ctx, rule, attr):
"""Generate runfiles for a data attribute.
Attrs:
ctx: The rule context.
rule: The rule object, `ctx` for a rule, `ctx.rule` for an aspect.
attr: The attribute name of the data attribute.
Returns:
A runfiles object capturing data files and data runfiles.
"""
return _merge_runfiles(
[ctx.runfiles(files = getattr(rule.files, attr, []))] +
[data[DefaultInfo].default_runfiles for data in getattr(rule.attr, attr, [])],
)
def _merge_HaskellReplLoadInfo(load_infos):
source_files = depset()
import_dirs = depset()
cc_libraries_infos = []
cc_infos = []
compiler_flags = []
repl_ghci_args = []
data_runfiles = []
for load_info in load_infos:
source_files = depset(transitive = [source_files, load_info.source_files])
import_dirs = depset(transitive = [import_dirs, load_info.import_dirs])
cc_libraries_infos.append(load_info.cc_libraries_info)
cc_infos.append(load_info.cc_info)
compiler_flags += load_info.compiler_flags
repl_ghci_args += load_info.repl_ghci_args
data_runfiles.append(load_info.data_runfiles)
return HaskellReplLoadInfo(
source_files = source_files,
import_dirs = import_dirs,
cc_libraries_info = merge_HaskellCcLibrariesInfo(infos = cc_libraries_infos),
cc_info = cc_common.merge_cc_infos(cc_infos = cc_infos),
compiler_flags = compiler_flags,
repl_ghci_args = repl_ghci_args,
data_runfiles = _merge_runfiles(data_runfiles),
)
def _merge_HaskellReplDepInfo(dep_infos):
package_ids = []
package_databases = depset()
interface_dirs = depset()
cc_libraries_infos = []
cc_infos = []
runfiles = []
for dep_info in dep_infos:
package_ids += dep_info.package_ids
package_databases = depset(transitive = [package_databases, dep_info.package_databases])
interface_dirs = depset(transitive = [interface_dirs, dep_info.interface_dirs])
cc_libraries_infos.append(dep_info.cc_libraries_info)
cc_infos.append(dep_info.cc_info)
runfiles.append(dep_info.runfiles)
return HaskellReplDepInfo(
package_ids = package_ids,
package_databases = package_databases,
interface_dirs = interface_dirs,
cc_libraries_info = merge_HaskellCcLibrariesInfo(infos = cc_libraries_infos),
cc_info = cc_common.merge_cc_infos(cc_infos = cc_infos),
runfiles = _merge_runfiles(runfiles),
)
def _create_HaskellReplCollectInfo(target, ctx):
load_infos = {}
dep_infos = {}
hs_info = target[HaskellInfo]
if not HaskellToolchainLibraryInfo in target:
load_infos[target.label] = HaskellReplLoadInfo(
source_files = hs_info.source_files,
import_dirs = set.to_depset(hs_info.import_dirs),
cc_libraries_info = deps_HaskellCcLibrariesInfo([
dep
for dep in getattr(ctx.rule.attr, "deps", [])
if CcInfo in dep and not HaskellInfo in dep
]),
cc_info = cc_common.merge_cc_infos(cc_infos = [
# Collect pure C library dependencies, no Haskell dependencies.
dep[CcInfo]
for dep in getattr(ctx.rule.attr, "deps", [])
if CcInfo in dep and not HaskellInfo in dep
]),
compiler_flags = hs_info.user_compile_flags,
repl_ghci_args = hs_info.user_repl_flags,
data_runfiles = _data_runfiles(ctx, ctx.rule, "data"),
)
if HaskellLibraryInfo in target:
lib_info = target[HaskellLibraryInfo]
dep_infos[target.label] = HaskellReplDepInfo(
package_ids = all_package_ids(lib_info),
package_databases = hs_info.package_databases,
interface_dirs = hs_info.interface_dirs,
cc_libraries_info = target[HaskellCcLibrariesInfo],
cc_info = target[CcInfo],
runfiles = target[DefaultInfo].default_runfiles,
)
return HaskellReplCollectInfo(
load_infos = load_infos,
dep_infos = dep_infos,
)
def _merge_HaskellReplCollectInfo(args):
load_infos = {}
dep_infos = {}
for arg in args:
load_infos.update(arg.load_infos)
dep_infos.update(arg.dep_infos)
return HaskellReplCollectInfo(
load_infos = load_infos,
dep_infos = dep_infos,
)
def _load_as_source(from_source, from_binary, lbl):
"""Whether a package should be loaded by source or as binary."""
for pat in from_binary:
if match_label(pat, lbl):
return False
for pat in from_source:
if match_label(pat, lbl):
return True
return False
def _create_HaskellReplInfo(from_source, from_binary, collect_info):
"""Convert a HaskellReplCollectInfo to a HaskellReplInfo.
Args:
from_source: List of patterns for packages to load by source.
from_binary: List of patterns for packages to load as binary packages.
collect_info: HaskellReplCollectInfo provider.
Returns:
HaskellReplInfo provider.
"""
load_infos = collect_info.load_infos
dep_infos = collect_info.dep_infos
# Collect all packages to load by source.
load_info = _merge_HaskellReplLoadInfo([
load_info
for (lbl, load_info) in load_infos.items()
if _load_as_source(from_source, from_binary, lbl)
])
# Collect all packages to load as binary packages.
dep_info = _merge_HaskellReplDepInfo([
dep_info
for (lbl, dep_info) in dep_infos.items()
if not (lbl in load_infos and _load_as_source(from_source, from_binary, lbl))
])
return HaskellReplInfo(
load_info = load_info,
dep_info = dep_info,
)
def _concat(lists):
return [item for l in lists for item in l]
def _compiler_flags_and_inputs(hs, repl_info, static = False, path_prefix = ""):
"""Collect compiler flags and inputs.
Compiler flags:
- Package databases and identifiers.
- Linker flags for C library dependencies.
- Haskell include directory flags.
Inputs:
- Source files.
- Package databases.
- C library dependencies.
- Locale archive if required.
Args:
hs: Haskell context.
repl_info: HaskellReplInfo.
static: bool, Whether we're collecting libraries for static RTS.
Contrary to GHCi, ghcide is built as a static executable using the static RTS.
path_prefix: string, optional, Prefix for package db paths.
Returns:
(args, inputs):
args: list of string, the compiler flags.
inputs: depset of File, inputs required by the compiler.
"""
args = []
# Load built dependencies (-package-id, -package-db)
for package_id in repl_info.dep_info.package_ids:
args.extend(["-package-id", package_id])
for package_cache in repl_info.dep_info.package_databases.to_list():
args.extend(["-package-db", paths.join(path_prefix, package_cache.dirname)])
# Load C library dependencies
cc_libraries_info = merge_HaskellCcLibrariesInfo(infos = [
repl_info.load_info.cc_libraries_info,
repl_info.dep_info.cc_libraries_info,
])
cc_info = cc_common.merge_cc_infos(cc_infos = [
repl_info.load_info.cc_info,
repl_info.dep_info.cc_info,
])
all_libraries = [lib for li in cc_info.linking_context.linker_inputs.to_list() for lib in li.libraries]
cc_libraries = get_cc_libraries(cc_libraries_info, all_libraries)
if static:
cc_library_files = _concat(get_library_files(hs, cc_libraries_info, cc_libraries))
else:
cc_library_files = get_ghci_library_files(hs, cc_libraries_info, cc_libraries)
link_libraries(cc_library_files, args, path_prefix = path_prefix)
if static:
all_library_files = _concat(get_library_files(hs, cc_libraries_info, all_libraries, include_real_paths = True))
else:
all_library_files = get_ghci_library_files(hs, cc_libraries_info, all_libraries, include_real_paths = True)
inputs = depset(transitive = [
repl_info.load_info.source_files,
repl_info.dep_info.package_databases,
depset(all_library_files),
depset([hs.toolchain.locale_archive] if hs.toolchain.locale_archive else []),
repl_info.dep_info.interface_dirs,
])
return (args, inputs)
def _create_repl(hs, posix, ctx, repl_info, output):
"""Build a multi target REPL.
Args:
hs: Haskell context.
ctx: Rule context.
repl_info: HaskellReplInfo provider.
output: The output for the executable REPL script.
Returns:
List of providers:
DefaultInfo provider for the executable REPL script.
"""
# The base and directory packages are necessary for the GHCi script we use
# (loads source files and brings in scope the corresponding modules).
args = ["-hide-all-packages", "-package", "base", "-package", "directory"]
# REPL scripts `cd` into the workspace root. Depending on their provenance,
# some C libraries' files may be in subdirectories which are _only_ relative
# to the execroot. External static C library dependencies are an example of
# this -- unchanged we may end up with paths like
# `external/some_dependency/lib` and/or
# `bazel-out/k8-fastbuild/bin/_solib_k8/...`; the former containing the
# archive (`.a`) file we want, but only being relative to the execroot, and
# the latter being relative to both the workspace root and the execroot but
# only containing dynamic libraries.
#
# We fix this by prefixing paths with the execroot when generating linker
# flags so that all required libraries are visible.
compiler_flags, inputs = _compiler_flags_and_inputs(
hs,
repl_info,
path_prefix = "$RULES_HASKELL_EXEC_ROOT",
)
args.extend(compiler_flags)
args.extend([
'"{}"'.format(arg)
for arg in ghc_cc_program_args(paths.join(
"$RULES_HASKELL_EXEC_ROOT",
hs.toolchain.cc_wrapper.executable.path,
))
])
# Load source files
# Force loading by source with `:add *...`.
# See https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ghci.html#ghci-cmd-:add
add_sources = [
"*" + f.path
for f in repl_info.load_info.source_files.to_list()
]
ghci_repl_script = hs.actions.declare_file(
target_unique_name(hs, "ghci-repl-script"),
)
hs.actions.expand_template(
template = ctx.file._ghci_repl_script,
output = ghci_repl_script,
substitutions = {
"{ADD_SOURCES}": " ".join(add_sources),
"{COMMANDS}": "\n".join(ctx.attr.repl_ghci_commands),
},
)
args += [
"-ghci-script",
paths.join("$RULES_HASKELL_EXEC_ROOT", ghci_repl_script.path),
]
# Extra arguments.
# `compiler flags` is the default set of arguments for the repl,
# augmented by `repl_ghci_args`.
# The ordering is important, first compiler flags (from toolchain
# and local rule), then from `repl_ghci_args`. This way the more
# specific arguments are listed last, and then have more priority in
# GHC.
# Note that most flags for GHCI do have their negative value, so a
# negative flag in `repl_ghci_args` can disable a positive flag set
# in `compiler_flags`, such as `-XNoOverloadedStrings` will disable
# `-XOverloadedStrings`.
repl_ghci_args = expand_make_variables(
"repl_ghci_args",
ctx,
ctx.attr.repl_ghci_args,
[ctx.attr.data],
)
quote_args = (
hs.toolchain.compiler_flags +
repl_info.load_info.compiler_flags +
hs.toolchain.repl_ghci_args +
repl_info.load_info.repl_ghci_args +
repl_ghci_args
)
hs.actions.expand_template(
template = ctx.file._ghci_repl_wrapper,
output = output,
is_executable = True,
substitutions = {
"%{ENV}": render_env(hs.env),
"%{TOOL}": hs.tools.ghci.path,
"%{ARGS}": "(" + " ".join(
args + [
shell.quote(a)
for a in quote_args
],
) + ")",
},
)
runfiles = [
ctx.runfiles(
files = [
hs.tools.ghci,
ghci_repl_script,
],
transitive_files = inputs,
),
hs.toolchain.cc_wrapper.runfiles,
]
if ctx.attr.collect_data:
runfiles.append(repl_info.load_info.data_runfiles)
runfiles.append(repl_info.dep_info.runfiles)
runfiles.append(_data_runfiles(ctx, ctx, "data"))
return [DefaultInfo(
executable = output,
runfiles = _merge_runfiles(runfiles),
)]
def _create_hie_bios(hs, posix, ctx, repl_info):
"""Build a hie-bios argument file.
Args:
hs: Haskell context.
ctx: Rule context.
repl_info: HaskellReplInfo provider.
output: The output for the executable REPL script.
Returns:
List of providers:
OutputGroupInfo provider for the hie-bios argument file.
"""
args, inputs = _compiler_flags_and_inputs(hs, repl_info, static = True)
args.extend(ghc_cc_program_args(hs.toolchain.cc_wrapper.executable.path))
args.extend(hs.toolchain.compiler_flags)
args.extend(repl_info.load_info.compiler_flags)
# Add import directories.
# Note, src_strip_prefix is deprecated. However, for now ghcide depends on
# `-i` flags to find source files to modules.
for import_dir in repl_info.load_info.import_dirs.to_list():
args.append("-i" + (import_dir if import_dir else "."))
# List modules (Targets) covered by this cradle.
args.extend([f.path for f in repl_info.load_info.source_files.to_list()])
args_file = ctx.actions.declare_file(".%s.hie-bios" % ctx.label.name)
args_link = ctx.actions.declare_file("%s@hie-bios" % ctx.label.name)
ctx.actions.write(args_file, "\n".join(args))
ln(hs, posix, args_file, args_link, extra_inputs = inputs)
return [OutputGroupInfo(hie_bios = [args_link])]
def _haskell_repl_aspect_impl(target, ctx):
if HaskellInfo not in target:
return []
target_info = _create_HaskellReplCollectInfo(target, ctx)
if hasattr(ctx.rule.attr, "deps"):
deps_infos = [
dep[HaskellReplCollectInfo]
for dep in ctx.rule.attr.deps
if HaskellReplCollectInfo in dep
]
else:
deps_infos = []
collect_info = _merge_HaskellReplCollectInfo([target_info] + deps_infos)
# This aspect currently does not generate an executable REPL script by
# itself. This could be extended in future. Note, to that end it's
# necessary to construct a Haskell context without `ctx.attr.name`.
return [collect_info]
haskell_repl_aspect = aspect(
implementation = _haskell_repl_aspect_impl,
attr_aspects = ["deps"],
required_aspect_providers = [HaskellCcLibrariesInfo],
doc = """\
Haskell REPL aspect.
Used to implement the haskell_repl rule. Does not generate an executable REPL
by itself.
""",
)
def _haskell_repl_impl(ctx):
collect_info = _merge_HaskellReplCollectInfo([
dep[HaskellReplCollectInfo]
for dep in ctx.attr.deps
if HaskellReplCollectInfo in dep
])
from_source = [parse_pattern(ctx, pat) for pat in ctx.attr.experimental_from_source]
from_binary = [parse_pattern(ctx, pat) for pat in ctx.attr.experimental_from_binary]
repl_info = _create_HaskellReplInfo(from_source, from_binary, collect_info)
hs = haskell_context(ctx)
posix = ctx.toolchains["@rules_sh//sh/posix:toolchain_type"]
return _create_repl(hs, posix, ctx, repl_info, ctx.outputs.repl) + \
_create_hie_bios(hs, posix, ctx, repl_info)
haskell_repl = rule(
implementation = _haskell_repl_impl,
attrs = {
"_ghci_repl_script": attr.label(
allow_single_file = True,
default = Label("@rules_haskell//haskell:assets/ghci_script"),
),
"_ghci_repl_wrapper": attr.label(
allow_single_file = True,
default = Label("@rules_haskell//haskell:private/ghci_repl_wrapper.sh"),
),
"deps": attr.label_list(
aspects = [
haskell_cc_libraries_aspect,
haskell_repl_aspect,
],
doc = "List of Haskell targets to load into the REPL",
),
"data": attr.label_list(
allow_files = True,
doc = "See [Bazel documentation](https://docs.bazel.build/versions/master/be/common-definitions.html#common.data). Only available when `collect_data = True`.",
),
"experimental_from_source": attr.string_list(
doc = """White-list of targets to load by source.
Wild-card targets such as //... or //:all are allowed.
The black-list takes precedence over the white-list.
Note, this attribute will change depending on the outcome of
https://github.com/bazelbuild/bazel/issues/7763.
""",
default = ["//..."],
),
"experimental_from_binary": attr.string_list(
doc = """Black-list of targets to not load by source but as packages.
Wild-card targets such as //... or //:all are allowed.
The black-list takes precedence over the white-list.
Note, this attribute will change depending on the outcome of
https://github.com/bazelbuild/bazel/issues/7763.
""",
default = [],
),
"repl_ghci_args": attr.string_list(
doc = "Arbitrary extra arguments to pass to GHCi. This extends `compiler_flags` and `repl_ghci_args` from the toolchain. Subject to Make variable substitution.",
default = [],
),
"repl_ghci_commands": attr.string_list(
doc = "Arbitrary extra commands to execute in GHCi.",
default = [],
),
"collect_data": attr.bool(
doc = "Whether to collect the data runfiles from the dependencies in srcs, data and deps attributes.",
default = True,
),
},
executable = True,
outputs = {
"repl": "%{name}@repl",
},
toolchains = [
"@rules_haskell//haskell:toolchain",
"@rules_sh//sh/posix:toolchain_type",
],
doc = """\
Build a REPL for multiple targets.
### Examples
```bzl
haskell_repl(
name = "repl",
deps = [
"//lib:some_lib",
"//exe:some_exe",
],
experimental_from_source = [
"//lib/...",
"//exe/...",
"//common/...",
],
experimental_from_binary = [
"//lib/vendored/...",
],
)
```
Collects all transitive Haskell dependencies from `deps`. Those that match
`experimental_from_binary` or are defined in an external workspace will be
loaded as binary packages. Those that match `experimental_from_source` and
are defined in the local workspace will be loaded by source.
You can call the REPL like this:
```
$ bazel run //:repl
```
### IDE Support (Experimental)
`haskell_repl` targets provide the `hie_bios` output group to optionally
generate GHCi flags for [hie-bios](https://github.com/mpickering/hie-bios)'s
`bios` cradle. You can use this for IDE support with
[ghcide](https://github.com/digital-asset/ghcide).
Given a `haskell_repl` target `//:repl` an example `.hie-bios` script could
look as follows. Please refer to the `hie-bios` documentation for further
information.
```shell
#!/usr/bin/env bash
set -euo pipefail
bazel build //:repl --output_groups=hie_bios
cat bazel-bin/repl@hie-bios >"$HIE_BIOS_OUTPUT"
```
""",
)
| 34.770615 | 173 | 0.656994 |
154ecd853fcf2f963df27d5be49b2ed224682f9f | 4,903 | py | Python | hnn/hnn.py | StuartSul/Homemade_Neural_Network | a52bf863275799f455cceed6920ce95aab7fa500 | [
"MIT"
] | null | null | null | hnn/hnn.py | StuartSul/Homemade_Neural_Network | a52bf863275799f455cceed6920ce95aab7fa500 | [
"MIT"
] | null | null | null | hnn/hnn.py | StuartSul/Homemade_Neural_Network | a52bf863275799f455cceed6920ce95aab7fa500 | [
"MIT"
] | null | null | null | from hnn.network import Network
from hnn.trainer import Trainer
from hnn.loader import *
class hnn:
def __init__(self, network_id, input_count, output_count, structure, activation,
features, labels, train_ratio, loss_function, regularization=None):
self.network = None
self.trainer = None
self.init_network(network_id, input_count, output_count, structure, activation)
self.init_trainer(features, labels, train_ratio, loss_function, regularization)
def init_network(self, network_id, input_count, output_count, structure, activation):
if type(network_id) is not str:
print('ERROR: must provide string value for network_id')
return
if type(input_count) is not int or input_count < 1:
print('ERROR: input_count must be an integer value greater than or equal to 1')
return
elif type(output_count) is not int or output_count < 1:
print('ERROR: output_count must be an integer value greater than or equal to 1')
return
elif type(structure) is not list or type(structure[0]) is not int:
print('ERROR: structure must be a list of integers')
return
self.network = Network(network_id, input_count, output_count, structure, activation)
def init_trainer(self, features, labels, train_ratio, loss_function, regularization):
if self.network == None:
print('ERROR: must initialize network first')
return
elif type(train_ratio) is not float or train_ratio >= 1 or train_ratio <= 0:
print('ERROR: train_ratio must be a float value at the range of (0, 1)')
return
elif type(features) is not list:
print('ERROR: must provide an instance of list for features')
return
elif type(labels) is not list:
print('ERROR: must provide an instance of list for labels')
return
elif len(features) == 0 or len(labels) == 0 or len(features) != len(labels):
print('ERROR: features and labels must have same length')
return
elif len(features[0]) != self.network.input_count:
print('ERROR: input_width and the length of each feature must be equal')
return
elif type(labels[0]) is not int and type(labels[0]) is not float:
print('ERROR: each label must consist of a single numeric value')
return
self.trainer = Trainer(self.network, features, labels, train_ratio, loss_function)
def train(self, batch_size, learning_rate, total_epochs, periods):
if self.network == None:
print('ERROR: must initialize network first')
return
elif self.trainer == None:
print('ERROR: must initialize trainer first')
return
if type(batch_size) is not int or batch_size < 1 or batch_size > len(self.trainer.features):
print('ERROR: batch_size must be an integer value at the range of [1, NUM_FEATURES]')
return
elif type(learning_rate) is not float or learning_rate <= 0:
print('ERROR: learning_rate must be a float value greater than 0')
return
elif type(total_epochs) is not int or total_epochs < 1:
print('ERROR: total_epochs must be an integer value greater than 0')
return
elif type(periods) is not int or periods < 1 or periods > total_epochs:
print('ERROR: periods must be an integer value at the range of [1, total_epochs]')
return
epochs_per_period = total_epochs // periods
print('\nInitiating training on network ' + self.network.id + "...\n")
for i in range(periods):
print('Period ' + str(i+1) + ' out of ' + str(periods))
train_loss, test_loss = self.trainer.train(batch_size, learning_rate, epochs_per_period)
print(' Training loss: ' + str(train_loss))
print(' Testing loss: ' + str(test_loss))
print('\nTraining complete\n')
def predict(self, feature):
if self.network == None:
print('ERROR: Must initialize network first')
return self.network.execute(feature)[0]
def save(self, filename):
if self.network == None:
print('ERROR: There does not exist a network to save')
save_network(self.network, filename)
print('Successfully saved network ' + self.network.id)
@classmethod
def load(cls, filename):
network = load_network(filename)
new_hnn = cls('', 1, 1, [1], None, [[1]], [1], .1, None)
new_hnn.network = network
new_hnn.trainer = None
print('Successfully loaded network ' + network.id)
return new_hnn
def reset(self):
self.network = None
self.trainer = None | 46.695238 | 100 | 0.627371 |
71e4ae033272689a0c5d014356404a8a5ae503e7 | 3,391 | py | Python | droidlet/interpreter/craftassist/interpret_facing.py | ali-senguel/fairo | 1ec5d8ecbdfc782de63a92aad9bf8534110ce762 | [
"MIT"
] | 669 | 2020-11-21T01:20:20.000Z | 2021-09-13T13:25:16.000Z | droidlet/interpreter/craftassist/interpret_facing.py | ali-senguel/fairo | 1ec5d8ecbdfc782de63a92aad9bf8534110ce762 | [
"MIT"
] | 324 | 2020-12-07T18:20:34.000Z | 2021-09-14T17:17:18.000Z | droidlet/interpreter/craftassist/interpret_facing.py | ali-senguel/fairo | 1ec5d8ecbdfc782de63a92aad9bf8534110ce762 | [
"MIT"
] | 56 | 2021-01-04T19:57:40.000Z | 2021-09-13T21:20:08.000Z | """
Copyright (c) Facebook, Inc. and its affiliates.
"""
from droidlet.shared_data_structs import ErrorWithResponse
from droidlet.interpreter import interpret_relative_direction
from word2number.w2n import word_to_num
def number_from_span(span):
# this will fail in many cases....
words = span.split()
degrees = None
for w in words:
try:
degrees = int(w)
except:
pass
if not degrees:
try:
degrees = word_to_num(span)
except:
pass
return degrees
class FacingInterpreter:
def __call__(self, interpreter, speaker, d):
self_mem = interpreter.memory.get_mem_by_id(interpreter.memory.self_memid)
current_yaw, current_pitch = self_mem.get_yaw_pitch()
if d.get("yaw_pitch"):
span = d["yaw_pitch"]
# for now assumed in (yaw, pitch) or yaw, pitch or yaw pitch formats
yp = span.replace("(", "").replace(")", "").split()
return {"head_yaw_pitch": (int(yp[0]), int(yp[1]))}
elif d.get("yaw"):
# for now assumed span is yaw as word or number
w = d["yaw"].strip(" degrees").strip(" degree")
return {"head_yaw_pitch": (word_to_num(w), current_pitch)}
elif d.get("pitch"):
# for now assumed span is pitch as word or number
w = d["pitch"].strip(" degrees").strip(" degree")
return {"head_yaw_pitch": (current_yaw, word_to_num(w))}
elif d.get("relative_yaw"):
# TODO in the task use turn angle
if "left" in d["relative_yaw"] or "right" in d["relative_yaw"]:
left = "left" in d["relative_yaw"] or "leave" in d["relative_yaw"] # lemmatizer :)
degrees = number_from_span(d["relative_yaw"]) or 90
if degrees > 0 and left:
return {"relative_yaw": -degrees}
else:
return {"relative_yaw": degrees}
else:
try:
degrees = int(number_from_span(d["relative_yaw"]))
return {"relative_yaw": degrees}
except:
pass
elif d.get("relative_pitch"):
if "down" in d["relative_pitch"] or "up" in d["relative_pitch"]:
down = "down" in d["relative_pitch"]
degrees = number_from_span(d["relative_pitch"]) or 90
if degrees > 0 and down:
return {"relative_pitch": -degrees}
else:
return {"relative_pitch": degrees}
else:
# TODO in the task make this relative!
try:
deg = int(number_from_span(d["relative_pitch"]))
return {"relative_pitch": deg}
except:
pass
elif d.get("location"):
mems = interpreter.subinterpret["reference_locations"](
interpreter, speaker, d["location"]
)
steps, reldir = interpret_relative_direction(interpreter, d["location"])
loc, _ = interpreter.subinterpret["specify_locations"](
interpreter, speaker, mems, steps, reldir
)
return {"head_xyz": loc}
else:
raise ErrorWithResponse("I am not sure where you want me to turn")
| 39.894118 | 99 | 0.543203 |
f13b02e9c4e1de35efe340e6b41d28db0b676453 | 5,254 | py | Python | venv/Lib/site-packages/pandas/tests/base/test_constructors.py | arnoyu-hub/COMP0016miemie | 59af664dcf190eab4f93cefb8471908717415fea | [
"MIT"
] | null | null | null | venv/Lib/site-packages/pandas/tests/base/test_constructors.py | arnoyu-hub/COMP0016miemie | 59af664dcf190eab4f93cefb8471908717415fea | [
"MIT"
] | null | null | null | venv/Lib/site-packages/pandas/tests/base/test_constructors.py | arnoyu-hub/COMP0016miemie | 59af664dcf190eab4f93cefb8471908717415fea | [
"MIT"
] | null | null | null | from datetime import datetime
import sys
import numpy as np
import pytest
from pandas.compat import PYPY
import pandas as pd
from pandas import (
DataFrame,
Index,
Series,
)
import pandas._testing as tm
from pandas.core.accessor import PandasDelegate
from pandas.core.base import (
NoNewAttributesMixin,
PandasObject,
)
@pytest.fixture(
params=[
Series,
lambda x, **kwargs: DataFrame({"a": x}, **kwargs)["a"],
lambda x, **kwargs: DataFrame(x, **kwargs)[0],
Index,
],
ids=["Series", "DataFrame-dict", "DataFrame-array", "Index"],
)
def constructor(request):
return request.param
class TestPandasDelegate:
class Delegator:
_properties = ["foo"]
_methods = ["bar"]
def _set_foo(self, value):
self.foo = value
def _get_foo(self):
return self.foo
foo = property(_get_foo, _set_foo, doc="foo property")
def bar(self, *args, **kwargs):
"""a test bar method"""
pass
class Delegate(PandasDelegate, PandasObject):
def __init__(self, obj):
self.obj = obj
def setup_method(self, method):
pass
def test_invalid_delegation(self):
# these show that in order for the delegation to work
# the _delegate_* methods need to be overridden to not raise
# a TypeError
self.Delegate._add_delegate_accessors(
delegate=self.Delegator,
accessors=self.Delegator._properties,
typ="property",
)
self.Delegate._add_delegate_accessors(
delegate=self.Delegator, accessors=self.Delegator._methods, typ="method"
)
delegate = self.Delegate(self.Delegator())
msg = "You cannot access the property foo"
with pytest.raises(TypeError, match=msg):
delegate.foo
msg = "The property foo cannot be set"
with pytest.raises(TypeError, match=msg):
delegate.foo = 5
msg = "You cannot access the property foo"
with pytest.raises(TypeError, match=msg):
delegate.foo()
@pytest.mark.skipif(PYPY, reason="not relevant for PyPy")
def test_memory_usage(self):
# Delegate does not implement memory_usage.
# Check that we fall back to in-built `__sizeof__`
# GH 12924
delegate = self.Delegate(self.Delegator())
sys.getsizeof(delegate)
class TestNoNewAttributesMixin:
def test_mixin(self):
class T(NoNewAttributesMixin):
pass
t = T()
assert not hasattr(t, "__frozen")
t.a = "test"
assert t.a == "test"
t._freeze()
assert "__frozen" in dir(t)
assert getattr(t, "__frozen")
msg = "You cannot add any new attribute"
with pytest.raises(AttributeError, match=msg):
t.b = "test"
assert not hasattr(t, "b")
class TestConstruction:
# test certain constructor behaviours on dtype inference across Series,
# Index and DataFrame
@pytest.mark.parametrize(
"klass",
[
Series,
lambda x, **kwargs: DataFrame({"a": x}, **kwargs)["a"],
lambda x, **kwargs: DataFrame(x, **kwargs)[0],
Index,
],
)
@pytest.mark.parametrize(
"a",
[
np.array(["2263-01-01"], dtype="datetime64[D]"),
np.array([datetime(2263, 1, 1)], dtype=object),
np.array([np.datetime64("2263-01-01", "D")], dtype=object),
np.array(["2263-01-01"], dtype=object),
],
ids=[
"datetime64[D]",
"object-datetime.datetime",
"object-numpy-scalar",
"object-string",
],
)
def test_constructor_datetime_outofbound(self, a, klass):
# GH-26853 (+ bug GH-26206 out of bound non-ns unit)
# No dtype specified (dtype inference)
# datetime64[non-ns] raise error, other cases result in object dtype
# and preserve original data
if a.dtype.kind == "M":
msg = "Out of bounds"
with pytest.raises(pd.errors.OutOfBoundsDatetime, match=msg):
klass(a)
else:
result = klass(a)
assert result.dtype == "object"
tm.assert_numpy_array_equal(result.to_numpy(), a)
# Explicit dtype specified
# Forced conversion fails for all -> all cases raise error
msg = "Out of bounds"
with pytest.raises(pd.errors.OutOfBoundsDatetime, match=msg):
klass(a, dtype="datetime64[ns]")
def test_constructor_datetime_nonns(self, constructor):
arr = np.array(["2020-01-01T00:00:00.000000"], dtype="datetime64[us]")
expected = constructor(pd.to_datetime(["2020-01-01"]))
result = constructor(arr)
tm.assert_equal(result, expected)
# https://github.com/pandas-dev/pandas/issues/34843
arr.flags.writeable = False
result = constructor(arr)
tm.assert_equal(result, expected)
| 29.683616 | 85 | 0.570042 |
21263968fe409408a234582a337b0d9c77778523 | 86 | py | Python | models/counters/__init__.py | sailyung/crowd_counting | a19c4edab06a841bfe3b8eacdc12104dbddf4d7d | [
"MIT"
] | 1 | 2021-02-10T16:43:34.000Z | 2021-02-10T16:43:34.000Z | models/counters/__init__.py | sailyung/crowd_counting | a19c4edab06a841bfe3b8eacdc12104dbddf4d7d | [
"MIT"
] | null | null | null | models/counters/__init__.py | sailyung/crowd_counting | a19c4edab06a841bfe3b8eacdc12104dbddf4d7d | [
"MIT"
] | null | null | null | # from . import CSRNet
from . import Res101_SFCN
from . import LCN
from . import MCNN
| 17.2 | 25 | 0.744186 |
3f8b6ad18e9698f185fb1857e9930f2f4d5ffe37 | 2,981 | py | Python | application/flicket_admin/models/flicket_config.py | quanpower/flicket | a5019e32c5534932b7546c18c00d6327751b7192 | [
"MIT"
] | 1 | 2018-11-07T02:00:27.000Z | 2018-11-07T02:00:27.000Z | application/flicket_admin/models/flicket_config.py | quanpower/flicket | a5019e32c5534932b7546c18c00d6327751b7192 | [
"MIT"
] | null | null | null | application/flicket_admin/models/flicket_config.py | quanpower/flicket | a5019e32c5534932b7546c18c00d6327751b7192 | [
"MIT"
] | null | null | null | #! usr/bin/python3
# -*- coding: utf8 -*-
#
# Flicket - copyright Paul Bourne: evereux@gmail.com
from application import db
from application.flicket.models import Base
class FlicketConfig(Base):
"""
Server configuration settings editable by administrators only via the adminstration page `/flicket_admin/config/`.
For email configuration settings see https://flask-mail.readthedocs.io/en/latest/ for more information.
:param str mail_server: example: `smtp.yourcompany.com`.
:param int mail_port: example: `567`
:param bool mail_use_tls: example: `true`
:param bool mail_use_ssl: example: `false`
:param bool mail_debug: example: `false`
:param str mail_username: example: `flicket.admin`
:param str mail_password:
:param str mail_default_sender: example: `flicket.admin@yourcompany.com`
:param int mail_max_emails:
:param bool mail_suppress_send:
:param bool mail_ascii_attachments:
:param str application_title: Changes the default banner text from `Flicket`. Can typically be your company name.
:param str posts_per_page: Maximum number of posts / topics displayed per page.
:param str allowed_extensions: A comma delimited list of file extensions users are allowed to upload. DO NOT include
the . before the extension letter.
:param str ticket_upload_folder: The folder used for file uploads.
:param str base_url: The sites base url. This is used to resolve urls for emails and links. Broken links are
probably a result of not setting this value.
:param str csv_dump_limit: The maximum number of rows exported to csv.
"""
__tablename__ = 'flicket_config'
def __init__(self, **kwargs):
"""
Initialisation used for initial setup.py file.
:param kwargs:
"""
for key, value in kwargs.items():
setattr(self, key, value)
id = db.Column(db.Integer, primary_key=True)
# mail settings for Flask-Mail
mail_server = db.Column(db.String(128))
mail_port = db.Column(db.Integer)
mail_use_tls = db.Column(db.BOOLEAN)
mail_use_ssl = db.Column(db.BOOLEAN)
mail_debug = db.Column(db.BOOLEAN)
mail_username = db.Column(db.String(128))
mail_password = db.Column(db.String(256))
mail_default_sender = db.Column(db.String(128))
mail_max_emails = db.Column(db.Integer)
mail_suppress_send = db.Column(db.BOOLEAN)
mail_ascii_attachments = db.Column(db.BOOLEAN)
posts_per_page = db.Column(db.Integer)
allowed_extensions = db.Column(db.String(256))
ticket_upload_folder = db.Column(db.String(256))
avatar_upload_folder = db.Column(db.String(256))
application_title = db.Column(db.String(32))
base_url = db.Column(db.String(128))
auth_domain = db.Column(db.String(64))
use_auth_domain = db.Column(db.BOOLEAN, default=False)
csv_dump_limit = db.Column(db.Integer, default=1000)
def __repr__(self):
return "<FlicketConfig model class>"
| 38.217949 | 120 | 0.712848 |
cbdc20894eb541af242719db73af364ed38396f7 | 923 | py | Python | AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/demo.py | CEOALT1/RefindPlusUDK | 116b957ad735f96fbb6d80a0ba582046960ba164 | [
"BSD-2-Clause"
] | 2,757 | 2018-04-28T21:41:36.000Z | 2022-03-29T06:33:36.000Z | AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/demo.py | CEOALT1/RefindPlusUDK | 116b957ad735f96fbb6d80a0ba582046960ba164 | [
"BSD-2-Clause"
] | 20 | 2019-07-23T15:29:32.000Z | 2022-01-21T12:53:04.000Z | AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/demo.py | CEOALT1/RefindPlusUDK | 116b957ad735f96fbb6d80a0ba582046960ba164 | [
"BSD-2-Clause"
] | 449 | 2018-05-09T05:54:05.000Z | 2022-03-30T14:54:18.000Z | #! /usr/bin/env python
"""Print names of all methods defined in module
This script demonstrates use of the visitor interface of the compiler
package.
"""
import compiler
class MethodFinder:
"""Print the names of all the methods
Each visit method takes two arguments, the node and its current
scope. The scope is the name of the current class or None.
"""
def visitClass(self, node, scope=None):
self.visit(node.code, node.name)
def visitFunction(self, node, scope=None):
if scope is not None:
print "%s.%s" % (scope, node.name)
self.visit(node.code, None)
def main(files):
mf = MethodFinder()
for file in files:
f = open(file)
buf = f.read()
f.close()
ast = compiler.parse(buf)
compiler.walk(ast, mf)
if __name__ == "__main__":
import sys
main(sys.argv[1:])
| 23.666667 | 70 | 0.603467 |
50e21e88bf3bd1adbf7f648f37e1627493e4e47d | 183 | py | Python | regtests/list/concatenate.py | bpmbank/PythonJS | 591a80afd8233fb715493591db2b68f1748558d9 | [
"BSD-3-Clause"
] | 319 | 2015-01-02T11:34:16.000Z | 2022-03-25T00:43:33.000Z | regtests/list/concatenate.py | idobatter/PythonJS | 0161dd5aba6caeaf5b06e74cc8524efd04a36143 | [
"BSD-3-Clause"
] | 10 | 2015-02-03T02:33:09.000Z | 2021-11-09T21:41:00.000Z | regtests/list/concatenate.py | idobatter/PythonJS | 0161dd5aba6caeaf5b06e74cc8524efd04a36143 | [
"BSD-3-Clause"
] | 61 | 2015-01-02T12:01:56.000Z | 2021-12-08T07:16:16.000Z | """concatenate lists"""
def main():
a = [1,2]
b = [3,4]
c = a + b
TestError( len(c)==4 )
TestError( c[0]==1 )
TestError( c[1]==2 )
TestError( c[2]==3 )
TestError( c[3]==4 )
| 14.076923 | 23 | 0.513661 |
41de5030d0dce60790676f17ef4f4dc5b959b0ea | 535 | py | Python | stubs/micropython-v1_14-esp8266/uasyncio/funcs.py | mattytrentini/micropython-stubs | 4d596273823b69e9e5bcf5fa67f249c374ee0bbc | [
"MIT"
] | null | null | null | stubs/micropython-v1_14-esp8266/uasyncio/funcs.py | mattytrentini/micropython-stubs | 4d596273823b69e9e5bcf5fa67f249c374ee0bbc | [
"MIT"
] | null | null | null | stubs/micropython-v1_14-esp8266/uasyncio/funcs.py | mattytrentini/micropython-stubs | 4d596273823b69e9e5bcf5fa67f249c374ee0bbc | [
"MIT"
] | null | null | null | """
Module: 'uasyncio.funcs' on micropython-v1.14-esp8266
"""
# MCU: {'ver': 'v1.14', 'port': 'esp8266', 'arch': 'xtensa', 'sysname': 'esp8266', 'release': '1.14', 'name': 'micropython', 'mpy': 9733, 'version': '1.14', 'machine': 'ESP module with ESP8266', 'build': '', 'nodename': 'esp8266', 'platform': 'esp8266', 'family': 'micropython'}
# Stubber: 1.5.4
from typing import Any
wait_for: Any ## <class 'generator'> = <generator>
gather: Any ## <class 'generator'> = <generator>
def wait_for_ms(*args, **kwargs) -> Any:
...
| 38.214286 | 278 | 0.618692 |
3ede11933adde13fbc0c50a2051527d3e317b461 | 3,077 | py | Python | api/app/cached_routes.py | lightning-dabbler/github_api_client | e3822c743c581c9e24e9ae83da6f199642ef3db9 | [
"MIT"
] | 1 | 2020-06-17T12:03:55.000Z | 2020-06-17T12:03:55.000Z | api/app/cached_routes.py | lightning-dabbler/github_api_client | e3822c743c581c9e24e9ae83da6f199642ef3db9 | [
"MIT"
] | 5 | 2020-07-31T19:42:18.000Z | 2021-03-18T02:21:19.000Z | api/app/cached_routes.py | lightning-dabbler/github-api-client | e3822c743c581c9e24e9ae83da6f199642ef3db9 | [
"MIT"
] | null | null | null | import json
import logging
import os
from flask import Blueprint, jsonify, request
from rediscluster import RedisCluster
import redis
from . import helpers
logger = logging.getLogger(__name__)
APP_ENV = os.environ.get("APP_ENV", "development")
if APP_ENV == "production":
logger.info("Redis Production Cluster Subnet: 10.0.0.0/16 Ports: 6380-6385")
startup_nodes = [
{"host": "10.0.0.11", "port": 6380},
{"host": "10.0.0.12", "port": 6381},
{"host": "10.0.0.13", "port": 6382},
{"host": "10.0.0.14", "port": 6383},
{"host": "10.0.0.15", "port": 6384},
{"host": "10.0.0.16", "port": 6385},
]
r = RedisCluster(startup_nodes=startup_nodes, decode_responses=True)
else:
REDIS_URL_NET = os.environ.get("REDIS_URL_NET")
logger.info(f"Redis Development node {REDIS_URL_NET}")
r = redis.from_url(REDIS_URL_NET)
cache_bp = Blueprint("cache_bp", __name__)
@cache_bp.route("/cached/trending", methods=["GET"])
def cached_trending():
logger.info(f"Route = {request.url}")
developers = request.args.get("developers", False)
developers = (
True if helpers.str_lower_rem_l_t_whitespace(developers) == "true" else False
)
since = request.args.get("since", "")
since = helpers.str_lower_rem_l_t_whitespace(since)
refresh = request.args.get("refresh", False)
refresh = True if helpers.str_lower_rem_l_t_whitespace(refresh) == "true" else False
ttl = 60 * 60 * 5
freqs = ["daily", "weekly", "monthly"]
if since not in freqs:
since = "daily"
if developers:
key_construct = "trending_dev"
else:
key_construct = "trending_repo"
params = {
"key": f"{key_construct}_{since}",
"developers": developers,
"since": since,
"ttl": ttl,
"r": r,
}
if refresh:
logger.info(
f"Issuing a Refresh for cached Trending; developers = {developers} !"
)
for freq in freqs:
results = helpers.h_trending(developers=developers, since=freq)
r.set(f"{key_construct}_{freq}", json.dumps(results), ex=ttl)
logger.debug(f"Value set @ key {key_construct}_{freq} TTL = {ttl} !")
results = helpers.cached_trending_util(**params)
return jsonify(results)
@cache_bp.route("/cached/emojis/<path:emoji>", methods=["GET"])
def cached_emojis(emoji):
logger.info(f"Route = {request.url}")
emoji = emoji.strip().lower()
results = r.get(emoji)
ttl = 60 * 60 * 20
if results == None:
logger.info(f"No Cached Data @ key {emoji} !")
results = helpers.h_emojis(emoji)
if emoji in results:
results = {"name": emoji, "exists": True, "img": results[emoji]}
else:
results = {"name": emoji, "exists": False}
r.set(emoji, json.dumps(results), ex=ttl)
logger.debug(f"Value set @ key {emoji} TTL = {ttl} !")
else:
logger.info(f"Cached Data @ key {emoji} Retrieved !")
results = json.loads(results)
return jsonify(results)
| 30.166667 | 88 | 0.61456 |
fd86b9735af71dd8f27e1797444d25ecd7d9242e | 1,053 | py | Python | tests/ex04_contact/models.py | RodrigoDeRosa/related | 3799cde862b8c9500931706f5f1ce5576028f642 | [
"MIT"
] | 190 | 2017-05-25T11:57:15.000Z | 2022-03-17T01:44:53.000Z | tests/ex04_contact/models.py | RodrigoDeRosa/related | 3799cde862b8c9500931706f5f1ce5576028f642 | [
"MIT"
] | 42 | 2017-06-11T14:05:11.000Z | 2021-12-14T21:12:07.000Z | tests/ex04_contact/models.py | RodrigoDeRosa/related | 3799cde862b8c9500931706f5f1ce5576028f642 | [
"MIT"
] | 18 | 2018-01-05T08:47:30.000Z | 2022-01-28T06:24:05.000Z | from enum import Enum, unique
import related
@unique
class Degree(Enum):
HIGH_SCHOOL = "High School"
ASSOCIATES = "Associate's"
BACHELORS = "Bachelor's"
MASTERS = "Master's"
PHD = "Ph.D"
JD = "J.D."
MD = "M.D."
DDS = "D.D.S."
PHARMD = "Pharm.D."
@related.immutable
class Address(object):
street = related.StringField()
city = related.StringField()
zipcode = related.StringField()
street_two = related.StringField(required=False)
@related.immutable
class Education(object):
school = related.StringField()
degree = related.ChildField(Degree, required=False)
field_of_study = related.StringField(required=False)
from_year = related.IntegerField(required=False)
to_year = related.IntegerField(required=False)
@related.immutable
class Person(object):
name = related.StringField()
age = related.IntegerField(required=False)
address = related.ChildField(Address, required=False, repr=False)
education = related.SequenceField(Education, required=False, repr=False)
| 25.682927 | 76 | 0.701804 |
6d64a5e193652aceb7d8c85f3cfc8ad0400ff6a6 | 7,929 | py | Python | backend/miss_latina_eleganc_34241/settings.py | crowdbotics-apps/miss-latina-eleganc-34241 | 2c097e6858484f950085306249463fe088cbac05 | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | backend/miss_latina_eleganc_34241/settings.py | crowdbotics-apps/miss-latina-eleganc-34241 | 2c097e6858484f950085306249463fe088cbac05 | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | backend/miss_latina_eleganc_34241/settings.py | crowdbotics-apps/miss-latina-eleganc-34241 | 2c097e6858484f950085306249463fe088cbac05 | [
"FTL",
"AML",
"RSA-MD"
] | null | null | null | """
Django settings for miss_latina_eleganc_34241 project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
import io
import environ
import logging
import google.auth
from google.cloud import secretmanager
from google.auth.exceptions import DefaultCredentialsError
from google.api_core.exceptions import PermissionDenied
from modules.manifest import get_modules
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
env_file = os.path.join(BASE_DIR, ".env")
env = environ.Env()
env.read_env(env_file)
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool("DEBUG", default=False)
try:
# Pull secrets from Secret Manager
_, project = google.auth.default()
client = secretmanager.SecretManagerServiceClient()
settings_name = os.environ.get("SETTINGS_NAME", "django_settings")
name = client.secret_version_path(project, settings_name, "latest")
payload = client.access_secret_version(name=name).payload.data.decode("UTF-8")
env.read_env(io.StringIO(payload))
except (DefaultCredentialsError, PermissionDenied):
pass
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str("SECRET_KEY")
ALLOWED_HOSTS = env.list("HOST", default=["*"])
SITE_ID = 1
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = env.bool("SECURE_REDIRECT", default=False)
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites'
]
LOCAL_APPS = [
'home',
'users.apps.UsersConfig',
]
THIRD_PARTY_APPS = [
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_auth.registration',
'bootstrap4',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'django_extensions',
'drf_yasg',
'storages',
]
MODULES_APPS = get_modules()
INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS + MODULES_APPS
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'miss_latina_eleganc_34241.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'web_build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'miss_latina_eleganc_34241.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
if env.str("DATABASE_URL", default=None):
DATABASES = {
'default': env.db()
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware']
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend'
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'web_build/static')]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# allauth / users
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
ACCOUNT_UNIQUE_EMAIL = True
LOGIN_REDIRECT_URL = "users:redirect"
ACCOUNT_ADAPTER = "users.adapters.AccountAdapter"
SOCIALACCOUNT_ADAPTER = "users.adapters.SocialAccountAdapter"
ACCOUNT_ALLOW_REGISTRATION = env.bool("ACCOUNT_ALLOW_REGISTRATION", True)
SOCIALACCOUNT_ALLOW_REGISTRATION = env.bool("SOCIALACCOUNT_ALLOW_REGISTRATION", True)
REST_AUTH_SERIALIZERS = {
# Replace password reset serializer to fix 500 error
"PASSWORD_RESET_SERIALIZER": "home.api.v1.serializers.PasswordSerializer",
}
REST_AUTH_REGISTER_SERIALIZERS = {
# Use custom serializer that has no username and matches web signup
"REGISTER_SERIALIZER": "home.api.v1.serializers.SignupSerializer",
}
# Custom user model
AUTH_USER_MODEL = "users.User"
EMAIL_HOST = env.str("EMAIL_HOST", "smtp.sendgrid.net")
EMAIL_HOST_USER = env.str("SENDGRID_USERNAME", "")
EMAIL_HOST_PASSWORD = env.str("SENDGRID_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# AWS S3 config
AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", "")
AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", "")
AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", "")
AWS_STORAGE_REGION = env.str("AWS_STORAGE_REGION", "")
USE_S3 = (
AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY and
AWS_STORAGE_BUCKET_NAME and
AWS_STORAGE_REGION
)
if USE_S3:
AWS_S3_CUSTOM_DOMAIN = env.str("AWS_S3_CUSTOM_DOMAIN", "")
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_DEFAULT_ACL = env.str("AWS_DEFAULT_ACL", "public-read")
AWS_MEDIA_LOCATION = env.str("AWS_MEDIA_LOCATION", "media")
AWS_AUTO_CREATE_BUCKET = env.bool("AWS_AUTO_CREATE_BUCKET", True)
DEFAULT_FILE_STORAGE = env.str(
"DEFAULT_FILE_STORAGE", "home.storage_backends.MediaStorage"
)
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
# Swagger settings for api docs
SWAGGER_SETTINGS = {
"DEFAULT_INFO": f"{ROOT_URLCONF}.api_info",
}
if DEBUG or not (EMAIL_HOST_USER and EMAIL_HOST_PASSWORD):
# output email to console instead of sending
if not DEBUG:
logging.warning("You should setup `SENDGRID_USERNAME` and `SENDGRID_PASSWORD` env vars to send emails.")
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
# GCP config
GS_BUCKET_NAME = env.str("GS_BUCKET_NAME", "")
if GS_BUCKET_NAME:
DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage"
STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage"
GS_DEFAULT_ACL = "publicRead"
| 30.496154 | 112 | 0.737798 |
800e97a816b45d73d1715ae2363120b2dadb1346 | 7,903 | py | Python | pieface/writeproperties.py | jcumby/PIEFACE | d7027de7b3258022622361e8deedcc827ea5b64f | [
"MIT"
] | 7 | 2017-02-03T12:40:14.000Z | 2021-09-08T17:45:31.000Z | pieface/writeproperties.py | jcumby/PIEFACE | d7027de7b3258022622361e8deedcc827ea5b64f | [
"MIT"
] | 2 | 2018-07-05T09:30:17.000Z | 2021-03-29T13:19:44.000Z | pieface/writeproperties.py | jcumby/PIEFACE | d7027de7b3258022622361e8deedcc827ea5b64f | [
"MIT"
] | 4 | 2017-05-21T17:38:53.000Z | 2020-11-02T17:38:43.000Z | """ Module to write pieface ellipsoid parameters to text file. """
from __future__ import division
import os, sys
import numpy as np
import textwrap
import logging
from time import sleep
# Set up logger
logger = logging.getLogger(__name__)
# Basic Format definitions
fmt_flt = "{:11.6f}"
fmt_lflt = "{:14.8f}"
fmt_str = "{:<11}"
fmt_lstr = "{:<14}"
fmt_vlstr = "{:<25}"
fmt_int = "{:11d}"
fmt_lint = "{:14d}"
fmt_3colstr = "{:<33}"
fmt_vlrstr = "{:>25}"
# Combined formatters based on simple definitions above
fmt_unitcell = fmt_flt*6+"\n"
fmt_atm_cord = fmt_str+fmt_flt*3+"\n"
fmt_llbl_1lflt = fmt_vlstr+":"+fmt_lflt+"\n"
fmt_llbl_3lflt = fmt_vlstr+":"+fmt_lflt+fmt_lflt+fmt_lflt+"\n"
fmt_llbl_1lint = fmt_vlstr+":"+fmt_lint+"\n"
fmt_lbl_9flt_str = fmt_str+fmt_flt*9+fmt_vlrstr+"\n"
fmt_lbl_10flt = fmt_str+fmt_flt*10+"\n"
fmt_lbl_3flt = fmt_str+fmt_flt*3+"\n"
fmt_lbl_3flt_str = fmt_str+fmt_flt*3+fmt_vlrstr+"\n"
def _writeintro(fileob, v=0):
""" Write ellipsoid properties to file. """
if v == 1:
string = """\
# Introduction to the ellipsoid method, perhaps also
# a reference?
"""
fileob.write(textwrap.dedent(string))
if v == 6:
string = """\
# A longer introduction to the ellipsoid method,
# as well as more detail about the parameters
# reported? And a reference?
"""
fileob.write(textwrap.dedent(string))
def _writecrystal(fileob, phase, v=0):
""" Write Crystal data to file. """
if v >= 1:
fileob.write("! Unit cell parameters a b c alpha beta gamma\n")
fileob.write((fmt_unitcell).format(phase.cell['a'],phase.cell['b'],phase.cell['c'],phase.cell['alp'], phase.cell['bet'], phase.cell['gam']))
fileob.write("\n")
if v >= 4:
fileob.write("! Coordinates of all atoms in unit cell ({0})\n".format(len(phase.atoms)))
for site in phase.atoms:
fileob.write(fmt_atm_cord.format(site, *phase.atoms[site]))
fileob.write("\n")
def _writepolyhedron(fileob, phase, cen, v=0):
""" Write details of polyhedron definition """
polyob = getattr(phase, cen+"_poly")
if v == 0:
# Assume we don't want any lists of ligands or coordinates
pass
if v == 1:
fileob.write("! Polyhedron definition {0} ({1}-coordinate) -------\n".format(cen, len(polyob.liglbl)))
fileob.write((fmt_str+fmt_3colstr+"\n").format("# Atom", "Lattice Coords"))
data = [cen] + [p for p in polyob.cenabc] + ["*Central Site"]
fileob.write(fmt_lbl_3flt.format(*data))
for i, lig in enumerate(polyob.liglbl): # Iterate over all sites
data = [lig] + [p for p in polyob.ligabc[i]]
fileob.write(fmt_lbl_3flt.format(*data))
fileob.write("\n")
if v >= 2:
fileob.write("! Polyhedron definition {0} ({1}-coordinate) -------\n".format(cen, len(polyob.liglbl)))
fileob.write((fmt_str+fmt_3colstr*3+fmt_vlrstr+"\n").format("# Atom", "Lattice Coords","CartesianCoords","CartesianCoordsReltoCentre","Centre-ligand bondlength"))
data = [cen] + [p for p in polyob.cenabc] + [p for p in polyob.cenxyz(phase.orthomatrix())]
data = data + [ p for p in polyob.alldelxyz(phase.orthomatrix())[0]] + ["*Central Site"]
fileob.write(fmt_lbl_9flt_str.format(*data))
for i, lig in enumerate(polyob.liglbl): # Iterate over all sites
data = [lig] + [p for p in polyob.ligabc[i]] + [p for p in polyob.ligxyz(phase.orthomatrix())[i]] + [ p for p in polyob.ligdelxyz(phase.orthomatrix())[i]] + [ polyob.allbondlens(phase.mtensor())[i] ]
fileob.write(fmt_lbl_10flt.format(*data))
fileob.write("\n")
def _writeellipsoid(fileob, phase, cen, v=0):
""" Write paramters of fitted ellipsoid """
try:
ellipob = getattr(phase, cen+"_poly").ellipsoid
except AttributeError:
logger.debug("No ellipsoid defined for %s, omitting from output file", cen)
return
if v >= 0:
fileob.write("! Ellipsoid parameters {0} -------\n".format(cen))
fileob.write(fmt_llbl_3lflt.format("Radii R1 > R2 > R3", *ellipob.radii))
fileob.write(fmt_llbl_3lflt.format("Ellipsoid centre x,y,z", *ellipob.centre))
if v >= 1:
fileob.write(fmt_llbl_3lflt.format("Rotation matrix", *ellipob.rotation[0]))
fileob.write(fmt_llbl_3lflt.format("", *ellipob.rotation[1]))
fileob.write(fmt_llbl_3lflt.format("", *ellipob.rotation[2]))
if v >= 2:
fileob.write(fmt_llbl_1lflt.format("Tolerance", ellipob.tolerance))
fileob.write(fmt_llbl_1lflt.format("Mean Radius", ellipob.meanrad()))
fileob.write(fmt_llbl_1lflt.format("Radius Variance", ellipob.radvar()))
fileob.write(fmt_llbl_1lflt.format("Volume", ellipob.ellipsvol()))
if v >= 3:
fileob.write(fmt_llbl_1lint.format("Hyperellipse dims", ellipob.ellipdims))
fileob.write(fmt_llbl_1lint.format("Unique radii", ellipob.uniquerad()))
fileob.write(fmt_llbl_1lflt.format("Equiv. Sphere Radius", ellipob.sphererad()))
fileob.write(fmt_llbl_1lflt.format("Strain Energy", ellipob.strainenergy()))
fileob.write(fmt_llbl_1lflt.format("Shape Parameter", ellipob.shapeparam()))
if v >= 0:
fileob.write('\n')
def _query(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer. """
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'".format(default))
while True:
#print question + prompt
logger.critical(question + prompt)
sleep(1) # Sleep briefly to allow logger to output last message
choice = raw_input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
logger.critical("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")
def writeall(FILE, phase, verbosity=3, overwrite=False):
""" Write data to file
Increasing verbosity above 0 will increase the amount of data printed to file
(4 is maximum output)
"""
if not overwrite:
while True:
if os.path.isfile(FILE):
if not _query("File {0} already exists: do you want to overwrite it?".format(FILE), default="no"):
logger.critical("Enter new filename ([Return] to exit):\t")
sleep(1) # Sleep briefly to allow logger to output last message
#newout = raw_input("Enter new filename ([Return] to exit):\t")
newout = raw_input()
if newout == "":
return
else:
FILE = newout
break
try:
fileob = open(FILE, "w")
except IOError as e:
logger.critical("I/O error({0}): {1}".format(e.errno, e.strerror))
_writeintro(fileob, v=verbosity)
_writecrystal(fileob, phase, v=verbosity)
for site in phase.polyhedra:
_writepolyhedron(fileob, phase, site, v=verbosity)
_writeellipsoid(fileob, phase, site, v=verbosity)
logger.debug("Output written to {0}".format(FILE))
fileob.close()
| 40.321429 | 212 | 0.584588 |
456dd59d855ace162d8085e48ac59639b3185d07 | 406 | py | Python | pendulum/locales/fo/custom.py | rileyjohngibbs/pendulum | f1df7dc3f838bd4ab1075ba25c8b6ce5d8141995 | [
"MIT"
] | null | null | null | pendulum/locales/fo/custom.py | rileyjohngibbs/pendulum | f1df7dc3f838bd4ab1075ba25c8b6ce5d8141995 | [
"MIT"
] | null | null | null | pendulum/locales/fo/custom.py | rileyjohngibbs/pendulum | f1df7dc3f838bd4ab1075ba25c8b6ce5d8141995 | [
"MIT"
] | null | null | null | """
fo custom locale file.
"""
translations = {
# Relative time
"after": "{0} aftaná",
"before": "{0} áðrenn",
# Ordinals
"ordinal": {"other": "."},
# Date formats
"date_formats": {
"LTS": "HH:mm:ss",
"LT": "HH:mm",
"LLLL": "dddd D. MMMM, YYYY HH:mm",
"LLL": "D MMMM YYYY HH:mm",
"LL": "D MMMM YYYY",
"L": "DD/MM/YYYY",
},
}
| 19.333333 | 43 | 0.448276 |
99a6caf117e1cfb8d902418388d83dd9c2590ca8 | 1,174 | py | Python | yearn/db/models.py | pmdaly/yearn-exporter | d1e7697f8bf12cdb1126ea86fa350a26aea23cf8 | [
"MIT"
] | null | null | null | yearn/db/models.py | pmdaly/yearn-exporter | d1e7697f8bf12cdb1126ea86fa350a26aea23cf8 | [
"MIT"
] | null | null | null | yearn/db/models.py | pmdaly/yearn-exporter | d1e7697f8bf12cdb1126ea86fa350a26aea23cf8 | [
"MIT"
] | null | null | null | import os
from datetime import datetime
from typing import List, Optional
from sqlmodel import (
Column,
DateTime,
Field,
Relationship,
Session,
SQLModel,
create_engine,
select,
)
class Block(SQLModel, table=True):
id: int = Field(primary_key=True)
chain_id: int
height: int
timestamp: datetime = Field(sa_column=Column(DateTime(timezone=True)))
snapshot: Optional[datetime] = Field(sa_column=Column(DateTime(timezone=True)))
snapshots: List["Snapshot"] = Relationship(back_populates="block")
class Snapshot(SQLModel, table=True):
id: int = Field(primary_key=True)
product: str
name: str
assets: float
block_id: int = Field(foreign_key="block.id")
block: Block = Relationship(back_populates="snapshots")
pguser = os.environ.get('PGUSER', 'postgres')
pgpassword = os.environ.get('PGPASSWORD', 'yearn')
pghost = os.environ.get('PGHOST', 'localhost')
pgdatabase = os.environ.get('PGDATABASE', 'yearn')
dsn = f'postgresql://{pguser}:{pgpassword}@{pghost}:5432/{pgdatabase}'
engine = create_engine(dsn, echo=False)
# SQLModel.metadata.drop_all(engine)
SQLModel.metadata.create_all(engine)
| 25.521739 | 83 | 0.710392 |
f208609731b5959930f2d50df6f240ec2da89fab | 1,444 | py | Python | telestream_cloud_qc_sdk/test/test_clean_aperture_test.py | pandastream/telestream-cloud-python-sdk | ce0ad503299661a0f622661359367173c06889fc | [
"MIT"
] | null | null | null | telestream_cloud_qc_sdk/test/test_clean_aperture_test.py | pandastream/telestream-cloud-python-sdk | ce0ad503299661a0f622661359367173c06889fc | [
"MIT"
] | 2 | 2016-07-06T14:13:31.000Z | 2018-03-07T12:54:58.000Z | telestream_cloud_qc_sdk/test/test_clean_aperture_test.py | Telestream/telestream-cloud-python-sdk | ce0ad503299661a0f622661359367173c06889fc | [
"MIT"
] | null | null | null | # coding: utf-8
"""
Qc API
Qc API # noqa: E501
The version of the OpenAPI document: 3.0.0
Contact: cloudsupport@telestream.net
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import telestream_cloud_qc
from telestream_cloud_qc.models.clean_aperture_test import CleanApertureTest # noqa: E501
from telestream_cloud_qc.rest import ApiException
class TestCleanApertureTest(unittest.TestCase):
"""CleanApertureTest unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test CleanApertureTest
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# model = telestream_cloud_qc.models.clean_aperture_test.CleanApertureTest() # noqa: E501
if include_optional :
return CleanApertureTest(
reject_on_error = True,
checked = True
)
else :
return CleanApertureTest(
)
def testCleanApertureTest(self):
"""Test CleanApertureTest"""
inst_req_only = self.make_instance(include_optional=False)
inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()
| 26.254545 | 98 | 0.675208 |
59ad6dabf85a3b6633888e0656321961461e168c | 6,900 | bzl | Python | deb/internal/virtual_filesystem.bzl | silvergasp/rules_deb | 4fc707b1c8015d2239579ef6688fda9d95f5d573 | [
"MIT"
] | 4 | 2022-01-09T12:19:37.000Z | 2022-02-03T10:34:50.000Z | deb/internal/virtual_filesystem.bzl | silvergasp/rules_deb | 4fc707b1c8015d2239579ef6688fda9d95f5d573 | [
"MIT"
] | 3 | 2022-01-09T07:36:10.000Z | 2022-01-09T07:43:36.000Z | deb/internal/virtual_filesystem.bzl | silvergasp/rules_deb | 4fc707b1c8015d2239579ef6688fda9d95f5d573 | [
"MIT"
] | null | null | null | """ When extracting debian packages, it is assumed that the it is
overlayed on top of the root filesystem. However as we are extracting
each package to a seperate directory we must be able to produce a
mapping between the package -> Bazel targets.
"""
def _remove_leading_relative_paths(paths):
""" Removes the leading relative path from a path."""
removed = []
for path in paths:
if path.startswith("./"):
removed.append(path[2:])
else:
removed.append(path)
return removed
def _path_to_target(package, path):
""" Converts a path to a Bazel target. """
return "@{package}//:{path}".format(package = package, path = path)
def _find_in_directory(repository_ctx, args):
""" Finds the files in the given directory. """
find_result = repository_ctx.execute(
["find"] + args,
)
if find_result.return_code != 0:
fail("Failed to find files in directory: %s" % find_result.stderr)
return _remove_leading_relative_paths(find_result.stdout.splitlines())
def _get_symlink_target(repository_ctx, path):
""" Gets the target of a symlink. """
readlink_result = repository_ctx.execute(
["realpath", "-m", "--relative-to=.", path],
)
if readlink_result.return_code != 0:
fail("Failed to read symlink: %s" % readlink_result.stderr)
return _remove_leading_relative_paths(
[readlink_result.stdout.strip("\n")],
)[0]
def _find_all_files_in_package(repository_ctx):
""" Find all files in the package.
Args:
repository_ctx: The repository context.
Returns:
A dict containing valid files and broken symlinks.
"""
# Find files and valid symlinks.
valid_files = _find_in_directory(
repository_ctx,
[".", "-not", "-type", "d"],
)
# Find broken symlinks.
broken_symlinks = _find_in_directory(
repository_ctx,
[".", "-type", "l", "-xtype", "l"],
)
broken_symlink_mapping = {
path: _get_symlink_target(repository_ctx, path)
for path in broken_symlinks
}
return {
"valid_files": valid_files,
"broken_symlinks": broken_symlink_mapping,
}
def map_broken_symlinks_to_dependent_targets(
broken_symlinks, # {symlink_path: target_path}
dependent_package_mapping):
return {
symlink_path: dependent_package_mapping.get(target_path, "@broken//dependency")
for symlink_path, target_path in broken_symlinks.items()
}
LOAD_TEMPLATE = \
'load("{script_name}", {local_symbol_name} = "{symbol_name}")'
def _generate_load_statement(script_name, symbol_name, local_symbol_name):
""" Generates a load statement. """
return LOAD_TEMPLATE.format(
script_name = script_name,
symbol_name = symbol_name,
local_symbol_name = local_symbol_name,
)
VFS_TEMPLATE = """
# Repeated loads from dependencies, this should load dependent
# package files.
{loads}
load("@rules_deb//deb/internal:virtual_filesystem.bzl",
"map_broken_symlinks_to_dependent_targets")
load("@bazel_skylib//lib:dicts.bzl", "dicts")
_BROKEN_SYMLINKS = {broken_symlinks}
# Combined files from dependencies.
_DEPENDANT_PACKAGE_FILES = dicts.add({dependant_package_files})
FILE_MAPPING__ = dicts.add({file_mapping},
map_broken_symlinks_to_dependent_targets(
_BROKEN_SYMLINKS,
_DEPENDANT_PACKAGE_FILES,
)
)
SHARED_LIBS = {{f: t
for f, t in FILE_MAPPING__.items()
if f.endswith(".so")}}
# TODO(#3): Uncomment this when we have a way to deal with
# linking PIC and non-PIC static libs. e.g. we need to solve
# 'relocation R_X86_64_PC32 cannot be used against symbol'.
# linker errors.
# STATIC_LIBS = {{f: t
# for f, t in FILE_MAPPING__.items()
# if f.endswith(".a")}}
STATIC_LIBS ={{}}
def deb_file(path):
return FILE_MAPPING__.get(path, None)
"""
def _local_symbol_name(package_name):
return package_name.replace(".", "_").replace("-", "_") + \
"_FILE_MAPPING__"
def _create_dependency_load_statements(dependencies, break_deps):
""" Creates a list of load statements for the given dependencies. """
load_statements = []
variable_names = []
for dependency in dependencies:
if _local_symbol_name(dependency.name) not in variable_names and \
dependency.name not in break_deps:
load_statements.append(_generate_load_statement(
script_name = "@{dep_name}//:vfs.bzl".format(
dep_name = dependency.name,
),
symbol_name = "FILE_MAPPING__",
local_symbol_name = _local_symbol_name(dependency.name),
))
variable_names.append(_local_symbol_name(dependency.name))
return (load_statements, variable_names)
def generate_file_vfs_package_plugin(
file_mapping,
broken_symlinks,
dependencies,
break_deps):
""" Generates a file vfs package plugin.
Generates a .bzl file that stores the mapping between
paths->bazel_targets for the given package. Relative symlinks
are broken by splitting the extraction of each package. Because of this we
need to remap the broken symlinks to the correct target. This is done by
looking up the 'symlink target' path in the target mapping of dependent
packages.
Args:
file_mapping: A dict containing the mapping between paths and bazel
targets.
broken_symlinks: A dict containing the mapping between broken
symlinks and their target.
dependencies: A list of dependencies.
break_deps: A list of dependencies to break.
"""
load_statement_list, variable_names = \
_create_dependency_load_statements(dependencies, break_deps)
return VFS_TEMPLATE.format(
loads = "\n".join(load_statement_list),
broken_symlinks = str(broken_symlinks),
dependant_package_files = ",\n".join(variable_names),
file_mapping = str(file_mapping),
)
def write_path_to_label_mapping(repository_ctx, package_deps, break_deps):
""" Builds a mapping between each file in the package and a Bazel target
Any broken symlinks are resolved to the dependant packages location.
Args:
repository_ctx: The repository context.
package_deps: A list of package dependencies.
break_deps: A list of dependencies to break.
Returns:
A dictionary mapping each path to a Bazel target.
"""
all_files = _find_all_files_in_package(repository_ctx)
package = repository_ctx.name
file_mapping = {
path: _path_to_target(package, path)
for path in all_files["valid_files"]
}
repository_ctx.file("vfs.bzl", generate_file_vfs_package_plugin(
file_mapping,
all_files["broken_symlinks"],
package_deps,
break_deps,
))
| 33.014354 | 87 | 0.677681 |
b8a0bff1d17a0c100c791323c2ffcbb6c95e228a | 13,415 | py | Python | tests/test_app/tests/test_models.py | jmrivas86/django-reversion | daacd7cf74fdefed4d1214588d96a89d6bc02182 | [
"BSD-3-Clause"
] | 1 | 2021-02-17T13:11:16.000Z | 2021-02-17T13:11:16.000Z | tests/test_app/tests/test_models.py | jmrivas86/django-reversion | daacd7cf74fdefed4d1214588d96a89d6bc02182 | [
"BSD-3-Clause"
] | null | null | null | tests/test_app/tests/test_models.py | jmrivas86/django-reversion | daacd7cf74fdefed4d1214588d96a89d6bc02182 | [
"BSD-3-Clause"
] | 1 | 2020-01-08T20:18:17.000Z | 2020-01-08T20:18:17.000Z | from django.utils.encoding import force_text
import reversion
from reversion.models import Version
from test_app.models import TestModel, TestModelRelated, TestModelParent
from test_app.tests.base import TestBase, TestModelMixin, TestModelParentMixin
class GetForModelTest(TestModelMixin, TestBase):
def testGetForModel(self):
with reversion.create_revision():
obj = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_model(obj.__class__).count(), 1)
class GetForModelDbTest(TestModelMixin, TestBase):
def testGetForModelDb(self):
with reversion.create_revision(using="postgres"):
obj = TestModel.objects.create()
self.assertEqual(Version.objects.using("postgres").get_for_model(obj.__class__).count(), 1)
def testGetForModelDbMySql(self):
with reversion.create_revision(using="mysql"):
obj = TestModel.objects.create()
self.assertEqual(Version.objects.using("mysql").get_for_model(obj.__class__).count(), 1)
class GetForObjectTest(TestModelMixin, TestBase):
def testGetForObject(self):
with reversion.create_revision():
obj = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object(obj).count(), 1)
def testGetForObjectEmpty(self):
obj = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object(obj).count(), 0)
def testGetForObjectOrdering(self):
with reversion.create_revision():
obj = TestModel.objects.create()
with reversion.create_revision():
obj.name = "v2"
obj.save()
self.assertEqual(Version.objects.get_for_object(obj)[0].field_dict["name"], "v2")
self.assertEqual(Version.objects.get_for_object(obj)[1].field_dict["name"], "v1")
def testGetForObjectFiltering(self):
with reversion.create_revision():
obj_1 = TestModel.objects.create()
with reversion.create_revision():
obj_2 = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object(obj_1).get().object, obj_1)
self.assertEqual(Version.objects.get_for_object(obj_2).get().object, obj_2)
class GetForObjectDbTest(TestModelMixin, TestBase):
def testGetForObjectDb(self):
with reversion.create_revision(using="postgres"):
obj = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object(obj).count(), 0)
self.assertEqual(Version.objects.using("postgres").get_for_object(obj).count(), 1)
def testGetForObjectDbMySql(self):
with reversion.create_revision(using="mysql"):
obj = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object(obj).count(), 0)
self.assertEqual(Version.objects.using("mysql").get_for_object(obj).count(), 1)
class GetForObjectModelDbTest(TestModelMixin, TestBase):
def testGetForObjectModelDb(self):
with reversion.create_revision():
obj = TestModel.objects.db_manager("postgres").create()
self.assertEqual(Version.objects.get_for_object(obj).count(), 0)
self.assertEqual(Version.objects.get_for_object(obj, model_db="postgres").count(), 1)
class GetForObjectUniqueTest(TestModelMixin, TestBase):
def testGetForObjectUnique(self):
with reversion.create_revision():
obj = TestModel.objects.create()
with reversion.create_revision():
obj.save()
self.assertEqual(len(list(Version.objects.get_for_object(obj).get_unique())), 1)
def testGetForObjectUniqueMiss(self):
with reversion.create_revision():
obj = TestModel.objects.create()
with reversion.create_revision():
obj.name = "v2"
obj.save()
self.assertEqual(len(list(Version.objects.get_for_object(obj).get_unique())), 2)
class GetForObjectReferenceTest(TestModelMixin, TestBase):
def testGetForObjectReference(self):
with reversion.create_revision():
obj = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object_reference(TestModel, obj.pk).count(), 1)
def testGetForObjectReferenceEmpty(self):
obj = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object_reference(TestModel, obj.pk).count(), 0)
def testGetForObjectReferenceOrdering(self):
with reversion.create_revision():
obj = TestModel.objects.create()
with reversion.create_revision():
obj.name = "v2"
obj.save()
self.assertEqual(Version.objects.get_for_object_reference(TestModel, obj.pk)[0].field_dict["name"], "v2")
self.assertEqual(Version.objects.get_for_object_reference(TestModel, obj.pk)[1].field_dict["name"], "v1")
def testGetForObjectReferenceFiltering(self):
with reversion.create_revision():
obj_1 = TestModel.objects.create()
with reversion.create_revision():
obj_2 = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object_reference(TestModel, obj_1.pk).get().object, obj_1)
self.assertEqual(Version.objects.get_for_object_reference(TestModel, obj_2.pk).get().object, obj_2)
class GetForObjectReferenceDbTest(TestModelMixin, TestBase):
def testGetForObjectReferenceModelDb(self):
with reversion.create_revision(using="postgres"):
obj = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object_reference(TestModel, obj.pk).count(), 0)
self.assertEqual(Version.objects.using("postgres").get_for_object_reference(TestModel, obj.pk).count(), 1)
class GetForObjectReferenceModelDbTest(TestModelMixin, TestBase):
def testGetForObjectReferenceModelDb(self):
with reversion.create_revision():
obj = TestModel.objects.db_manager("postgres").create()
self.assertEqual(Version.objects.get_for_object_reference(TestModel, obj.pk).count(), 0)
self.assertEqual(Version.objects.get_for_object_reference(TestModel, obj.pk, model_db="postgres").count(), 1)
def testGetForObjectReferenceModelDbMySql(self):
with reversion.create_revision():
obj = TestModel.objects.db_manager("mysql").create()
self.assertEqual(Version.objects.get_for_object_reference(TestModel, obj.pk).count(), 0)
self.assertEqual(Version.objects.get_for_object_reference(TestModel, obj.pk, model_db="mysql").count(), 1)
class GetDeletedTest(TestModelMixin, TestBase):
def testGetDeleted(self):
with reversion.create_revision():
obj = TestModel.objects.create()
with reversion.create_revision():
obj.save()
obj.delete()
self.assertEqual(Version.objects.get_deleted(TestModel).count(), 1)
def testGetDeletedEmpty(self):
with reversion.create_revision():
TestModel.objects.create()
self.assertEqual(Version.objects.get_deleted(TestModel).count(), 0)
def testGetDeletedOrdering(self):
with reversion.create_revision():
obj_1 = TestModel.objects.create()
with reversion.create_revision():
obj_2 = TestModel.objects.create()
pk_1 = obj_1.pk
obj_1.delete()
pk_2 = obj_2.pk
obj_2.delete()
self.assertEqual(Version.objects.get_deleted(TestModel)[0].object_id, force_text(pk_2))
self.assertEqual(Version.objects.get_deleted(TestModel)[1].object_id, force_text(pk_1))
class GetDeletedDbTest(TestModelMixin, TestBase):
def testGetDeletedDb(self):
with reversion.create_revision(using="postgres"):
obj = TestModel.objects.create()
obj.delete()
self.assertEqual(Version.objects.get_deleted(TestModel).count(), 0)
self.assertEqual(Version.objects.using("postgres").get_deleted(TestModel).count(), 1)
def testGetDeletedDbMySql(self):
with reversion.create_revision(using="mysql"):
obj = TestModel.objects.create()
obj.delete()
self.assertEqual(Version.objects.get_deleted(TestModel).count(), 0)
self.assertEqual(Version.objects.using("mysql").get_deleted(TestModel).count(), 1)
class GetDeletedModelDbTest(TestModelMixin, TestBase):
def testGetDeletedModelDb(self):
with reversion.create_revision():
obj = TestModel.objects.db_manager("postgres").create()
obj.delete()
self.assertEqual(Version.objects.get_deleted(TestModel).count(), 0)
self.assertEqual(Version.objects.get_deleted(TestModel, model_db="postgres").count(), 1)
class FieldDictTest(TestModelMixin, TestBase):
def testFieldDict(self):
with reversion.create_revision():
obj = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object(obj).get().field_dict, {
"id": obj.pk,
"name": "v1",
"related": [],
})
def testFieldDictM2M(self):
obj_related = TestModelRelated.objects.create()
with reversion.create_revision():
obj = TestModel.objects.create()
obj.related.add(obj_related)
self.assertEqual(Version.objects.get_for_object(obj).get().field_dict, {
"id": obj.pk,
"name": "v1",
"related": [],
})
class FieldDictFieldsTest(TestBase):
def testFieldDictFieldFields(self):
reversion.register(TestModel, fields=("name",))
with reversion.create_revision():
obj = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object(obj).get().field_dict, {
"name": "v1",
})
class FieldDictExcludeTest(TestBase):
def testFieldDictFieldExclude(self):
reversion.register(TestModel, exclude=("name",))
with reversion.create_revision():
obj = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object(obj).get().field_dict, {
"id": obj.pk,
"related": [],
})
class FieldDictInheritanceTest(TestModelParentMixin, TestBase):
def testFieldDictInheritance(self):
with reversion.create_revision():
obj = TestModelParent.objects.create()
self.assertEqual(Version.objects.get_for_object(obj).get().field_dict, {
"id": obj.pk,
"name": "v1",
"related": [],
"parent_name": "parent v1",
"testmodel_ptr_id": obj.pk,
})
def testFieldDictInheritanceUpdate(self):
obj = TestModelParent.objects.create()
with reversion.create_revision():
obj.name = "v2"
obj.parent_name = "parent v2"
obj.save()
self.assertEqual(Version.objects.get_for_object(obj).get().field_dict, {
"id": obj.pk,
"name": "v2",
"parent_name": "parent v2",
"related": [],
"testmodel_ptr_id": obj.pk,
})
class RevertTest(TestModelMixin, TestBase):
def testRevert(self):
with reversion.create_revision():
obj = TestModel.objects.create()
with reversion.create_revision():
obj.name = "v2"
obj.save()
Version.objects.get_for_object(obj)[1].revert()
obj.refresh_from_db()
self.assertEqual(obj.name, "v1")
def testRevertBadSerializedData(self):
with reversion.create_revision():
obj = TestModel.objects.create()
Version.objects.get_for_object(obj).update(serialized_data="boom")
with self.assertRaises(reversion.RevertError):
Version.objects.get_for_object(obj).get().revert()
def testRevertBadFormat(self):
with reversion.create_revision():
obj = TestModel.objects.create()
Version.objects.get_for_object(obj).update(format="boom")
with self.assertRaises(reversion.RevertError):
Version.objects.get_for_object(obj).get().revert()
class RevisionRevertTest(TestModelMixin, TestBase):
def testRevert(self):
with reversion.create_revision():
obj_1 = TestModel.objects.create(
name="obj_1 v1"
)
obj_2 = TestModel.objects.create(
name="obj_2 v1"
)
with reversion.create_revision():
obj_1.name = "obj_1 v2"
obj_1.save()
obj_2.name = "obj_2 v2"
obj_2.save()
Version.objects.get_for_object(obj_1)[1].revision.revert()
obj_1.refresh_from_db()
self.assertEqual(obj_1.name, "obj_1 v1")
obj_2.refresh_from_db()
self.assertEqual(obj_2.name, "obj_2 v1")
class RevisionRevertDeleteTest(TestBase):
def testRevertDelete(self):
reversion.register(TestModel, follow=("related",))
reversion.register(TestModelRelated)
with reversion.create_revision():
obj = TestModel.objects.create()
obj_related = TestModelRelated.objects.create()
with reversion.create_revision():
obj.related.add(obj_related)
obj.name = "v2"
obj.save()
Version.objects.get_for_object(obj)[1].revision.revert(delete=True)
obj.refresh_from_db()
self.assertEqual(obj.name, "v1")
self.assertFalse(TestModelRelated.objects.filter(pk=obj_related.pk).exists())
| 38.659942 | 117 | 0.665524 |
4c5f44ad2d656cbb76e1a736e631cc73200e9b4a | 17,183 | py | Python | mask_cyclegan_vc/model.py | tttocklll/MaskCycleGAN-VC | 10465d6ef3c194a28449a925c9de70056cfe92b2 | [
"MIT"
] | 63 | 2021-03-26T22:35:58.000Z | 2022-03-20T11:15:24.000Z | mask_cyclegan_vc/model.py | tttocklll/MaskCycleGAN-VC | 10465d6ef3c194a28449a925c9de70056cfe92b2 | [
"MIT"
] | 19 | 2021-03-30T07:21:37.000Z | 2021-11-29T17:59:38.000Z | mask_cyclegan_vc/model.py | tttocklll/MaskCycleGAN-VC | 10465d6ef3c194a28449a925c9de70056cfe92b2 | [
"MIT"
] | 25 | 2021-04-19T21:42:28.000Z | 2022-03-31T11:36:09.000Z | """
MaskCycleGAN-VC models as described in https://arxiv.org/pdf/2102.12841.pdf
Inspired by https://github.com/jackaduma/CycleGAN-VC2
"""
import numpy as np
import torch
import torch.nn as nn
class GLU(nn.Module):
"""Custom implementation of GLU since the paper assumes GLU won't reduce
the dimension of tensor by 2.
"""
def __init__(self):
super(GLU, self).__init__()
def forward(self, x):
return x * torch.sigmoid(x)
class PixelShuffle(nn.Module):
"""Custom implementation pf Pixel Shuffle since PyTorch's PixelShuffle
requires a 4D input (we have 3D inputs).
"""
def __init__(self, upscale_factor):
super(PixelShuffle, self).__init__()
self.upscale_factor = upscale_factor
def forward(self, x):
n = x.shape[0]
c_out = x.shape[1] // 2
w_new = x.shape[2] * 2
return x.view(n, c_out, w_new)
class ResidualLayer(nn.Module):
"""ResBlock.
"""
def __init__(self, in_channels, out_channels, kernel_size, stride, padding):
super(ResidualLayer, self).__init__()
self.conv1d_layer = nn.Sequential(nn.Conv1d(in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=1,
padding=padding),
nn.InstanceNorm1d(num_features=out_channels,
affine=True))
self.conv_layer_gates = nn.Sequential(nn.Conv1d(in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=1,
padding=padding),
nn.InstanceNorm1d(num_features=out_channels,
affine=True))
self.conv1d_out_layer = nn.Sequential(nn.Conv1d(in_channels=out_channels,
out_channels=in_channels,
kernel_size=kernel_size,
stride=1,
padding=padding),
nn.InstanceNorm1d(num_features=in_channels,
affine=True))
def forward(self, x):
h1_norm = self.conv1d_layer(x)
h1_gates_norm = self.conv_layer_gates(x)
h1_glu = h1_norm * torch.sigmoid(h1_gates_norm) # GLU
h2_norm = self.conv1d_out_layer(h1_glu)
return x + h2_norm
class DownSampleGenerator(nn.Module):
"""Downsampling blocks of the Generator.
"""
def __init__(self, in_channels, out_channels, kernel_size, stride, padding):
super(DownSampleGenerator, self).__init__()
self.convLayer = nn.Sequential(nn.Conv2d(in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding),
nn.InstanceNorm2d(num_features=out_channels,
affine=True))
self.convLayer_gates = nn.Sequential(nn.Conv2d(in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding),
nn.InstanceNorm2d(num_features=out_channels,
affine=True))
def forward(self, x):
# GLU
return self.convLayer(x) * torch.sigmoid(self.convLayer_gates(x))
class Generator(nn.Module):
"""Generator of MaskCycleGAN-VC
"""
def __init__(self, input_shape=(80, 64), residual_in_channels=256):
super(Generator, self).__init__()
Cx, Tx = input_shape
self.flattened_channels = (Cx // 4) * residual_in_channels
# 2D Conv Layer
self.conv1 = nn.Conv2d(in_channels=2,
out_channels=residual_in_channels // 2,
kernel_size=(5, 15),
stride=(1, 1),
padding=(2, 7))
self.conv1_gates = nn.Conv2d(in_channels=2,
out_channels=residual_in_channels // 2,
kernel_size=(5, 15),
stride=1,
padding=(2, 7))
# 2D Downsampling Layers
self.downSample1 = DownSampleGenerator(in_channels=residual_in_channels // 2,
out_channels=residual_in_channels,
kernel_size=5,
stride=2,
padding=2)
self.downSample2 = DownSampleGenerator(in_channels=residual_in_channels,
out_channels=residual_in_channels,
kernel_size=5,
stride=2,
padding=2)
# 2D -> 1D Conv
self.conv2dto1dLayer = nn.Conv1d(in_channels=self.flattened_channels,
out_channels=residual_in_channels,
kernel_size=1,
stride=1,
padding=0)
self.conv2dto1dLayer_tfan = nn.InstanceNorm1d(
num_features=residual_in_channels, affine=True)
# Residual Blocks
self.residualLayer1 = ResidualLayer(in_channels=residual_in_channels,
out_channels=residual_in_channels * 2,
kernel_size=3,
stride=1,
padding=1)
self.residualLayer2 = ResidualLayer(in_channels=residual_in_channels,
out_channels=residual_in_channels * 2,
kernel_size=3,
stride=1,
padding=1)
self.residualLayer3 = ResidualLayer(in_channels=residual_in_channels,
out_channels=residual_in_channels * 2,
kernel_size=3,
stride=1,
padding=1)
self.residualLayer4 = ResidualLayer(in_channels=residual_in_channels,
out_channels=residual_in_channels * 2,
kernel_size=3,
stride=1,
padding=1)
self.residualLayer5 = ResidualLayer(in_channels=residual_in_channels,
out_channels=residual_in_channels * 2,
kernel_size=3,
stride=1,
padding=1)
self.residualLayer6 = ResidualLayer(in_channels=residual_in_channels,
out_channels=residual_in_channels * 2,
kernel_size=3,
stride=1,
padding=1)
# 1D -> 2D Conv
self.conv1dto2dLayer = nn.Conv1d(in_channels=residual_in_channels,
out_channels=self.flattened_channels,
kernel_size=1,
stride=1,
padding=0)
self.conv1dto2dLayer_tfan = nn.InstanceNorm1d(
num_features=self.flattened_channels, affine=True)
# UpSampling Layers
self.upSample1 = self.upsample(in_channels=residual_in_channels,
out_channels=residual_in_channels * 4,
kernel_size=5,
stride=1,
padding=2)
self.glu = GLU()
self.upSample2 = self.upsample(in_channels=residual_in_channels,
out_channels=residual_in_channels * 2,
kernel_size=5,
stride=1,
padding=2)
# 2D Conv Layer
self.lastConvLayer = nn.Conv2d(in_channels=residual_in_channels // 2,
out_channels=1,
kernel_size=(5, 15),
stride=(1, 1),
padding=(2, 7))
def downsample(self, in_channels, out_channels, kernel_size, stride, padding):
self.ConvLayer = nn.Sequential(nn.Conv1d(in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding),
nn.InstanceNorm1d(
num_features=out_channels,
affine=True),
GLU())
return self.ConvLayer
def upsample(self, in_channels, out_channels, kernel_size, stride, padding):
self.convLayer = nn.Sequential(nn.Conv2d(in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding),
nn.PixelShuffle(upscale_factor=2),
nn.InstanceNorm2d(
num_features=out_channels // 4,
affine=True),
GLU())
return self.convLayer
def forward(self, x, mask):
# Conv2d
x = torch.stack((x*mask, mask), dim=1)
conv1 = self.conv1(x) * torch.sigmoid(self.conv1_gates(x)) # GLU
# Downsampling
downsample1 = self.downSample1(conv1)
downsample2 = self.downSample2(downsample1)
# Reshape
reshape2dto1d = downsample2.view(
downsample2.size(0), self.flattened_channels, 1, -1)
reshape2dto1d = reshape2dto1d.squeeze(2)
# 2D -> 1D
conv2dto1d_layer = self.conv2dto1dLayer(reshape2dto1d)
conv2dto1d_layer = self.conv2dto1dLayer_tfan(conv2dto1d_layer)
# Residual Blocks
residual_layer_1 = self.residualLayer1(conv2dto1d_layer)
residual_layer_2 = self.residualLayer2(residual_layer_1)
residual_layer_3 = self.residualLayer3(residual_layer_2)
residual_layer_4 = self.residualLayer4(residual_layer_3)
residual_layer_5 = self.residualLayer5(residual_layer_4)
residual_layer_6 = self.residualLayer6(residual_layer_5)
# 1D -> 2D
conv1dto2d_layer = self.conv1dto2dLayer(residual_layer_6)
conv1dto2d_layer = self.conv1dto2dLayer_tfan(conv1dto2d_layer)
# Reshape
reshape1dto2d = conv1dto2d_layer.unsqueeze(2)
reshape1dto2d = reshape1dto2d.view(reshape1dto2d.size(0), 256, 20, -1)
# UpSampling
upsample_layer_1 = self.upSample1(reshape1dto2d)
upsample_layer_2 = self.upSample2(upsample_layer_1)
# Conv2d
output = self.lastConvLayer(upsample_layer_2)
output = output.squeeze(1)
return output
class Discriminator(nn.Module):
"""PatchGAN discriminator.
"""
def __init__(self, input_shape=(80, 64), residual_in_channels=256):
super(Discriminator, self).__init__()
self.convLayer1 = nn.Sequential(nn.Conv2d(in_channels=1,
out_channels=residual_in_channels // 2,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1)),
GLU())
# Downsampling Layers
self.downSample1 = self.downsample(in_channels=residual_in_channels // 2,
out_channels=residual_in_channels,
kernel_size=(3, 3),
stride=(2, 2),
padding=1)
self.downSample2 = self.downsample(in_channels=residual_in_channels,
out_channels=residual_in_channels * 2,
kernel_size=(3, 3),
stride=[2, 2],
padding=1)
self.downSample3 = self.downsample(in_channels=residual_in_channels * 2,
out_channels=residual_in_channels * 4,
kernel_size=[3, 3],
stride=[2, 2],
padding=1)
self.downSample4 = self.downsample(in_channels=residual_in_channels * 4,
out_channels=residual_in_channels * 4,
kernel_size=[1, 10],
stride=(1, 1),
padding=(0, 2))
# Conv Layer
self.outputConvLayer = nn.Sequential(nn.Conv2d(in_channels=residual_in_channels * 4,
out_channels=1,
kernel_size=(1, 3),
stride=[1, 1],
padding=[0, 1]))
def downsample(self, in_channels, out_channels, kernel_size, stride, padding):
convLayer = nn.Sequential(nn.Conv2d(in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding),
nn.InstanceNorm2d(num_features=out_channels,
affine=True),
GLU())
return convLayer
def forward(self, x):
# x has shape [batch_size, num_features, frames]
# discriminator requires shape [batchSize, 1, num_features, frames]
x = x.unsqueeze(1)
conv_layer_1 = self.convLayer1(x)
downsample1 = self.downSample1(conv_layer_1)
downsample2 = self.downSample2(downsample1)
downsample3 = self.downSample3(downsample2)
output = torch.sigmoid(self.outputConvLayer(downsample3))
return output
if __name__ == '__main__':
# Non exhaustive test for MaskCycleGAN-VC models
# Generator Dimensionality Testing
np.random.seed(0)
residual_in_channels = 256
# input = np.random.randn(2, 80, 64)
input = np.random.randn(2, 80, 64)
input = torch.from_numpy(input).float()
print("Generator input: ", input.shape)
mask = torch.ones_like(input)
generator = Generator(input.shape[1:], residual_in_channels)
output = generator(input, mask)
print("Generator output shape: ", output.shape)
# Discriminator Dimensionality Testing
discriminator = Discriminator(input.shape[1:], residual_in_channels)
output = discriminator(output)
print("Discriminator output shape ", output.shape)
| 46.19086 | 92 | 0.454112 |
ef1ef7c04666b6a58c17000203cc31836c13ad19 | 150 | py | Python | MixNotes/123.py | nickliqian/ralph_doc_to_chinese | be120ce2bb94a8e8395630218985f5e51ae087d9 | [
"MIT"
] | 8 | 2018-05-22T01:11:33.000Z | 2020-03-19T01:44:55.000Z | MixNotes/123.py | yangliangguang/keep_learning | 47ab39c726cb28713ad22bf4cf39d6b146715910 | [
"MIT"
] | null | null | null | MixNotes/123.py | yangliangguang/keep_learning | 47ab39c726cb28713ad22bf4cf39d6b146715910 | [
"MIT"
] | 3 | 2018-07-25T09:31:53.000Z | 2019-09-14T14:05:31.000Z | import getopt
args = '-a -b 35 -cfoo -d bar -f a1 a2'.split()
print(args)
optlist, args = getopt.getopt(args, 'abc:d:f')
print(optlist)
print(args)
| 16.666667 | 47 | 0.666667 |
b8534579e3a8792540c016e899a3c0ece2edfaa5 | 3,382 | py | Python | os_migrate/plugins/modules/export_security_group_rules.py | rbrady/os-migrate | fec256075307a4a11fb1b6e154737a1c3b34f0dd | [
"Apache-2.0"
] | 1 | 2021-09-24T10:36:26.000Z | 2021-09-24T10:36:26.000Z | os_migrate/plugins/modules/export_security_group_rules.py | rbrady/os-migrate | fec256075307a4a11fb1b6e154737a1c3b34f0dd | [
"Apache-2.0"
] | null | null | null | os_migrate/plugins/modules/export_security_group_rules.py | rbrady/os-migrate | fec256075307a4a11fb1b6e154737a1c3b34f0dd | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: export_security_group_rules
short_description: Export OpenStack security group rules
extends_documentation_fragment: openstack
version_added: "2.9"
author: "OpenStack tenant migration tools (@os-migrate)"
description:
- "Export an OpenStack security group rules definition into an OS-Migrate YAML"
options:
auth:
description:
- Dictionary with parameters for chosen auth type.
required: true
type: dict
auth_type:
description:
- Auth type plugin for OpenStack. Can be omitted if using password authentication.
required: false
type: str
region_name:
description:
- OpenStack region name. Can be omitted if using default region.
required: false
type: str
path:
description:
- Resources YAML file to where security groups will be serialized.
- In case the resource file already exists, it must match the
os-migrate version.
- In case the resource of same type and name exists in the file,
it will be replaced.
required: true
type: str
name:
description:
- Name of the security group. OS-Migrate requires unique resource names.
required: true
type: str
availability_zone:
description:
- Availability zone.
required: false
type: str
cloud:
description:
- Ignored. Present for backwards compatibility.
required: false
type: raw
'''
EXAMPLES = '''
- name: Export security groups into /opt/os-migrate/security_groups.yml
os_migrate.os_migrate.export_security_group_rules:
cloud: source_cloud
path: /opt/os-migrate/security_groups.yml
name: mysecgroup
'''
RETURN = '''
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack \
import openstack_full_argument_spec, openstack_cloud_from_module
from ansible_collections.os_migrate.os_migrate.plugins.module_utils import filesystem
from ansible_collections.os_migrate.os_migrate.plugins.module_utils import security_group_rule
def run_module():
argument_spec = openstack_full_argument_spec(
path=dict(type='str', required=True),
name=dict(type='str', required=True),
)
# TODO: check the del
# del argument_spec['cloud']
result = dict(
changed=False,
)
module = AnsibleModule(
argument_spec=argument_spec,
# TODO: Consider check mode. We'd fetch the resource and check
# if the file representation matches it.
# supports_check_mode=True,
)
sdk, conn = openstack_cloud_from_module(module)
sdk_sec = conn.network.find_security_group(module.params['name'], ignore_missing=False)
sdk_rules = conn.network.security_group_rules(security_group_id=sdk_sec['id'])
result['changed'] = False
for sdk_rule in sdk_rules:
ser_rule = security_group_rule.SecurityGroupRule.from_sdk(conn, sdk_rule)
rchanged = filesystem.write_or_replace_resource(module.params['path'], ser_rule)
if rchanged:
result['changed'] = True
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()
| 26.015385 | 94 | 0.707569 |
cc914b2114450404439133788c1400fb722425ad | 549 | py | Python | python_advance/requests请求重试/flask_server.py | Dustyposa/goSpider | 8faf077e73bf6f0b1ffa05366876e89ddf648e9d | [
"MIT"
] | 66 | 2019-04-10T07:34:57.000Z | 2021-12-23T09:39:38.000Z | python_advance/requests请求重试/flask_server.py | Dustyposa/goSpider | 8faf077e73bf6f0b1ffa05366876e89ddf648e9d | [
"MIT"
] | 1 | 2021-12-02T07:45:33.000Z | 2021-12-02T07:45:33.000Z | python_advance/requests请求重试/flask_server.py | Dustyposa/goSpider | 8faf077e73bf6f0b1ffa05366876e89ddf648e9d | [
"MIT"
] | 13 | 2019-04-14T12:45:54.000Z | 2021-09-15T08:53:21.000Z | from time import sleep
from flask import Flask, jsonify, Response
app: Flask = Flask(__name__)
retry_count: int = 0 # 用于重试请求的计数
@app.route("/api/retry", methods=["GET"])
def retry_api() -> Response:
"""
延时 1s 的请求接口, 响应时间 > 1s。
:return:
"""
global retry_count
retry_count += 1
print(f"这是第{retry_count}次请求")
if retry_count < 3:
sleep(1)
else:
retry_count = 0 # 计数清零
return jsonify({"msg": "已经三次了哦!"})
# @app.route("/")
if __name__ == '__main__':
app.run(host="0.0.0.0", port=9999)
| 18.3 | 42 | 0.59745 |
6db266baaa16c367e0795500605b5ad48662cadf | 11,228 | py | Python | experiment/generate_tests.py | fabiand/test-infra | cf8e12368691f996f411b5ccf508777b1c0c3fd4 | [
"Apache-2.0"
] | 1 | 2019-04-01T06:20:56.000Z | 2019-04-01T06:20:56.000Z | experiment/generate_tests.py | fabiand/test-infra | cf8e12368691f996f411b5ccf508777b1c0c3fd4 | [
"Apache-2.0"
] | null | null | null | experiment/generate_tests.py | fabiand/test-infra | cf8e12368691f996f411b5ccf508777b1c0c3fd4 | [
"Apache-2.0"
] | 1 | 2018-09-27T19:28:56.000Z | 2018-09-27T19:28:56.000Z | #!/usr/bin/env python
# Copyright 2017 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Create e2e test definitions.
Usage example:
In $GOPATH/src/k8s.io/test-infra,
$ bazel run //experiment:generate_tests -- \
--yaml-config-path=experiment/test_config.yaml \
"""
import argparse
import hashlib
import os
import ruamel.yaml as yaml
# TODO(yguo0905): Generate Prow and testgrid configurations.
PROW_CONFIG_TEMPLATE = """
tags:
- generated # AUTO-GENERATED by experiment/generate_tests.py - DO NOT EDIT!
interval:
agent: kubernetes
labels:
preset-service-account: "true"
preset-k8s-ssh: "true"
name:
spec:
containers:
- args:
env:
image: gcr.io/k8s-testimages/kubekins-e2e:v20180730-8b7ab3104-master
"""
COMMENT = 'AUTO-GENERATED by experiment/generate_tests.py - DO NOT EDIT.'
def get_sha1_hash(data):
"""Returns the SHA1 hash of the specified data."""
sha1_hash = hashlib.sha1()
sha1_hash.update(data)
return sha1_hash.hexdigest()
def substitute(job_name, lines):
"""Replace '${job_name_hash}' in lines with the SHA1 hash of job_name."""
return [line.replace('${job_name_hash}', get_sha1_hash(job_name)[:10]) \
for line in lines]
def get_args(job_name, field):
"""Returns a list of args for the given field."""
if not field:
return []
return substitute(job_name, field.get('args', []))
def write_prow_configs_file(output_file, job_defs):
"""Writes the Prow configurations into output_file."""
with open(output_file, 'w') as fp:
yaml.dump(
job_defs, fp, Dumper=yaml.RoundTripDumper, width=float("inf"))
fp.write('\n')
def apply_job_overrides(envs_or_args, job_envs_or_args):
'''Applies the envs or args overrides defined in the job level'''
for job_env_or_arg in job_envs_or_args:
name = job_env_or_arg.split('=', 1)[0]
env_or_arg = next(
(x for x in envs_or_args if (x.strip().startswith('%s=' % name) or
x.strip() == name)), None)
if env_or_arg:
envs_or_args.remove(env_or_arg)
envs_or_args.append(job_env_or_arg)
class E2ENodeTest(object):
def __init__(self, job_name, job, config):
self.job_name = job_name
self.job = job
self.common = config['nodeCommon']
self.images = config['nodeImages']
self.k8s_versions = config['nodeK8sVersions']
self.test_suites = config['nodeTestSuites']
def __get_job_def(self, args):
"""Returns the job definition from the given args."""
return {
'scenario': 'kubernetes_e2e',
'args': args,
'sigOwners': self.job.get('sigOwners') or ['UNNOWN'],
# Indicates that this job definition is auto-generated.
'tags': ['generated'],
'_comment': COMMENT,
}
def __get_prow_config(self, test_suite, k8s_version):
"""Returns the Prow config for the job from the given fields."""
prow_config = yaml.round_trip_load(PROW_CONFIG_TEMPLATE)
prow_config['name'] = self.job_name
prow_config['interval'] = self.job['interval']
# Assumes that the value in --timeout is of minutes.
timeout = int(next(
x[10:-1] for x in test_suite['args'] if (
x.startswith('--timeout='))))
container = prow_config['spec']['containers'][0]
if not container['args']:
container['args'] = []
if not container['env']:
container['env'] = []
# Prow timeout = job timeout + 20min
container['args'].append('--timeout=%d' % (timeout + 20))
container['args'].extend(k8s_version.get('args', []))
container['args'].append('--root=/go/src')
container['env'].extend([{'name':'GOPATH', 'value': '/go'}])
# Specify the appropriate kubekins-e2e image. This allows us to use a
# specific image (containing a particular Go version) to build and
# trigger the node e2e test to avoid issues like
# https://github.com/kubernetes/kubernetes/issues/43534.
if k8s_version.get('prowImage', None):
container['image'] = k8s_version['prowImage']
return prow_config
def generate(self):
'''Returns the job and the Prow configurations for this test.'''
fields = self.job_name.split('-')
if len(fields) != 6:
raise ValueError('Expected 6 fields in job name', self.job_name)
image = self.images[fields[3]]
k8s_version = self.k8s_versions[fields[4][3:]]
test_suite = self.test_suites[fields[5]]
# envs are disallowed in node e2e tests.
if 'envs' in self.common or 'envs' in image or 'envs' in test_suite:
raise ValueError(
'envs are disallowed in node e2e test', self.job_name)
# Generates args.
args = []
args.extend(get_args(self.job_name, self.common))
args.extend(get_args(self.job_name, image))
args.extend(get_args(self.job_name, test_suite))
# Generates job config.
job_config = self.__get_job_def(args)
# Generates prow config.
prow_config = self.__get_prow_config(test_suite, k8s_version)
# Combine --node-args
node_args = []
job_args = []
for arg in job_config['args']:
if '--node-args=' in arg:
node_args.append(arg.split('=', 1)[1])
else:
job_args.append(arg)
if node_args:
flag = '--node-args='
for node_arg in node_args:
flag += '%s ' % node_arg
job_args.append(flag.strip())
job_config['args'] = job_args
return job_config, prow_config
class E2ETest(object):
def __init__(self, output_dir, job_name, job, config):
self.env_filename = os.path.join(output_dir, '%s.env' % job_name),
self.job_name = job_name
self.job = job
self.common = config['common']
self.cloud_providers = config['cloudProviders']
self.images = config['images']
self.k8s_versions = config['k8sVersions']
self.test_suites = config['testSuites']
def __get_job_def(self, args):
"""Returns the job definition from the given args."""
return {
'scenario': 'kubernetes_e2e',
'args': args,
'sigOwners': self.job.get('sigOwners') or ['UNNOWN'],
# Indicates that this job definition is auto-generated.
'tags': ['generated'],
'_comment': COMMENT,
}
def __get_prow_config(self, test_suite):
"""Returns the Prow config for the e2e job from the given fields."""
prow_config = yaml.round_trip_load(PROW_CONFIG_TEMPLATE)
prow_config['name'] = self.job_name
prow_config['interval'] = self.job['interval']
# Assumes that the value in --timeout is of minutes.
timeout = int(next(
x[10:-1] for x in test_suite['args'] if (
x.startswith('--timeout='))))
container = prow_config['spec']['containers'][0]
if not container['args']:
container['args'] = []
container['args'].append('--bare')
# Prow timeout = job timeout + 20min
container['args'].append('--timeout=%d' % (timeout + 20))
return prow_config
def generate(self):
'''Returns the job and the Prow configurations for this test.'''
fields = self.job_name.split('-')
if len(fields) != 7:
raise ValueError('Expected 7 fields in job name', self.job_name)
cloud_provider = self.cloud_providers[fields[3]]
image = self.images[fields[4]]
k8s_version = self.k8s_versions[fields[5][3:]]
test_suite = self.test_suites[fields[6]]
# Generates args.
args = []
args.extend(get_args(self.job_name, self.common))
args.extend(get_args(self.job_name, cloud_provider))
args.extend(get_args(self.job_name, image))
args.extend(get_args(self.job_name, k8s_version))
args.extend(get_args(self.job_name, test_suite))
# Generates job config.
job_config = self.__get_job_def(args)
# Generates Prow config.
prow_config = self.__get_prow_config(test_suite)
return job_config, prow_config
def for_each_job(output_dir, job_name, job, yaml_config):
"""Returns the job config and the Prow config for one test job."""
fields = job_name.split('-')
if len(fields) < 3:
raise ValueError('Expected at least 3 fields in job name', job_name)
job_type = fields[2]
# Generates configurations.
if job_type == 'e2e':
generator = E2ETest(output_dir, job_name, job, yaml_config)
elif job_type == 'e2enode':
generator = E2ENodeTest(job_name, job, yaml_config)
else:
raise ValueError('Unexpected job type ', job_type)
job_config, prow_config = generator.generate()
# Applies job-level overrides.
apply_job_overrides(job_config['args'], get_args(job_name, job))
# merge job_config into prow_config
args = prow_config['spec']['containers'][0]['args']
args.append('--scenario=' + job_config['scenario'])
args.append('--')
args.extend(job_config['args'])
return prow_config
def main(yaml_config_path, output_dir):
"""Creates test job definitions.
Converts the test configurations in yaml_config_path to the job definitions
in output_dir/generated.yaml.
"""
# TODO(yguo0905): Validate the configurations from yaml_config_path.
with open(yaml_config_path) as fp:
yaml_config = yaml.safe_load(fp)
output_config = {}
output_config['periodics'] = []
for job_name, _ in yaml_config['jobs'].items():
# Get the envs and args for each job defined under "jobs".
prow = for_each_job(
output_dir, job_name, yaml_config['jobs'][job_name], yaml_config)
output_config['periodics'].append(prow)
# Write the job definitions to --output-dir/generated.yaml
write_prow_configs_file(output_dir + 'generated.yaml', output_config)
if __name__ == '__main__':
PARSER = argparse.ArgumentParser(
description='Create test definitions from the given yaml config')
PARSER.add_argument('--yaml-config-path', help='Path to config.yaml')
PARSER.add_argument(
'--output-dir',
help='Prowjob config output dir',
default='config/jobs/kubernetes/generated/')
ARGS = PARSER.parse_args()
main(
ARGS.yaml_config_path,
ARGS.output_dir)
| 35.644444 | 79 | 0.629943 |
0835d277097bbbd36a91a13379cfe8c97fe1b21f | 5,730 | py | Python | colossalai/nn/loss/loss_3d.py | mrriteshranjan/ColossalAI | 0d057a1bae67b915a385be7edab7da83413cb645 | [
"Apache-2.0"
] | null | null | null | colossalai/nn/loss/loss_3d.py | mrriteshranjan/ColossalAI | 0d057a1bae67b915a385be7edab7da83413cb645 | [
"Apache-2.0"
] | null | null | null | colossalai/nn/loss/loss_3d.py | mrriteshranjan/ColossalAI | 0d057a1bae67b915a385be7edab7da83413cb645 | [
"Apache-2.0"
] | null | null | null | import torch
import torch.distributed as dist
from colossalai.constants import INPUT_GROUP_3D, WEIGHT_GROUP_3D, OUTPUT_GROUP_3D
from colossalai.core import global_context as gpc
from colossalai.nn.layer.parallel_3d import reduce_by_batch_3d, split_tensor_3d
from colossalai.nn.layer.parallel_3d._utils import get_parallel_mode_from_env
from colossalai.registry import LOSSES
from colossalai.utils import get_current_device
from torch.cuda.amp import custom_bwd, custom_fwd
from torch.nn.functional import cross_entropy
from torch.nn.modules.loss import _Loss
@LOSSES.register_module
class CrossEntropyLoss3D(_Loss):
"""
Cross entropy loss for 3D parallelism
:param reduction: whether to average the loss, defaults to True
:param args: Args for loss function
:param kwargs: Kwargs for loss function
:type reduction: bool, optional
"""
def __init__(self, reduction=True, *args, **kwargs):
super().__init__()
self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D)
self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D)
self.reduction_mean = reduction
self.loss_args = args
self.loss_kwargs = kwargs
def forward(self, logits, targets):
"""Calculate loss between logits and targets
:param logits: Output logits of model
:param targets: True targets from data
"""
targets = split_tensor_3d(targets, 0, self.weight_parallel_mode)
targets = split_tensor_3d(targets, 0, self.input_parallel_mode)
loss = cross_entropy(logits, targets, reduction='none', *self.loss_args, **self.loss_kwargs)
if self.reduction_mean:
loss = loss.mean()
loss = reduce_by_batch_3d(loss, self.input_parallel_mode, self.weight_parallel_mode, True)
return loss
class _VocabParallelCrossEntropy3D(torch.autograd.Function):
# Adapted from megatron.mpu.cross_entropy
# loss[i] = -logits[i][targets] + log(sum(exp(logits[i])))
@staticmethod
@custom_fwd(cast_inputs=torch.float32)
def forward(ctx, logits, targets, output_parallel_mode):
# logits: [b/q^2, c/q]
# labels: [b/q^2]
# loss: [b/q^2]
logits_max = torch.max(logits, dim=-1)[0]
dist.all_reduce(logits_max, op=torch.distributed.ReduceOp.MAX, group=gpc.get_group(output_parallel_mode))
# Subtract the maximum value.
logits = logits - logits_max.unsqueeze(dim=-1)
vocab_size_per_partition = logits.size()[-1]
rank = gpc.get_local_rank(output_parallel_mode)
vocab_start = rank * vocab_size_per_partition
vocab_end = (rank + 1) * vocab_size_per_partition - 1
# loss[i] = 0 if targets[i] < vocab_start or targets[i] > vocab_end
target_mask = (targets < vocab_start) | (targets > vocab_end)
masked_target = targets.clone() - vocab_start
masked_target[target_mask] = 0
arange_1d = torch.arange(start=0, end=logits.size()[0], device=get_current_device())
predicted_logits = logits[arange_1d, masked_target]
predicted_logits = predicted_logits.clone().contiguous().view_as(targets)
predicted_logits[target_mask] = 0.
dist.all_reduce(predicted_logits, group=gpc.get_group(output_parallel_mode))
# Loss = log(sum(exp(logits))) - predicted-logit.
exp_logits = torch.exp(logits)
sum_exp_logits = exp_logits.sum(dim=-1)
dist.all_reduce(sum_exp_logits, group=gpc.get_group(output_parallel_mode))
loss = torch.log(sum_exp_logits) - predicted_logits
exp_logits.div_(sum_exp_logits.unsqueeze(dim=-1))
ctx.save_for_backward(exp_logits, target_mask, masked_target)
return loss
@staticmethod
@custom_bwd
def backward(ctx, output_grad):
# Retreive tensors from the forward path.
softmax, target_mask, masked_target = ctx.saved_tensors
# All the inputs have softmax as thier gradient.
input_grad = softmax
# For simplicity, work with the 2D gradient.
partition_vocab_size = softmax.size()[-1]
grad_2d = input_grad.view(-1, partition_vocab_size)
# Add the gradient from matching classes.
arange_1d = torch.arange(start=0, end=grad_2d.size()[0], device=get_current_device())
grad_2d[arange_1d, masked_target] -= (1.0 - target_mask.view(-1).float())
input_grad.mul_(output_grad.unsqueeze(dim=-1))
return input_grad, None, None, None
@LOSSES.register_module
class VocabParallelCrossEntropyLoss3D(_Loss):
"""
Vocab parallel cross entropy loss for 2D parallelism
:param reduction: whether to average the loss, defaults to True
:type reduction: bool, optional
"""
def __init__(self, reduction=True):
super().__init__()
self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D)
self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D)
self.output_parallel_mode = get_parallel_mode_from_env(OUTPUT_GROUP_3D)
self.reduction_mean = reduction
def forward(self, logits, targets):
"""Calculate loss between logits and targets
:param logits: Output logits of model
:param targets: True targets from data
"""
targets = split_tensor_3d(targets, 0, self.weight_parallel_mode)
targets = split_tensor_3d(targets, 0, self.input_parallel_mode)
loss = _VocabParallelCrossEntropy3D.apply(logits, targets, self.output_parallel_mode)
if self.reduction_mean:
loss = loss.mean()
loss = reduce_by_batch_3d(loss, self.input_parallel_mode, self.weight_parallel_mode, True)
return loss
| 40.928571 | 113 | 0.703839 |
87277c44b2f18628963c86ae71890033499a287a | 5,063 | py | Python | OpenPoseImage.py | NusaibaNizam/Anonymous-Person-Tracking-across-Multiple-Camera-Using-Color-Histogram-and | bd65abb830e7f6a6651f2d9ddba67415880fd42a | [
"Apache-2.0"
] | null | null | null | OpenPoseImage.py | NusaibaNizam/Anonymous-Person-Tracking-across-Multiple-Camera-Using-Color-Histogram-and | bd65abb830e7f6a6651f2d9ddba67415880fd42a | [
"Apache-2.0"
] | null | null | null | OpenPoseImage.py | NusaibaNizam/Anonymous-Person-Tracking-across-Multiple-Camera-Using-Color-Histogram-and | bd65abb830e7f6a6651f2d9ddba67415880fd42a | [
"Apache-2.0"
] | null | null | null | import cv2
import time
import numpy as np
import math
#import argparse
# parser = argparse.ArgumentParser(description='Run keypoint detection')
# parser.add_argument("--device", default="gpu", help="Device to inference on")
# parser.add_argument("--image_file", default="single.jpeg", help="Input image")
#
# args = parser.parse_args()
#
def openpose(image_file, device):
MODE = "COCO"
frame_ary=[]
if MODE is "COCO":
protoFile = "pose/coco/pose_deploy_linevec.prototxt"
weightsFile = "pose/coco/pose_iter_440000.caffemodel"
nPoints = 18
POSE_PAIRS = [ [1,0],[1,2],[1,5],[2,3],[3,4],[5,6],[6,7],[1,8],[8,9],[9,10],[1,11],[11,12],[12,13],[0,14],[0,15],[14,16],[15,17]]
elif MODE is "MPI" :
protoFile = "pose/mpi/pose_deploy_linevec_faster_4_stages.prototxt"
weightsFile = "pose/mpi/pose_iter_160000.caffemodel"
nPoints = 15
POSE_PAIRS = [[0,1], [1,2], [2,3], [3,4], [1,5], [5,6], [6,7], [1,14], [14,8], [8,9], [9,10], [14,11], [11,12], [12,13] ]
frame = image_file
frameCopy = np.copy(frame)
frameWidth = frame.shape[1]
frameHeight = frame.shape[0]
threshold = 0.1
net = cv2.dnn.readNetFromCaffe(protoFile, weightsFile)
if device == "cpu":
net.setPreferableBackend(cv2.dnn.DNN_TARGET_CPU)
#print("Using CPU device")
elif device == "gpu":
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
print("Using GPU device")
t = time.time()
# input image dimensions for the network
inWidth = 368
inHeight = 368
inpBlob = cv2.dnn.blobFromImage(frame, 1.0 / 255, (inWidth, inHeight),
(0, 0, 0), swapRB=False, crop=False)
net.setInput(inpBlob)
output = net.forward()
print("time taken by network : {:.3f}".format(time.time() - t))
H = output.shape[2]
W = output.shape[3]
# Empty list to store the detected keypoints
points = []
for i in range(nPoints):
# confidence map of corresponding body's part.
probMap = output[0, i, :, :]
# Find global maxima of the probMap.
minVal, prob, minLoc, point = cv2.minMaxLoc(probMap)
# Scale the point to fit on the original image
x = (frameWidth * point[0]) / W
y = (frameHeight * point[1]) / H
if prob > threshold :
# cv2.circle(frameCopy, (int(x), int(y)), 1, (0, 255, 255), thickness=-1, lineType=cv2.FILLED)
# cv2.putText(frameCopy, "{}".format(i), (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, lineType=cv2.LINE_AA)
# Add the point to the list if the probability is greater than the threshold
points.append((int(x), int(y)))
else :
points.append(None)
# Draw Skeleton
if points[8] and points[9] and points[10]:
deltaX11 = points[8][0] - points[9][0]
deltaY11 = points[8][1] - points[9][1]
deltaX21 = points[10][0] - points[9][0]
deltaY21 = points[10][1] - points[9][1]
angle1 = (math.atan2(deltaX11, deltaY11) - math.atan2(deltaX21, deltaY21)) / math.pi * 180
frame_ary.extend([abs(angle1)])
if points[11] and points[12] and points[13]:
deltaX12 = points[11][0] - points[12][0]
deltaY12 = points[11][1] - points[12][1]
deltaX22 = points[13][0] - points[12][0]
deltaY22 = points[13][1] - points[12][1]
angle2 = (math.atan2(deltaX12, deltaY12) - math.atan2(deltaX22, deltaY22)) / math.pi * 180
frame_ary.extend([abs(angle2)])
if points[2] and points[3] and points[4]:
deltaX13 = points[2][0] - points[3][0]
deltaY13 = points[2][1] - points[3][1]
deltaX23 = points[4][0] - points[3][0]
deltaY23 = points[4][1] - points[3][1]
angle3 = (math.atan2(deltaX13, deltaY13) - math.atan2(deltaX23, deltaY23)) / math.pi * 180
frame_ary.extend([abs(angle3)])
if points[5] and points[6] and points[7]:
deltaX14 = points[5][0] - points[6][0]
deltaY14 = points[5][1] - points[6][1]
deltaX24 = points[7][0] - points[6][0]
deltaY24 = points[7][1] - points[6][1]
angle4 = (math.atan2(deltaX14, deltaY14) - math.atan2(deltaX24, deltaY24)) / math.pi * 180
frame_ary.extend([abs(angle4)])
# for pair in POSE_PAIRS:
# partA = pair[0]
# partB = pair[1]
#
# if points[partA] and points[partB]:
# cv2.line(frame, points[partA], points[partB], (0, 255, 255), 2)
# cv2.circle(frame, points[partA], 3, (0, 0, 255), thickness=-1, lineType=cv2.FILLED)
# cv2.circle(frame, points[partB], 3, (0, 0, 255), thickness=-1, lineType=cv2.FILLED)
#
# cv2.imshow('Output-Keypoints', frameCopy)
# cv2.imshow('Output-Skeleton', frame)
#
# cv2.imwrite('Output-Keypoints.jpg', frameCopy)
# cv2.imwrite('Output-Skeleton.jpg', frame)
#
# print("Total time taken : {:.3f}".format(time.time() - t))
return frame_ary
| 37.783582 | 137 | 0.592139 |
bf70f499ec693f470c37f0416512db8550eaa848 | 5,018 | py | Python | homeassistant/components/sensibo/entity.py | mcx/core | 55eca2e2b4ebcf11486749035fd3c7e77ea14b8f | [
"Apache-2.0"
] | null | null | null | homeassistant/components/sensibo/entity.py | mcx/core | 55eca2e2b4ebcf11486749035fd3c7e77ea14b8f | [
"Apache-2.0"
] | null | null | null | homeassistant/components/sensibo/entity.py | mcx/core | 55eca2e2b4ebcf11486749035fd3c7e77ea14b8f | [
"Apache-2.0"
] | null | null | null | """Base entity for Sensibo integration."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import async_timeout
from pysensibo.model import MotionSensor, SensiboDevice
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, LOGGER, SENSIBO_ERRORS, TIMEOUT
from .coordinator import SensiboDataUpdateCoordinator
class SensiboBaseEntity(CoordinatorEntity[SensiboDataUpdateCoordinator]):
"""Representation of a Sensibo entity."""
def __init__(
self,
coordinator: SensiboDataUpdateCoordinator,
device_id: str,
) -> None:
"""Initiate Sensibo Number."""
super().__init__(coordinator)
self._device_id = device_id
self._client = coordinator.client
@property
def device_data(self) -> SensiboDevice:
"""Return data for device."""
return self.coordinator.data.parsed[self._device_id]
class SensiboDeviceBaseEntity(SensiboBaseEntity):
"""Representation of a Sensibo device."""
def __init__(
self,
coordinator: SensiboDataUpdateCoordinator,
device_id: str,
) -> None:
"""Initiate Sensibo Number."""
super().__init__(coordinator, device_id)
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, self.device_data.id)},
name=self.device_data.name,
connections={(CONNECTION_NETWORK_MAC, self.device_data.mac)},
manufacturer="Sensibo",
configuration_url="https://home.sensibo.com/",
model=self.device_data.model,
sw_version=self.device_data.fw_ver,
hw_version=self.device_data.fw_type,
suggested_area=self.device_data.name,
)
async def async_send_command(
self, command: str, params: dict[str, Any] | None = None
) -> dict[str, Any]:
"""Send command to Sensibo api."""
try:
async with async_timeout.timeout(TIMEOUT):
result = await self.async_send_api_call(command, params)
except SENSIBO_ERRORS as err:
raise HomeAssistantError(
f"Failed to send command {command} for device {self.name} to Sensibo servers: {err}"
) from err
LOGGER.debug("Result: %s", result)
return result
async def async_send_api_call(
self, command: str, params: dict[str, Any] | None = None
) -> dict[str, Any]:
"""Send api call."""
result: dict[str, Any] = {"status": None}
if command == "set_calibration":
if TYPE_CHECKING:
assert params is not None
result = await self._client.async_set_calibration(
self._device_id,
params["data"],
)
if command == "set_ac_state":
if TYPE_CHECKING:
assert params is not None
result = await self._client.async_set_ac_state_property(
self._device_id,
params["name"],
params["value"],
params["ac_states"],
params["assumed_state"],
)
if command == "set_timer":
if TYPE_CHECKING:
assert params is not None
result = await self._client.async_set_timer(self._device_id, params)
if command == "del_timer":
result = await self._client.async_del_timer(self._device_id)
if command == "set_pure_boost":
if TYPE_CHECKING:
assert params is not None
result = await self._client.async_set_pureboost(
self._device_id,
params,
)
return result
class SensiboMotionBaseEntity(SensiboBaseEntity):
"""Representation of a Sensibo motion entity."""
def __init__(
self,
coordinator: SensiboDataUpdateCoordinator,
device_id: str,
sensor_id: str,
sensor_data: MotionSensor,
name: str | None,
) -> None:
"""Initiate Sensibo Number."""
super().__init__(coordinator, device_id)
self._sensor_id = sensor_id
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, sensor_id)},
name=f"{self.device_data.name} Motion Sensor {name}",
via_device=(DOMAIN, device_id),
manufacturer="Sensibo",
configuration_url="https://home.sensibo.com/",
model=sensor_data.model,
sw_version=sensor_data.fw_ver,
hw_version=sensor_data.fw_type,
)
@property
def sensor_data(self) -> MotionSensor | None:
"""Return data for device."""
if TYPE_CHECKING:
assert self.device_data.motion_sensors
return self.device_data.motion_sensors[self._sensor_id]
| 34.847222 | 100 | 0.621363 |
885a8fa11069f77c5ebd9ec068d6a5e287b6ab61 | 631 | py | Python | eggs/GeneTrack-2.0.0_beta_1_dev_48da9e998f0caf01c5be731e926f4b0481f658f0-py2.7.egg/tests/testlib/pathfix.py | bopopescu/phyG | 023f505b705ab953f502cbc55e90612047867583 | [
"CC-BY-3.0"
] | null | null | null | eggs/GeneTrack-2.0.0_beta_1_dev_48da9e998f0caf01c5be731e926f4b0481f658f0-py2.7.egg/tests/testlib/pathfix.py | bopopescu/phyG | 023f505b705ab953f502cbc55e90612047867583 | [
"CC-BY-3.0"
] | null | null | null | eggs/GeneTrack-2.0.0_beta_1_dev_48da9e998f0caf01c5be731e926f4b0481f658f0-py2.7.egg/tests/testlib/pathfix.py | bopopescu/phyG | 023f505b705ab953f502cbc55e90612047867583 | [
"CC-BY-3.0"
] | 1 | 2020-07-25T21:10:26.000Z | 2020-07-25T21:10:26.000Z | """
The sole purpose of this module is to alter the sys.path upon
importing to add the current genetrack package's path first into
the import path
"""
import sys, os
def path_join(*args):
return os.path.abspath(os.path.join(*args))
curr_dir = os.path.dirname( __file__ )
test_dir = path_join(curr_dir, '..')
base_dir = path_join(curr_dir, '..', '..' )
lib_dir = path_join(base_dir, 'library')
zip_dir = path_join(lib_dir, 'library.zip')
for path in [ base_dir, lib_dir, zip_dir ]:
if path not in sys.path:
sys.path.insert(0, path )
# test that the modules in library.zip are accessible
import twill, figleaf
| 27.434783 | 65 | 0.708399 |
bbc5b5a86157bda52b3d36e9070356888ea0da2b | 8,193 | py | Python | research/object_detection/core/matcher.py | Dzinushi/models_1_4 | d7e72793a68c1667d403b1542c205d1cd9b1d17c | [
"Apache-2.0"
] | null | null | null | research/object_detection/core/matcher.py | Dzinushi/models_1_4 | d7e72793a68c1667d403b1542c205d1cd9b1d17c | [
"Apache-2.0"
] | null | null | null | research/object_detection/core/matcher.py | Dzinushi/models_1_4 | d7e72793a68c1667d403b1542c205d1cd9b1d17c | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Matcher interface and Match class.
This module defines the Matcher interface and the Match object. The job of the
matcher is to match row and column indices based on the similarity matrix and
other optional parameters. Each column is matched to at most one row. There
are three possibilities for the matching:
1) match: A column matches a row.
2) no_match: A column does not match any row.
3) ignore: A column that is neither 'match' nor no_match.
The ignore case is regularly encountered in object detection: when an anchor has
a relatively small overlap with a ground-truth box, one neither wants to
consider this box a positive example (match) nor a negative example (no match).
The Match class is used to store the match results and it provides simple apis
to query the results.
"""
from abc import ABCMeta
from abc import abstractmethod
import tensorflow as tf
class Match(object):
"""Class to store results from the matcher.
This class is used to store the results from the matcher. It provides
convenient methods to query the matching results.
"""
def __init__(self, match_results):
"""Constructs a Match object.
Args:
match_results: Integer tensor of shape [N] with (1) match_results[i]>=0,
meaning that column i is matched with row match_results[i].
(2) match_results[i]=-1, meaning that column i is not matched.
(3) match_results[i]=-2, meaning that column i is ignored.
Raises:
ValueError: if match_results does not have rank 1 or is not an
integer int32 scalar tensor
"""
if match_results.shape.ndims != 1:
raise ValueError('match_results should have rank 1')
if match_results.dtype != tf.int32:
raise ValueError('match_results should be an int32 or int64 scalar '
'tensor')
self._match_results = match_results
@property
def match_results(self):
"""The accessor for match results.
Returns:
the tensor which encodes the match results.
"""
return self._match_results
def matched_column_indices(self):
"""Returns column indices that match to some row.
The indices returned by this op are always sorted in increasing order.
Returns:
column_indices: int32 tensor of shape [K] with column indices.
"""
return self._reshape_and_cast(tf.where(tf.greater(self._match_results, -1)))
def matched_column_indicator(self):
"""Returns column indices that are matched.
Returns:
column_indices: int32 tensor of shape [K] with column indices.
"""
return tf.greater_equal(self._match_results, 0)
def num_matched_columns(self):
"""Returns number (int32 scalar tensor) of matched columns."""
return tf.size(self.matched_column_indices())
def unmatched_column_indices(self):
"""Returns column indices that do not match any row.
The indices returned by this op are always sorted in increasing order.
Returns:
column_indices: int32 tensor of shape [K] with column indices.
"""
return self._reshape_and_cast(tf.where(tf.equal(self._match_results, -1)))
def unmatched_column_indicator(self):
"""Returns column indices that are unmatched.
Returns:
column_indices: int32 tensor of shape [K] with column indices.
"""
return tf.equal(self._match_results, -1)
def num_unmatched_columns(self):
"""Returns number (int32 scalar tensor) of unmatched columns."""
return tf.size(self.unmatched_column_indices())
def ignored_column_indices(self):
"""Returns column indices that are ignored (neither Matched nor Unmatched).
The indices returned by this op are always sorted in increasing order.
Returns:
column_indices: int32 tensor of shape [K] with column indices.
"""
return self._reshape_and_cast(tf.where(self.ignored_column_indicator()))
def ignored_column_indicator(self):
"""Returns boolean column indicator where True means the colum is ignored.
Returns:
column_indicator: boolean vector which is True for all ignored column
indices.
"""
return tf.equal(self._match_results, -2)
def num_ignored_columns(self):
"""Returns number (int32 scalar tensor) of matched columns."""
return tf.size(self.ignored_column_indices())
def unmatched_or_ignored_column_indices(self):
"""Returns column indices that are unmatched or ignored.
The indices returned by this op are always sorted in increasing order.
Returns:
column_indices: int32 tensor of shape [K] with column indices.
"""
return self._reshape_and_cast(tf.where(tf.greater(0, self._match_results)))
def matched_row_indices(self):
"""Returns row indices that match some column.
The indices returned by this op are ordered so as to be in correspondence
with the output of matched_column_indicator(). For example if
self.matched_column_indicator() is [0,2], and self.matched_row_indices() is
[7, 3], then we know that column 0 was matched to row 7 and column 2 was
matched to row 3.
Returns:
row_indices: int32 tensor of shape [K] with row indices.
"""
return self._reshape_and_cast(
tf.gather(self._match_results, self.matched_column_indices()))
def _reshape_and_cast(self, t):
return tf.cast(tf.reshape(t, [-1]), tf.int32)
class Matcher(object):
"""Abstract base class for matcher.
"""
__metaclass__ = ABCMeta
def match(self, similarity_matrix, scope=None, **params):
"""Computes matches among row and column indices and returns the result.
Computes matches among the row and column indices based on the similarity
matrix and optional arguments.
Args:
similarity_matrix: Float tensor of shape [N, M] with pairwise similarity
where higher value means more similar.
scope: Op scope name. Defaults to 'Match' if None.
**params: Additional keyword arguments for specific implementations of
the Matcher.
Returns:
A Match object with the results of matching.
"""
with tf.name_scope(scope, 'Match', [similarity_matrix, params]) as scope:
return Match(self._match(similarity_matrix, **params))
@abstractmethod
def _match(self, similarity_matrix, **params):
"""Method to be overriden by implementations.
Args:
similarity_matrix: Float tensor of shape [N, M] with pairwise similarity
where higher value means more similar.
**params: Additional keyword arguments for specific implementations of
the Matcher.
Returns:
match_results: Integer tensor of shape [M]: match_results[i]>=0 means
that column i is matched to row match_results[i], match_results[i]=-1
means that the column is not matched. match_results[i]=-2 means that
the column is ignored (usually this happens when there is a very weak
match which one neither wants as positive nor negative example).
"""
pass
| 38.285047 | 84 | 0.662273 |
71ea503ef94780717eac66f10b2422d42d13f999 | 9,208 | py | Python | python/cuxfilter/charts/core/aggregate/core_aggregate_line.py | sean-frye/cuxfilter | e7291b819b01907da142f585112da66f7231d888 | [
"Apache-2.0"
] | null | null | null | python/cuxfilter/charts/core/aggregate/core_aggregate_line.py | sean-frye/cuxfilter | e7291b819b01907da142f585112da66f7231d888 | [
"Apache-2.0"
] | null | null | null | python/cuxfilter/charts/core/aggregate/core_aggregate_line.py | sean-frye/cuxfilter | e7291b819b01907da142f585112da66f7231d888 | [
"Apache-2.0"
] | null | null | null | import panel as pn
import dask_cudf
import numpy as np
from .core_aggregate import BaseAggregateChart
from ....assets.numba_kernels import calc_groupby, calc_value_counts
from ....layouts import chart_view
class BaseLine(BaseAggregateChart):
chart_type: str = "line"
reset_event = None
_datatile_loaded_state: bool = False
filter_widget = None
use_data_tiles = True
@property
def datatile_loaded_state(self):
return self._datatile_loaded_state
@datatile_loaded_state.setter
def datatile_loaded_state(self, state: bool):
self._datatile_loaded_state = state
if self.add_interaction:
if state:
self.filter_widget.bar_color = "#8ab4f7"
else:
self.filter_widget.bar_color = "#d3d9e2"
def __init__(
self,
x,
y=None,
data_points=None,
add_interaction=True,
aggregate_fn="count",
width=400,
height=400,
step_size=None,
step_size_type=int,
title="",
autoscaling=True,
**library_specific_params,
):
"""
Description:
-------------------------------------------
Input:
x
y
data_points
add_interaction
aggregate_fn
width
height
step_size
step_size_type
title
autoscaling
x_label_map
y_label_map
**library_specific_params
-------------------------------------------
Ouput:
"""
self.x = x
self.y = y
self.data_points = data_points
self.add_interaction = add_interaction
self.aggregate_fn = aggregate_fn
self.height = height
self.width = width
self.stride = step_size
self.stride_type = step_size_type
if len(title) == 0:
self.title = self.x
else:
self.title = title
self.autoscaling = autoscaling
self.library_specific_params = library_specific_params
def initiate_chart(self, dashboard_cls):
"""
Description:
-------------------------------------------
Input:
data: cudf DataFrame
-------------------------------------------
Ouput:
"""
if dashboard_cls._data[self.x].dtype == "bool":
self.min_value = 0
self.max_value = 1
self.stride = 1
# set axis labels:
dict_map = {0: "False", 1: "True"}
if len(self.x_label_map) == 0:
self.x_label_map = dict_map
if (
self.y != self.x
and self.y is not None
and len(self.y_label_map) == 0
):
self.y_label_map = dict_map
else:
if type(dashboard_cls._data) == dask_cudf.core.DataFrame:
self.min_value = dashboard_cls._data[self.x].min().compute()
self.max_value = dashboard_cls._data[self.x].max().compute()
else:
self.min_value = dashboard_cls._data[self.x].min()
self.max_value = dashboard_cls._data[self.x].max()
if self.max_value < 1 and self.stride_type == int:
self.stride_type = float
if self.stride is None and self.data_points is not None:
if self.stride_type == int:
self.stride = int(
round(
(self.max_value - self.min_value)
/ self.data_points
)
)
else:
self.stride = float(
(self.max_value - self.min_value) / self.data_points
)
self.calculate_source(dashboard_cls._data)
self.generate_chart()
self.apply_mappers()
if self.add_interaction:
self.add_range_slider_filter(dashboard_cls)
self.add_events(dashboard_cls)
def view(self):
return chart_view(self.chart, self.filter_widget, width=self.width)
def calculate_source(self, data, patch_update=False):
"""
Description:
-------------------------------------------
Input:
-------------------------------------------
Ouput:
"""
if self.y == self.x or self.y is None:
# it's a histogram
df, self.data_points, self.custom_binning = calc_value_counts(
data[self.x], self.stride, self.min_value, self.data_points
)
if self.data_points > 50_000:
print(
"number of x-values for a line chart ",
"exceeds 50,000 points.",
"Performance may be laggy, its recommended ",
"to use custom data_points parameter to ",
"enforce custom binning for smooth crossfiltering.",
"Also, checkout datashader.line for ",
"rendering millions of points.",
)
else:
self.aggregate_fn = "mean"
df = calc_groupby(self, data)
if self.data_points is None:
self.data_points = len(df[0])
if self.stride is None:
self.stride = self.stride_type(
round((self.max_value - self.min_value) / self.data_points)
)
if self.custom_binning:
if len(self.x_label_map) == 0:
temp_mapper_index = np.array(df[0])
temp_mapper_value = np.round(
(temp_mapper_index * self.stride) + self.min_value, 4,
).astype("str")
temp_mapper_index = temp_mapper_index.astype("str")
self.x_label_map = dict(
zip(temp_mapper_index, temp_mapper_value)
)
dict_temp = {
"X": list(df[0].astype(df[0].dtype)),
"Y": list(df[1].astype(df[1].dtype)),
}
self.format_source_data(dict_temp, patch_update)
def add_range_slider_filter(self, dashboard_cls):
"""
Description: add range slider to the bottom of the chart,
for the filter function to facilitate interaction
behavior, that updates the rest of the charts on the page,
using datatiles
-------------------------------------------
Input:
-------------------------------------------
Ouput:
"""
if self.stride is None:
self.stride = self.stride_type(
round((self.max_value - self.min_value) / self.data_points)
)
self.filter_widget = pn.widgets.RangeSlider(
start=self.min_value,
end=self.max_value,
value=(self.min_value, self.max_value),
step=self.stride,
**{"width": self.width},
sizing_mode="scale_width",
)
def filter_widget_callback(event):
if dashboard_cls._active_view != self.name:
dashboard_cls._reset_current_view(new_active_view=self)
dashboard_cls._calc_data_tiles()
dashboard_cls._query_datatiles_by_range(event.new)
# add callback to filter_Widget on value change
self.filter_widget.param.watch(
filter_widget_callback, ["value"], onlychanged=False
)
def compute_query_dict(self, query_str_dict):
"""
Description:
-------------------------------------------
Input:
query_dict = reference to dashboard.__cls__.query_dict
-------------------------------------------
Ouput:
"""
if self.filter_widget.value != (
self.filter_widget.start,
self.filter_widget.end,
):
min_temp, max_temp = self.filter_widget.value
query_str_dict[self.name] = (
str(self.stride_type(round(min_temp, 4)))
+ "<="
+ str(self.x)
+ "<="
+ str(self.stride_type(round(max_temp, 4)))
)
else:
query_str_dict.pop(self.name, None)
def add_events(self, dashboard_cls):
"""
Description:
-------------------------------------------
Input:
-------------------------------------------
Ouput:
"""
if self.reset_event is not None:
self.add_reset_event(dashboard_cls)
def add_reset_event(self, dashboard_cls):
"""
Description:
-------------------------------------------
Input:
-------------------------------------------
Ouput:
"""
def reset_callback(event):
self.filter_widget.value = (
self.filter_widget.start,
self.filter_widget.end,
)
# add callback to reset chart button
self.add_event(self.reset_event, reset_callback)
| 30.591362 | 78 | 0.491203 |
c3640a49d0a94a0b95e25a1ae69c8e53361e93b2 | 4,112 | py | Python | lib/python/treadmill/tests/runtime/linux/image/tar_test.py | vrautela/treadmill | 05e47fa8acdf8bad7af78e737efb26ea6488de82 | [
"Apache-2.0"
] | 1 | 2019-04-14T20:17:07.000Z | 2019-04-14T20:17:07.000Z | lib/python/treadmill/tests/runtime/linux/image/tar_test.py | vrautela/treadmill | 05e47fa8acdf8bad7af78e737efb26ea6488de82 | [
"Apache-2.0"
] | 1 | 2017-09-18T10:36:12.000Z | 2017-09-18T10:36:12.000Z | lib/python/treadmill/tests/runtime/linux/image/tar_test.py | evreng/treadmill | 05e47fa8acdf8bad7af78e737efb26ea6488de82 | [
"Apache-2.0"
] | null | null | null | """Tests for treadmill.runtime.linux.image.tar.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import shutil
import tempfile
import unittest
import io
import mock
import pkg_resources
# Disable W0611: Unused import
import treadmill.tests.treadmill_test_skip_windows # pylint: disable=W0611
import treadmill
import treadmill.services
import treadmill.subproc
import treadmill.rulefile
from treadmill import utils
from treadmill.runtime.linux.image import tar
def _test_data(name):
data_path = os.path.join('data', name)
with pkg_resources.resource_stream(__name__, data_path) as f:
return f.read()
class TarImageTest(unittest.TestCase):
"""Tests for treadmill.runtime.linux.image.tar."""
def setUp(self):
# Access protected module _base_service
# pylint: disable=W0212
self.container_dir = tempfile.mkdtemp()
self.root = tempfile.mkdtemp(dir=self.container_dir)
self.tmp_dir = tempfile.mkdtemp()
self.images_dir = tempfile.mkdtemp()
self.tm_env = mock.Mock(
root=self.root,
images_dir=self.images_dir,
svc_cgroup=mock.Mock(
spec_set=treadmill.services._base_service.ResourceService,
),
svc_localdisk=mock.Mock(
spec_set=treadmill.services._base_service.ResourceService,
),
svc_network=mock.Mock(
spec_set=treadmill.services._base_service.ResourceService,
),
rules=mock.Mock(
spec_set=treadmill.rulefile.RuleMgr,
),
)
self.app = utils.to_obj(
{
'type': 'native',
'proid': 'myproid',
'name': 'myproid.test#0',
'uniqueid': 'ID1234',
'environment': 'dev',
'disk': '100G',
'endpoints': [
{
'name': 'ssh',
'port': 47299,
'proto': 'tcp',
'real_port': 47299,
'type': 'infra'
}
],
'shared_network': False,
'ephemeral_ports': {
'tcp': 0,
'udp': 0
}
}
)
def tearDown(self):
if self.container_dir and os.path.isdir(self.container_dir):
shutil.rmtree(self.container_dir)
if self.images_dir and os.path.isdir(self.images_dir):
shutil.rmtree(self.images_dir)
if self.tmp_dir and os.path.isdir(self.tmp_dir):
shutil.rmtree(self.tmp_dir)
@mock.patch('treadmill.runtime.linux.image.native.NativeImage',
mock.Mock())
def test_get_tar_sha256_unpack(self):
"""Validates getting a test tar file with a sha256 hash_code."""
with io.open(os.path.join(self.tmp_dir, 'sleep.tar'), 'wb') as f:
f.write(_test_data('sleep.tar'))
repo = tar.TarImageRepository(self.tm_env)
img = repo.get(
'file://{0}/sleep.tar?sha256={1}'.format(
self.tmp_dir,
'5a0f99c73b03f7f17a9e03b20816c2931784d5e1fc574eb2d0dece57'
'f509e520'
)
)
self.assertIsNotNone(img)
img.unpack(self.container_dir, self.root, self.app)
def test_get_tar__invalid_sha256(self):
"""Validates getting a test tar file with an invalid sha256 hash_code.
"""
with io.open(os.path.join(self.tmp_dir, 'sleep.tar'), 'wb') as f:
f.write(_test_data('sleep.tar'))
repo = tar.TarImageRepository(self.tm_env)
with self.assertRaises(Exception):
repo.get(
'file://{0}/sleep.tar?sha256={1}'.format(
self.tmp_dir,
'this_is_an_invalid_sha256'
)
)
if __name__ == '__main__':
unittest.main()
| 30.235294 | 78 | 0.567121 |
0408f4a162e4444d83d383829f3e38c6d750647d | 91 | py | Python | tutos/tutorias/apps.py | UVG-Teams/Tutos-System | 230dd9434f745c2e6e69e10f9908e9818c559d03 | [
"MIT"
] | null | null | null | tutos/tutorias/apps.py | UVG-Teams/Tutos-System | 230dd9434f745c2e6e69e10f9908e9818c559d03 | [
"MIT"
] | null | null | null | tutos/tutorias/apps.py | UVG-Teams/Tutos-System | 230dd9434f745c2e6e69e10f9908e9818c559d03 | [
"MIT"
] | null | null | null | from django.apps import AppConfig
class TutoriasConfig(AppConfig):
name = 'tutorias'
| 15.166667 | 33 | 0.758242 |
096815c95bb691d81eff8dc70b3a14b7b63e0a5b | 11,757 | py | Python | cogs/info.py | CaseyK9/Scarecrow | c85d4f63f4c3a2fdfb0bf12d684adc4ef71508a8 | [
"MIT"
] | 12 | 2017-02-09T21:11:46.000Z | 2020-02-12T18:27:36.000Z | cogs/info.py | CaseyK9/Scarecrow | c85d4f63f4c3a2fdfb0bf12d684adc4ef71508a8 | [
"MIT"
] | 8 | 2017-06-26T14:39:18.000Z | 2020-04-22T23:15:40.000Z | cogs/info.py | CaseyK9/Scarecrow | c85d4f63f4c3a2fdfb0bf12d684adc4ef71508a8 | [
"MIT"
] | 19 | 2017-07-01T00:24:16.000Z | 2020-11-25T15:06:07.000Z | import collections
import subprocess
import time
import unicodedata
import psutil
import discord
import discord.ext.commands as commands
from utils import utils
def setup(bot):
bot.add_cog(Info(bot))
psutil.cpu_percent() # Initialise the first interval
class Info(commands.Cog):
"""When your curiosity takes over."""
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=['charinfos'])
async def charinfo(self, ctx, *, data: str):
"""Shows information about one or several characters.
'data' can either be a character, a unicode escape sequence, a unicode character name or a string.
If 'data' is a string only a summary of each character's info will be displayed.
"""
data = data.lower()
if data.startswith('\\u'):
# Let's interpret the unicode escape sequence
hex_values = data.split('\\u')[1:]
try:
code_points = [int(val, 16) for val in hex_values]
except ValueError:
raise commands.BadArgument('Invalid unicode escape sequence.')
else:
data = ''.join(chr(cp) for cp in code_points)
elif len(data) > 1:
# Maybe we've been given the character's name ?
try:
data = unicodedata.lookup(data)
except KeyError:
pass
# Normalise the input
data = unicodedata.normalize('NFC', data)
url_fmt = '<http://unicode-table.com/en/{:X}>'
if len(data) == 1:
# Detailed info on the character
entries = [
('Character', data),
('Name', unicodedata.name(data, 'None')),
('Code point', f'{ord(data):04x}')
]
decomposition = unicodedata.decomposition(data)
if decomposition != '':
entries.append(('Decomposition', decomposition))
combining = unicodedata.combining(data)
if combining:
entries.append(('Combining class', combining))
entries.append(('Category', unicodedata.category(data)))
bidirectional = unicodedata.bidirectional(data)
entries.append(('Bidirectional', bidirectional if bidirectional != '' else 'None'))
entries.append(('Mirrored', 'True' if unicodedata.mirrored(data) == 1 else 'False'))
entries.append(('East asian width', unicodedata.east_asian_width(data)))
entries.append(('Url', url_fmt.format(ord(data))))
# Create the message's content and send it
content = utils.indented_entry_to_str(entries)
await ctx.send(utils.format_block(content))
else:
# Minimal info for each character
entries = [f'`\N{ZERO WIDTH SPACE}{c}\N{ZERO WIDTH SPACE}` | `\\u{ord(c):04x}` | `{unicodedata.name(c, "None")}` | {url_fmt.format(ord(c))}' for c in data]
content = '\n'.join(entries)
await ctx.send(content)
@commands.group(name='info', aliases=['infos'], invoke_without_command=True)
async def info_group(self, ctx):
"""Shows information about the bot."""
unique_members = set()
members_count = 0
for member in ctx.bot.get_all_members():
members_count += 1
unique_members.add(member.id)
unique_members_count = len(unique_members)
members_str = f'{members_count} ({unique_members_count} unique)'
owner = (ctx.guild.get_member(ctx.bot.owner.id) if ctx.guild else None) or ctx.bot.owner
prefixes = ctx.bot.command_prefix(ctx.bot, ctx.message)
prefixes.remove(f'{ctx.me.mention.replace("@", "@!")} ')
prefixes[prefixes.index(f'{ctx.me.mention} ')] = f'@\u200b{ctx.me.display_name} '
# Get cpu, memory and uptime
proc = psutil.Process()
mem_info = proc.memory_full_info()
mem_str = f'{mem_info.uss / 1048576:.2f} Mb' # Expressed in bytes, turn to Mb and round to 2 decimals
cpu_str = f'{psutil.cpu_percent()}%'
uptime = round(time.time() - self.bot.start_time)
uptime_str = utils.duration_to_str(uptime)
# Create the bot invite link with the following permissions :
# * Read Messages
# * Send Messages
# * Manage Messages
# * Embed Links
# * Read Message History
# * Use External Emojis
# * Add Reactions
perms = discord.Permissions(486464)
invite = discord.utils.oauth_url(ctx.bot.app_info.id, perms)
latest_commits = subprocess.check_output(
['git', 'log', '--pretty=format:[`%h`](https://github.com/PapyrusThePlant/Scarecrow/commit/%h) %s', '-n', '5']).decode('utf-8')
embed = discord.Embed(description=f'[Click here to invite me to your server !]({invite})', colour=discord.Colour.blurple())
embed.set_thumbnail(url=ctx.me.avatar_url)
embed.set_author(name=f'Author : {owner}', icon_url=owner.avatar_url)
embed.add_field(name='Command prefixes', value="`" + "`, `".join(prefixes) + "`")
embed.add_field(name='Servers', value=len(ctx.bot.guilds))
embed.add_field(name='Members', value=members_str)
embed.add_field(name='CPU', value=cpu_str)
embed.add_field(name='Memory', value=mem_str)
embed.add_field(name='Uptime', value=uptime_str)
embed.add_field(name='Latest changes', value=latest_commits, inline=False)
embed.add_field(name='\N{ZERO WIDTH SPACE}', value='For any question about the bot, announcements and an easy way to get in touch with me, feel free to join the dedicated [discord server](https://discord.gg/M85dw9u).')
embed.set_footer(text='Powered by discord.py', icon_url='http://i.imgur.com/5BFecvA.png')
await ctx.send(embed=embed)
@info_group.command(name='channel')
@commands.guild_only()
async def info_channel(self, ctx, *, channel: utils.GuildChannelConverter = None):
"""Shows information about the channel.
The channel can either be the name, the mention or the ID of a text or voice channel.
If no channel is given, the text channel this command was used in is selected.
"""
if channel is None:
channel = ctx.channel
embed = discord.Embed(description=channel.mention, colour=discord.Colour.blurple())
embed.add_field(name='ID', value=channel.id)
embed.add_field(name='Server', value=channel.guild.name)
embed.add_field(name='Type', value='Text channel' if isinstance(channel, discord.TextChannel) else 'Voice channel')
embed.add_field(name='Position', value=f'#{channel.position + 1}')
if isinstance(channel, discord.VoiceChannel):
embed.add_field(name='Bitrate', value=str(channel.bitrate))
embed.add_field(name='Members', value=str(len(channel.members)))
embed.add_field(name='User limit', value=str(channel.user_limit) if channel.user_limit > 0 else 'None')
await ctx.send(embed=embed)
@info_group.command(name='guild', aliases=['server'])
@commands.guild_only()
async def info_guild(self, ctx):
"""Shows information about the server."""
guild = ctx.guild
# List the roles other than @everyone
roles = ', '.join(guild.roles[i].name for i in range(1, len(guild.roles)))
# List the guild's features
features = ', '.join(feature.replace('_', ' ').capitalize() for feature in guild.features) or 'None'
# Figure out how many channels are locked
locked_text = 0
locked_voice = 0
for channel in guild.channels:
overwrites = channel.overwrites_for(guild.default_role)
if isinstance(channel, discord.TextChannel):
if overwrites.read_messages is False:
locked_text += 1
elif overwrites.connect is False or overwrites.speak is False:
locked_voice += 1
# Count the channels
channels = f'Text : {len(guild.text_channels)} ({locked_text} locked)\n' \
f'Voice : {len(guild.voice_channels)} ({locked_voice} locked)'
# Count the members
members_by_status = collections.Counter(f'{m.status}{"_bot" if m.bot else ""}' for m in guild.members)
members_by_status['online'] += members_by_status['online_bot']
members_by_status['idle'] += members_by_status['idle_bot']
members_by_status['offline'] += members_by_status['offline_bot']
members_fmt = 'Total : {0}\n' \
'Online : {1[online]} ({1[online_bot]} bots)\n' \
'Idle : {1[idle]} ({1[idle_bot]} bots)\n' \
'Offline : {1[offline]} ({1[offline_bot]} bots)'
members = members_fmt.format(len(guild.members), members_by_status)
# Gather the valid and permanent invites if we have permission to do so
invite = None
perms = guild.text_channels[0].permissions_for(guild.me)
if perms.manage_guild:
# Get only permanent and valid invites
invites = await guild.invites()
invites = [inv for inv in invites if not inv.revoked and inv.max_age == 0]
if invites:
# Get the invite with the most uses
invites.sort(key=lambda inv: inv.uses, reverse=True)
invite = invites[0]
# Create and fill the embed
if invite is not None:
embed = discord.Embed(title='Server invite', url=invite.url, colour=discord.Colour.blurple())
else:
embed = discord.Embed(colour=discord.Colour.blurple())
embed.set_author(name=guild.name, url=guild.icon_url, icon_url=guild.icon_url)
embed.add_field(name='ID', value=guild.id)
embed.add_field(name='Owner', value=str(guild.owner))
embed.add_field(name='Region', value=guild.region.value.title())
embed.add_field(name='Members', value=members)
embed.add_field(name='Channels', value=channels)
embed.add_field(name='Features', value=features)
embed.add_field(name='Roles', value=roles)
embed.set_footer(text='Server created the ')
embed.timestamp = guild.created_at
await ctx.send(embed=embed)
@info_group.command(name='user')
@commands.guild_only()
async def info_user(self, ctx, *, member: discord.Member):
"""Shows information about a user.
The given member can either be found by ID, nickname or username.
If no member is given, your info will be displayed.
"""
if member is None:
member = ctx.author
roles = ', '.join(role.name.replace('@', '@\u200b') for role in member.roles)
shared = sum(1 for m in ctx.bot.get_all_members() if m.id == member.id)
if member.voice:
vc = member.voice.channel
other_people = len(vc.members) - 1
voice = f'{vc.name}, {f"with {other_people} others" if other_people else "by themselves"}'
else:
voice = 'Not connected.'
embed = discord.Embed(title=member.display_name, colour=discord.Colour.blurple())
embed.set_author(name=str(member))
embed.set_thumbnail(url=member.avatar_url)
embed.add_field(name='ID', value=member.id)
embed.add_field(name='Servers', value=f'{shared} shared')
embed.add_field(name='Joined', value=member.joined_at)
embed.add_field(name='Roles', value=roles)
embed.add_field(name='Voice', value=voice)
embed.set_footer(text='User created the ')
embed.timestamp = member.created_at
await ctx.send(embed=embed)
| 45.045977 | 226 | 0.619716 |
f2e77c960f69036622558b16895b08494aad4411 | 1,388 | py | Python | search/index.py | smartdatalake/danae | d3caf14e86f416586046aa9050ca5673356dde6d | [
"Apache-2.0"
] | null | null | null | search/index.py | smartdatalake/danae | d3caf14e86f416586046aa9050ca5673356dde6d | [
"Apache-2.0"
] | null | null | null | search/index.py | smartdatalake/danae | d3caf14e86f416586046aa9050ca5673356dde6d | [
"Apache-2.0"
] | null | null | null | from rtree import index
from bidict import bidict
class RTree:
def __init__(self, name, no, flat=False):
idx_properties = index.Property()
idx_properties.dimension = no
idx_properties.overwrite = False
self.idx = index.Index('idx/index_{}_{}'.format(name, no), properties=idx_properties)
self.d = bidict()
self.flat = flat
self.inv = {}
def insert(self, key, val):
self.d[key] = len(self.d)
data, col = key.split(";", 1)
if data not in self.inv:
self.inv[data] = {}
self.inv[data][col] = val
#obj = [val[0], 0, val[1], 0] if self.flat else val + val
obj = val if self.flat else val + val
self.idx.insert(self.d[key], obj)
#def nearests(self, X, k):
# return [self.nearest(x, k) for x in X]
def get_columns(self, S):
if S in self.inv:
return self.inv[S]
def nearest(self, x, k, objects=False):
#obj = [x[0], 0, x[1], 0] if self.flat else x*2
obj = x if self.flat else x*2
if objects:
return [(self.d.inv[r.id], r.bbox) for r in self.idx.nearest(obj, k, objects)]
else:
return [self.d.inv[r] for r in self.idx.nearest(obj, k)]
def save_model(self, path):
self.idx.close() | 30.173913 | 93 | 0.528818 |
1d24026e90d7c564f65e9ca5a5a1055d9b13c86e | 4,585 | py | Python | tests/py/test_multi_gpu.py | svenchilton/Torch-TensorRT | 95d2b6e003a0392fe08ce49520f015c230d4c750 | [
"BSD-3-Clause"
] | 430 | 2021-11-09T08:08:01.000Z | 2022-03-31T10:13:45.000Z | tests/py/test_multi_gpu.py | svenchilton/Torch-TensorRT | 95d2b6e003a0392fe08ce49520f015c230d4c750 | [
"BSD-3-Clause"
] | 257 | 2021-11-09T07:17:03.000Z | 2022-03-31T20:29:31.000Z | tests/py/test_multi_gpu.py | svenchilton/Torch-TensorRT | 95d2b6e003a0392fe08ce49520f015c230d4c750 | [
"BSD-3-Clause"
] | 68 | 2021-11-10T05:03:22.000Z | 2022-03-22T17:07:32.000Z | import unittest
import torch_tensorrt as torchtrt
import torch
import torchvision.models as models
from model_test_case import ModelTestCase
class TestMultiGpuSwitching(ModelTestCase):
def setUp(self):
if torch.cuda.device_count() < 2:
self.fail("Test is not relevant for this platform since number of available CUDA devices is less than 2")
torchtrt.set_device(0)
self.target_gpu = 1
self.input = torch.randn((1, 3, 224, 224)).to("cuda:1")
self.model = self.model.to("cuda:1")
self.traced_model = torch.jit.trace(self.model, [self.input])
self.scripted_model = torch.jit.script(self.model)
def test_compile_traced(self):
torchtrt.set_device(0)
compile_spec = {
"inputs": [torchtrt.Input(self.input.shape)],
"device": {
"device_type": torchtrt.DeviceType.GPU,
"gpu_id": self.target_gpu,
"dla_core": 0,
"allow_gpu_fallback": False,
"disable_tf32": False
}
}
trt_mod = torchtrt.ts.compile(self.traced_model, **compile_spec)
torchtrt.set_device(self.target_gpu)
same = (trt_mod(self.input) - self.traced_model(self.input)).abs().max()
torchtrt.set_device(0)
self.assertTrue(same < 2e-3)
def test_compile_script(self):
torchtrt.set_device(0)
compile_spec = {
"inputs": [torchtrt.Input(self.input.shape)],
"device": {
"device_type": torchtrt.DeviceType.GPU,
"gpu_id": self.target_gpu,
"dla_core": 0,
"allow_gpu_fallback": False,
"disable_tf32": False
}
}
trt_mod = torchtrt.ts.compile(self.scripted_model, **compile_spec)
torchtrt.set_device(self.target_gpu)
same = (trt_mod(self.input) - self.scripted_model(self.input)).abs().max()
torchtrt.set_device(0)
self.assertTrue(same < 2e-3)
class TestMultiGpuSerializeDeserializeSwitching(ModelTestCase):
def setUp(self):
if torch.cuda.device_count() < 2:
self.fail("Test is not relevant for this platform since number of available CUDA devices is less than 2")
self.target_gpu = 0
torchtrt.set_device(0)
self.input = torch.randn((1, 3, 224, 224)).to("cuda:0")
self.model = self.model.to("cuda:0")
self.traced_model = torch.jit.trace(self.model, [self.input])
self.scripted_model = torch.jit.script(self.model)
def test_compile_traced(self):
torchtrt.set_device(0)
compile_spec = {
"inputs": [torchtrt.Input(self.input.shape)],
"device": {
"device_type": torchtrt.DeviceType.GPU,
"gpu_id": self.target_gpu,
"dla_core": 0,
"allow_gpu_fallback": False,
"disable_tf32": False
}
}
trt_mod = torchtrt.ts.compile(self.traced_model, **compile_spec)
# Changing the device ID deliberately. It should still run on correct device ID by context switching
torchtrt.set_device(1)
same = (trt_mod(self.input) - self.traced_model(self.input)).abs().max()
self.assertTrue(same < 2e-3)
def test_compile_script(self):
torchtrt.set_device(0)
compile_spec = {
"inputs": [torchtrt.Input(self.input.shape)],
"device": {
"device_type": torchtrt.DeviceType.GPU,
"gpu_id": self.target_gpu,
"dla_core": 0,
"allow_gpu_fallback": False,
"disable_tf32": False
}
}
trt_mod = torchtrt.ts.compile(self.scripted_model, **compile_spec)
# Changing the device ID deliberately. It should still run on correct device ID by context switching
torchtrt.set_device(1)
same = (trt_mod(self.input) - self.scripted_model(self.input)).abs().max()
self.assertTrue(same < 2e-3)
def test_suite():
suite = unittest.TestSuite()
suite.addTest(TestMultiGpuSwitching.parametrize(TestMultiGpuSwitching, model=models.resnet18(pretrained=True)))
suite.addTest(
TestMultiGpuSerializeDeserializeSwitching.parametrize(TestMultiGpuSwitching,
model=models.resnet18(pretrained=True)))
return suite
suite = test_suite()
runner = unittest.TextTestRunner()
result = runner.run(suite)
exit(int(not result.wasSuccessful()))
| 35.542636 | 117 | 0.605016 |
c5c59e9958ddb98960d053024a68e491b57c520e | 7,480 | py | Python | adafruit_veml7700.py | BrianPugh/Adafruit_CircuitPython_VEML7700 | 8f2f24e811c1b723e2a4a02933a36acf3bd27998 | [
"Unlicense",
"MIT-0",
"MIT"
] | null | null | null | adafruit_veml7700.py | BrianPugh/Adafruit_CircuitPython_VEML7700 | 8f2f24e811c1b723e2a4a02933a36acf3bd27998 | [
"Unlicense",
"MIT-0",
"MIT"
] | null | null | null | adafruit_veml7700.py | BrianPugh/Adafruit_CircuitPython_VEML7700 | 8f2f24e811c1b723e2a4a02933a36acf3bd27998 | [
"Unlicense",
"MIT-0",
"MIT"
] | null | null | null | # SPDX-FileCopyrightText: 2019 Kattni Rembor for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_veml7700`
================================================================================
CircuitPython driver for VEML7700 high precision I2C ambient light sensor.
* Author(s): Kattni Rembor
Implementation Notes
--------------------
**Hardware:**
* `Adafruit VEML7700 <https://www.adafruit.com/products>`_
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
* Adafruit's Register library: https://github.com/adafruit/Adafruit_CircuitPython_Register
"""
from micropython import const
import adafruit_bus_device.i2c_device as i2cdevice
from adafruit_register.i2c_struct import UnaryStruct, ROUnaryStruct
from adafruit_register.i2c_bits import RWBits
from adafruit_register.i2c_bit import RWBit, ROBit
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_VEML7700.git"
class VEML7700:
"""Driver for the VEML7700 ambient light sensor.
:param busio.I2C i2c_bus: The I2C bus the VEML7700 is connected to.
"""
# Ambient light sensor gain settings
ALS_GAIN_1 = const(0x0)
ALS_GAIN_2 = const(0x1)
ALS_GAIN_1_8 = const(0x2)
ALS_GAIN_1_4 = const(0x3)
# Ambient light integration time settings
ALS_25MS = const(0xC)
ALS_50MS = const(0x8)
ALS_100MS = const(0x0)
ALS_200MS = const(0x1)
ALS_400MS = const(0x2)
ALS_800MS = const(0x3)
# Gain value integers
gain_values = {
ALS_GAIN_2: 2,
ALS_GAIN_1: 1,
ALS_GAIN_1_4: 0.25,
ALS_GAIN_1_8: 0.125,
}
# Integration time value integers
integration_time_values = {
ALS_25MS: 25,
ALS_50MS: 50,
ALS_100MS: 100,
ALS_200MS: 200,
ALS_400MS: 400,
ALS_800MS: 800,
}
# ALS - Ambient light sensor high resolution output data
light = ROUnaryStruct(0x04, "<H")
"""Ambient light data.
This example prints the ambient light data. Cover the sensor to see the values change.
.. code-block:: python
import time
import board
import busio
import adafruit_veml7700
i2c = busio.I2C(board.SCL, board.SDA)
veml7700 = adafruit_veml7700.VEML7700(i2c)
while True:
print("Ambient light:", veml7700.light)
time.sleep(0.1)
"""
# WHITE - White channel output data
white = ROUnaryStruct(0x05, "<H")
"""White light data.
This example prints the white light data. Cover the sensor to see the values change.
.. code-block:: python
import time
import board
import busio
import adafruit_veml7700
i2c = busio.I2C(board.SCL, board.SDA)
veml7700 = adafruit_veml7700.VEML7700(i2c)
while True:
print("White light:", veml7700.white)
time.sleep(0.1)
"""
# ALS_CONF_0 - ALS gain, integration time, interrupt and shutdown.
light_shutdown = RWBit(0x00, 0, register_width=2)
"""Ambient light sensor shutdown. When ``True``, ambient light sensor is disabled."""
light_interrupt = RWBit(0x00, 1, register_width=2)
"""Enable interrupt. ``True`` to enable, ``False`` to disable."""
light_gain = RWBits(2, 0x00, 11, register_width=2)
"""Ambient light gain setting. Gain settings are 2, 1, 1/4 and 1/8. Settings options are:
ALS_GAIN_2, ALS_GAIN_1, ALS_GAIN_1_4, ALS_GAIN_1_8.
This example sets the ambient light gain to 2 and prints the ambient light sensor data.
.. code-block:: python
import time
import board
import busio
import adafruit_veml7700
i2c = busio.I2C(board.SCL, board.SDA)
veml7700 = adafruit_vcnl4040.VCNL4040(i2c)
veml7700.light_gain = veml7700.ALS_GAIN_2
while True:
print("Ambient light:", veml7700.light)
time.sleep(0.1)
"""
light_integration_time = RWBits(4, 0x00, 6, register_width=2)
"""Ambient light integration time setting. Longer time has higher sensitivity. Can be:
ALS_25MS, ALS_50MS, ALS_100MS, ALS_200MS, ALS_400MS, ALS_800MS.
This example sets the ambient light integration time to 400ms and prints the ambient light
sensor data.
.. code-block:: python
import time
import board
import busio
import adafruit_veml7700
i2c = busio.I2C(board.SCL, board.SDA)
veml7700 = adafruit_vcnl4040.VCNL4040(i2c)
veml7700.light_integration_time = veml7700.ALS_400MS
while True:
print("Ambient light:", veml7700.light)
time.sleep(0.1)
"""
# ALS_WH - ALS high threshold window setting
light_high_threshold = UnaryStruct(0x01, "<H")
"""Ambient light sensor interrupt high threshold setting."""
# ALS_WL - ALS low threshold window setting
light_low_threshold = UnaryStruct(0x02, "<H")
"""Ambient light sensor interrupt low threshold setting."""
# ALS_INT - ALS INT trigger event
light_interrupt_high = ROBit(0x06, 14, register_width=2)
"""Ambient light high threshold interrupt flag. Triggered when high threshold exceeded."""
light_interrupt_low = ROBit(0x06, 15, register_width=2)
"""Ambient light low threshold interrupt flag. Triggered when low threshold exceeded."""
def __init__(self, i2c_bus, address=0x10):
self.i2c_device = i2cdevice.I2CDevice(i2c_bus, address)
for _ in range(3):
try:
self.light_shutdown = False # Enable the ambient light sensor
break
except OSError:
pass
else:
raise RuntimeError("Unable to enable VEML7700 device")
def integration_time_value(self):
"""Integration time value in integer form. Used for calculating ``resolution``."""
integration_time = self.light_integration_time
return self.integration_time_values[integration_time]
def gain_value(self):
"""Gain value in integer form. Used for calculating ``resolution``."""
gain = self.light_gain
return self.gain_values[gain]
def resolution(self):
"""Calculate the ``resolution`` necessary to calculate lux. Based on integration time and
gain settings."""
resolution_at_max = 0.0036
gain_max = 2
integration_time_max = 800
if (
self.gain_value() == gain_max
and self.integration_time_value() == integration_time_max
):
return resolution_at_max
return (
resolution_at_max
* (integration_time_max / self.integration_time_value())
* (gain_max / self.gain_value())
)
@property
def lux(self):
"""Light value in lux.
This example prints the light data in lux. Cover the sensor to see the values change.
.. code-block:: python
import time
import board
import busio
import adafruit_veml7700
i2c = busio.I2C(board.SCL, board.SDA)
veml7700 = adafruit_veml7700.VEML7700(i2c)
while True:
print("Lux:", veml7700.lux)
time.sleep(0.1)
"""
return self.resolution() * self.light
| 30.283401 | 97 | 0.643984 |
fb26138eed941201dc7fa7b2c8d77fc28c0bdefc | 11,180 | py | Python | tests/regressiontests/transactions_regress/tests.py | graingert/django | 784d0c261c76535dc760bc8d76793d92f35c1513 | [
"BSD-3-Clause"
] | null | null | null | tests/regressiontests/transactions_regress/tests.py | graingert/django | 784d0c261c76535dc760bc8d76793d92f35c1513 | [
"BSD-3-Clause"
] | null | null | null | tests/regressiontests/transactions_regress/tests.py | graingert/django | 784d0c261c76535dc760bc8d76793d92f35c1513 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import absolute_import
from django.core.exceptions import ImproperlyConfigured
from django.db import connection, connections, transaction, DEFAULT_DB_ALIAS
from django.db.transaction import commit_on_success, commit_manually, TransactionManagementError
from django.test import TransactionTestCase, skipUnlessDBFeature
from django.test.utils import override_settings
from django.utils.unittest import skipIf, skipUnless
from .models import Mod, M2mA, M2mB
class TestTransactionClosing(TransactionTestCase):
"""
Tests to make sure that transactions are properly closed
when they should be, and aren't left pending after operations
have been performed in them. Refs #9964.
"""
def test_raw_committed_on_success(self):
"""
Make sure a transaction consisting of raw SQL execution gets
committed by the commit_on_success decorator.
"""
@commit_on_success
def raw_sql():
"Write a record using raw sql under a commit_on_success decorator"
cursor = connection.cursor()
cursor.execute("INSERT into transactions_regress_mod (id,fld) values (17,18)")
raw_sql()
# Rollback so that if the decorator didn't commit, the record is unwritten
transaction.rollback()
try:
# Check that the record is in the DB
obj = Mod.objects.get(pk=17)
self.assertEqual(obj.fld, 18)
except Mod.DoesNotExist:
self.fail("transaction with raw sql not committed")
def test_commit_manually_enforced(self):
"""
Make sure that under commit_manually, even "read-only" transaction require closure
(commit or rollback), and a transaction left pending is treated as an error.
"""
@commit_manually
def non_comitter():
"Execute a managed transaction with read-only operations and fail to commit"
_ = Mod.objects.count()
self.assertRaises(TransactionManagementError, non_comitter)
def test_commit_manually_commit_ok(self):
"""
Test that under commit_manually, a committed transaction is accepted by the transaction
management mechanisms
"""
@commit_manually
def committer():
"""
Perform a database query, then commit the transaction
"""
_ = Mod.objects.count()
transaction.commit()
try:
committer()
except TransactionManagementError:
self.fail("Commit did not clear the transaction state")
def test_commit_manually_rollback_ok(self):
"""
Test that under commit_manually, a rolled-back transaction is accepted by the transaction
management mechanisms
"""
@commit_manually
def roller_back():
"""
Perform a database query, then rollback the transaction
"""
_ = Mod.objects.count()
transaction.rollback()
try:
roller_back()
except TransactionManagementError:
self.fail("Rollback did not clear the transaction state")
def test_commit_manually_enforced_after_commit(self):
"""
Test that under commit_manually, if a transaction is committed and an operation is
performed later, we still require the new transaction to be closed
"""
@commit_manually
def fake_committer():
"Query, commit, then query again, leaving with a pending transaction"
_ = Mod.objects.count()
transaction.commit()
_ = Mod.objects.count()
self.assertRaises(TransactionManagementError, fake_committer)
@skipUnlessDBFeature('supports_transactions')
def test_reuse_cursor_reference(self):
"""
Make sure transaction closure is enforced even when the queries are performed
through a single cursor reference retrieved in the beginning
(this is to show why it is wrong to set the transaction dirty only when a cursor
is fetched from the connection).
"""
@commit_on_success
def reuse_cursor_ref():
"""
Fetch a cursor, perform an query, rollback to close the transaction,
then write a record (in a new transaction) using the same cursor object
(reference). All this under commit_on_success, so the second insert should
be committed.
"""
cursor = connection.cursor()
cursor.execute("INSERT into transactions_regress_mod (id,fld) values (1,2)")
transaction.rollback()
cursor.execute("INSERT into transactions_regress_mod (id,fld) values (1,2)")
reuse_cursor_ref()
# Rollback so that if the decorator didn't commit, the record is unwritten
transaction.rollback()
try:
# Check that the record is in the DB
obj = Mod.objects.get(pk=1)
self.assertEqual(obj.fld, 2)
except Mod.DoesNotExist:
self.fail("After ending a transaction, cursor use no longer sets dirty")
def test_failing_query_transaction_closed(self):
"""
Make sure that under commit_on_success, a transaction is rolled back even if
the first database-modifying operation fails.
This is prompted by http://code.djangoproject.com/ticket/6669 (and based on sample
code posted there to exemplify the problem): Before Django 1.3,
transactions were only marked "dirty" by the save() function after it successfully
wrote the object to the database.
"""
from django.contrib.auth.models import User
@transaction.commit_on_success
def create_system_user():
"Create a user in a transaction"
user = User.objects.create_user(username='system', password='iamr00t', email='root@SITENAME.com')
# Redundant, just makes sure the user id was read back from DB
Mod.objects.create(fld=user.id)
# Create a user
create_system_user()
try:
# The second call to create_system_user should fail for violating a unique constraint
# (it's trying to re-create the same user)
create_system_user()
except:
pass
else:
raise ImproperlyConfigured('Unique constraint not enforced on django.contrib.auth.models.User')
try:
# Try to read the database. If the last transaction was indeed closed,
# this should cause no problems
_ = User.objects.all()[0]
except:
self.fail("A transaction consisting of a failed operation was not closed.")
@override_settings(DEBUG=True)
def test_failing_query_transaction_closed_debug(self):
"""
Regression for #6669. Same test as above, with DEBUG=True.
"""
self.test_failing_query_transaction_closed()
class TestPostgresAutocommit(TransactionTestCase):
"""
Tests to make sure psycopg2's autocommit mode is restored after entering
and leaving transaction management. Refs #16047.
"""
def setUp(self):
from psycopg2.extensions import (ISOLATION_LEVEL_AUTOCOMMIT,
ISOLATION_LEVEL_READ_COMMITTED)
self._autocommit = ISOLATION_LEVEL_AUTOCOMMIT
self._read_committed = ISOLATION_LEVEL_READ_COMMITTED
# We want a clean backend with autocommit = True, so
# first we need to do a bit of work to have that.
self._old_backend = connections[DEFAULT_DB_ALIAS]
settings = self._old_backend.settings_dict.copy()
opts = settings['OPTIONS'].copy()
opts['autocommit'] = True
settings['OPTIONS'] = opts
new_backend = self._old_backend.__class__(settings, DEFAULT_DB_ALIAS)
connections[DEFAULT_DB_ALIAS] = new_backend
def test_initial_autocommit_state(self):
self.assertTrue(connection.features.uses_autocommit)
self.assertEqual(connection.isolation_level, self._autocommit)
def test_transaction_management(self):
transaction.enter_transaction_management()
transaction.managed(True)
self.assertEqual(connection.isolation_level, self._read_committed)
transaction.leave_transaction_management()
self.assertEqual(connection.isolation_level, self._autocommit)
def test_transaction_stacking(self):
transaction.enter_transaction_management()
transaction.managed(True)
self.assertEqual(connection.isolation_level, self._read_committed)
transaction.enter_transaction_management()
self.assertEqual(connection.isolation_level, self._read_committed)
transaction.leave_transaction_management()
self.assertEqual(connection.isolation_level, self._read_committed)
transaction.leave_transaction_management()
self.assertEqual(connection.isolation_level, self._autocommit)
def tearDown(self):
connections[DEFAULT_DB_ALIAS] = self._old_backend
TestPostgresAutocommit = skipUnless(connection.vendor == 'postgresql',
"This test only valid for PostgreSQL")(TestPostgresAutocommit)
TestPostgresAutoCommit = skipUnlessDBFeature('supports_transactions')(
TestPostgresAutocommit)
class TestManyToManyAddTransaction(TransactionTestCase):
def test_manyrelated_add_commit(self):
"Test for https://code.djangoproject.com/ticket/16818"
a = M2mA.objects.create()
b = M2mB.objects.create(fld=10)
a.others.add(b)
# We're in a TransactionTestCase and have not changed transaction
# behavior from default of "autocommit", so this rollback should not
# actually do anything. If it does in fact undo our add, that's a bug
# that the bulk insert was not auto-committed.
transaction.rollback()
self.assertEqual(a.others.count(), 1)
class SavepointTest(TransactionTestCase):
@skipUnlessDBFeature('uses_savepoints')
def test_savepoint_commit(self):
@commit_manually
def work():
mod = Mod.objects.create(fld=1)
pk = mod.pk
sid = transaction.savepoint()
mod1 = Mod.objects.filter(pk=pk).update(fld=10)
transaction.savepoint_commit(sid)
mod2 = Mod.objects.get(pk=pk)
transaction.commit()
self.assertEqual(mod2.fld, 10)
work()
@skipIf(connection.vendor == 'mysql' and \
connection.features._mysql_storage_engine == 'MyISAM',
"MyISAM MySQL storage engine doesn't support savepoints")
@skipUnlessDBFeature('uses_savepoints')
def test_savepoint_rollback(self):
@commit_manually
def work():
mod = Mod.objects.create(fld=1)
pk = mod.pk
sid = transaction.savepoint()
mod1 = Mod.objects.filter(pk=pk).update(fld=20)
transaction.savepoint_rollback(sid)
mod2 = Mod.objects.get(pk=pk)
transaction.commit()
self.assertEqual(mod2.fld, 1)
work()
| 39.5053 | 109 | 0.661807 |
51796b234a9b3558cc01021ae27caa40a91162bf | 4,995 | py | Python | ag_list_of_functions.py | arpanganguli/SACCR | 0232b9b34d67e3f67fd58675730ec67acafbe355 | [
"MIT"
] | null | null | null | ag_list_of_functions.py | arpanganguli/SACCR | 0232b9b34d67e3f67fd58675730ec67acafbe355 | [
"MIT"
] | 1 | 2021-09-17T23:32:01.000Z | 2021-09-17T23:32:01.000Z | ag_list_of_functions.py | arpanganguli/SACCR | 0232b9b34d67e3f67fd58675730ec67acafbe355 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 12 08:45:01 2021
@author: arpanganguli
"""
import pandas as pd
import glob
import os
from math import exp, log, sqrt
from scipy.stats import norm
# develop functions
def pick_latest_file():
"""
Picks latest file from the Database directory.
Returns
-------
Latest file from the Database directory.
"""
list_of_files = glob.glob("Database/*.json")
latest_file = max(list_of_files, key=os.path.getctime)
return latest_file
def generate_dataframe():
"""
Returns
-------
Reads the latest JSON file from the Database directory and generate resulting dataframe.
"""
latest_file = pick_latest_file()
file = pd.read_json(latest_file)
df = pd.json_normalize(file["data"])
return(df)
def intermediate_replacement_cost(func):
"""
Provides interim steps to calculate Replacement Cost (RC) component of Exposure at Default (EAD).
Returns
-------
Wrapper object.
"""
def wrapper(*args, **kwargs):
if func(*args, **kwargs) > 0:
return func(*args, **kwargs)
else:
return 0
return wrapper
@intermediate_replacement_cost
def calculate_replacement_cost(market_value):
"""
Calculates the replacement cost component of EAD.
Parameters
----------
V : Calculates Replacement Cost (RC) component of Exposure at Default (EAD)
Returns
-------
Replacement Cost (RC).
"""
return market_value.sum()
def calculate_market_value(value):
"""
Calculates the replacement cost component of EAD.
Parameters
----------
V : Current market value of the derivatives at the reference date.
Returns
-------
Replacement Cost (RC).
"""
market_value = value.sum()
return market_value
def calculate_multiplier(aggregate_add_on, value, RC):
"""
Calculates multiplier depending on Replacement Cost (RC).
Returns
-------
Multiplier.
"""
market_value = calculate_market_value(value)
if RC > 0:
multiplier = 1
return multiplier
else:
floor = 0.05
aggregate_add_on = 0.3
multiplier = floor + (1 - floor) * exp(market_value / (2 * (1 - floor) * aggregate_add_on))
if multiplier > 1:
return 1
else:
return multiplier
def calculate_supervisory_delta_put(vol=0.5, price=0.06, strike=0.05, time=1):
"""
Calculates supervisory delta for swaptions that are short in the primary risk factor.
Parameters
----------
vol : Supervisory option volatility.
DESCRIPTION. The default is 50%.
price : Underlying price (the appropriate forward swap rate)
DESCRIPTION. The default is 6%.
strike : Strike price (the swaption’s fixed rate)
DESCRIPTION. The default is 5%.
time : The option exercise date.
DESCRIPTION. The default is 1.
Returns
-------
delta : Supervisory delta
DESCRIPTION. Assigned to each trade in accordance with paragraph 159of Annex 4
"""
num = log(price/strike) + 0.5 * pow(vol,2) * time
denom = vol * sqrt(time)
delta = -1 * round(norm.cdf(-1*(num/denom)), 2)
return delta
def calculate_supervisory_delta_call(vol=0.5, price=0.06, strike=0.05, time=1):
"""
Calculates supervisory delta for swaptions that are long in the primary risk factor.
Parameters
----------
vol : Supervisory option volatility.
DESCRIPTION. The default is 50%.
price : Underlying price (the appropriate forward swap rate)
DESCRIPTION. The default is 6%.
strike : Strike price (the swaption’s fixed rate)
DESCRIPTION. The default is 5%.
time : The option exercise date.
DESCRIPTION. The default is 1.
Returns
-------
delta : Supervisory delta
DESCRIPTION. Assigned to each trade in accordance with paragraph 159of Annex 4
"""
num = log(price/strike) + 0.5* pow(vol,2) * time
denom = vol * sqrt(time)
delta = round(norm.cdf(num/denom), 2)
return delta
def calculate_effective_notional(first_value, second_value):
"""
Calculates effective notional amount for each hedging set
Parameters
----------
first_value : The square of sum of individual hedging currencies.
DESCRIPTION. Individual hedging currencies are squared and then summed up for the first component.
second_value : The sum of individual hedging currencies.
DESCRIPTION. Individual hedging currencies are summed up and then multiplied by 1.4 for the second component.
Returns
-------
Effective notional amount.
"""
first_component = first_value.sum()
second_component = 1.4*sum(a * b for a, b in zip(second_value, second_value[1:]))
effective_notional = first_component + second_component
return effective_notional
| 26.428571 | 117 | 0.640841 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.