repo_name
stringlengths 5
92
| path
stringlengths 4
221
| copies
stringclasses 19
values | size
stringlengths 4
6
| content
stringlengths 766
896k
| license
stringclasses 15
values | hash
int64 -9,223,277,421,539,062,000
9,223,102,107B
| line_mean
float64 6.51
99.9
| line_max
int64 32
997
| alpha_frac
float64 0.25
0.96
| autogenerated
bool 1
class | ratio
float64 1.5
13.6
| config_test
bool 2
classes | has_no_keywords
bool 2
classes | few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
roberthodgen/thought-jot | src/utilities.py | 1 | 2732 | """
The MIT License (MIT)
Copyright (c) 2015 Robert Hodgen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from ndb_users import users
import string
import re
import google.net.proto.ProtocolBuffer
from google.appengine.ext import ndb
from google.appengine.api import mail
def permalinkify(string):
""" Return a clean URL-friendly version of `string`. """
clean = string.lower().strip() # lowercase, striped of whitespace
clean = re.sub(r'\s(\s*)?', '-', clean) # Replace spaces with dashes "-"
clean = re.sub(r'[^a-z0-9-]', '', clean) # Strip non-alphanumeric
return clean
def key_for_urlsafe_id(key_id):
""" Try returning an NDB Key for `key_id`. None otherwise. """
key = None
try:
key = ndb.Key(urlsafe=key_id)
except google.net.proto.ProtocolBuffer.ProtocolBufferDecodeError, e:
return key
finally:
return key
def send_project_contributor_email(email_address, user, project):
""" Send `email` an email notifying them they've been added as a contributor
on `project`. """
sender_email_address = users._email_sender()
subject = ''.join([project.name, ' invite'])
with open('resource/email/project_contributor.txt', 'r') as f:
body_text = f.read()
body_text = body_text.format(login='http://thought-jot.appspot.com/login',
from_email=user.email, to_email=email_address,
project_name=project.name)
mail.send_mail(sender_email_address, email_address, subject, body_text)
def str_to_bool(string, allow_none=False):
""" Return a Boolean value for `string`. """
if allow_none and string is None:
return None
if string == 'True' or string == 'true':
return True
else:
return False
| mit | 7,328,222,909,209,888,000 | 34.025641 | 80 | 0.712299 | false | 3.91404 | false | false | false |
quokkaproject/quokka-classes | pipelines.py | 1 | 2318 | # coding: utf-8
from flask import request
from quokka.modules.cart.pipelines.base import CartPipeline
from quokka.utils import get_current_user
from .models import CourseSubscription, Subscriber
class SetSubscriber(CartPipeline):
def process(self):
name = request.form.get("name")
email = request.form.get("email")
area_code = request.form.get("area_code")
phone = request.form.get("phone")
document = request.form.get("document")
address = request.form.get("address")
confirm = request.form.get("classes_setsubscriber_confirm")
if not confirm:
return self.render('classes/setsubscriber.html', cart=self.cart)
formdata = dict(name=name, email=email, area_code=area_code,
phone=phone, document=document, address=address)
subscriptions = CourseSubscription.objects.filter(
cart=self.cart
)
user = get_current_user()
for subscription in subscriptions:
subscription.subscriber = self.get_subscriber(user, **formdata)
subscription.save()
self.cart.sender_data = {
"name": name or user.name,
"email": email or user.email,
"area_code": area_code,
"phone": phone.replace('-', '').replace('(', '').replace(')', ''),
}
self.cart.addlog("SetSubscriber Pipeline: defined sender data")
return self.go()
def get_subscriber(self, user, **kwargs):
if not user:
return None
try:
sub = Subscriber.objects.get(user=user)
sub.name = kwargs.get('name')
sub.email = kwargs.get('email')
sub.document = kwargs.get('document')
sub.address = kwargs.get('address')
sub.phone = u"%(area_code)s%(phone)s" % kwargs
sub.save()
return sub
except:
self.cart.addlog("Creating a new subscriber", save=False)
return Subscriber.objects.create(
name=kwargs.get('name'),
email=kwargs.get('email'),
user=user,
document=kwargs.get('document'),
address=kwargs.get('address'),
phone=u"%(area_code)s%(phone)s" % kwargs
)
| mit | 7,357,983,847,842,146,000 | 33.088235 | 78 | 0.572045 | false | 4.23766 | false | false | false |
walshjon/openmc | openmc/region.py | 1 | 18303 | from abc import ABCMeta, abstractmethod
from collections import OrderedDict
from collections.abc import Iterable, MutableSequence
from copy import deepcopy
import numpy as np
from openmc.checkvalue import check_type
class Region(metaclass=ABCMeta):
"""Region of space that can be assigned to a cell.
Region is an abstract base class that is inherited by
:class:`openmc.Halfspace`, :class:`openmc.Intersection`,
:class:`openmc.Union`, and :class:`openmc.Complement`. Each of those
respective classes are typically not instantiated directly but rather are
created through operators of the Surface and Region classes.
"""
def __and__(self, other):
return Intersection((self, other))
def __or__(self, other):
return Union((self, other))
def __invert__(self):
return Complement(self)
@abstractmethod
def __contains__(self, point):
pass
@abstractmethod
def __str__(self):
pass
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
else:
return str(self) == str(other)
def __ne__(self, other):
return not self == other
def get_surfaces(self, surfaces=None):
"""
Recursively find all the surfaces referenced by a region and return them
Parameters
----------
surfaces: collections.OrderedDict, optional
Dictionary mapping surface IDs to :class:`openmc.Surface` instances
Returns
-------
surfaces: collections.OrderedDict
Dictionary mapping surface IDs to :class:`openmc.Surface` instances
"""
if surfaces is None:
surfaces = OrderedDict()
for region in self:
surfaces = region.get_surfaces(surfaces)
return surfaces
@staticmethod
def from_expression(expression, surfaces):
"""Generate a region given an infix expression.
Parameters
----------
expression : str
Boolean expression relating surface half-spaces. The possible
operators are union '|', intersection ' ', and complement '~'. For
example, '(1 -2) | 3 ~(4 -5)'.
surfaces : dict
Dictionary whose keys are suface IDs that appear in the Boolean
expression and whose values are Surface objects.
"""
# Strip leading and trailing whitespace
expression = expression.strip()
# Convert the string expression into a list of tokens, i.e., operators
# and surface half-spaces, representing the expression in infix
# notation.
i = 0
i_start = -1
tokens = []
while i < len(expression):
if expression[i] in '()|~ ':
# If special character appears immediately after a non-operator,
# create a token with the apporpriate half-space
if i_start >= 0:
j = int(expression[i_start:i])
if j < 0:
tokens.append(-surfaces[abs(j)])
else:
tokens.append(+surfaces[abs(j)])
if expression[i] in '()|~':
# For everything other than intersection, add the operator
# to the list of tokens
tokens.append(expression[i])
else:
# Find next non-space character
while expression[i+1] == ' ':
i += 1
# If previous token is a halfspace or right parenthesis and next token
# is not a left parenthese or union operator, that implies that the
# whitespace is to be interpreted as an intersection operator
if (i_start >= 0 or tokens[-1] == ')') and \
expression[i+1] not in ')|':
tokens.append(' ')
i_start = -1
else:
# Check for invalid characters
if expression[i] not in '-+0123456789':
raise SyntaxError("Invalid character '{}' in expression"
.format(expression[i]))
# If we haven't yet reached the start of a word, start one
if i_start < 0:
i_start = i
i += 1
# If we've reached the end and we're still in a word, create a
# half-space token and add it to the list
if i_start >= 0:
j = int(expression[i_start:])
if j < 0:
tokens.append(-surfaces[abs(j)])
else:
tokens.append(+surfaces[abs(j)])
# The functions below are used to apply an operator to operands on the
# output queue during the shunting yard algorithm.
def can_be_combined(region):
return isinstance(region, Complement) or hasattr(region, 'surface')
def apply_operator(output, operator):
r2 = output.pop()
if operator == ' ':
r1 = output.pop()
if isinstance(r1, Intersection):
r1 &= r2
output.append(r1)
elif isinstance(r2, Intersection) and can_be_combined(r1):
r2.insert(0, r1)
output.append(r2)
else:
output.append(r1 & r2)
elif operator == '|':
r1 = output.pop()
if isinstance(r1, Union):
r1 |= r2
output.append(r1)
elif isinstance(r2, Union) and can_be_combined(r1):
r2.insert(0, r1)
output.append(r2)
else:
output.append(r1 | r2)
elif operator == '~':
output.append(~r2)
# The following is an implementation of the shunting yard algorithm to
# generate an abstract syntax tree for the region expression.
output = []
stack = []
precedence = {'|': 1, ' ': 2, '~': 3}
associativity = {'|': 'left', ' ': 'left', '~': 'right'}
for token in tokens:
if token in (' ', '|', '~'):
# Normal operators
while stack:
op = stack[-1]
if (op not in ('(', ')') and
((associativity[token] == 'right' and
precedence[token] < precedence[op]) or
(associativity[token] == 'left' and
precedence[token] <= precedence[op]))):
apply_operator(output, stack.pop())
else:
break
stack.append(token)
elif token == '(':
# Left parentheses
stack.append(token)
elif token == ')':
# Right parentheses
while stack[-1] != '(':
apply_operator(output, stack.pop())
if len(stack) == 0:
raise SyntaxError('Mismatched parentheses in '
'region specification.')
stack.pop()
else:
# Surface halfspaces
output.append(token)
while stack:
if stack[-1] in '()':
raise SyntaxError('Mismatched parentheses in region '
'specification.')
apply_operator(output, stack.pop())
# Since we are generating an abstract syntax tree rather than a reverse
# Polish notation expression, the output queue should have a single item
# at the end
return output[0]
@abstractmethod
def clone(self, memo=None):
"""Create a copy of this region - each of the surfaces in the
region's nodes will be cloned and will have new unique IDs.
Parameters
----------
memo : dict or None
A nested dictionary of previously cloned objects. This parameter
is used internally and should not be specified by the user.
Returns
-------
clone : openmc.Region
The clone of this region
Raises
------
NotImplementedError
This method is not implemented for the abstract region class.
"""
raise NotImplementedError('The clone method is not implemented for '
'the abstract region class.')
class Intersection(Region, MutableSequence):
r"""Intersection of two or more regions.
Instances of Intersection are generally created via the & operator applied
to two instances of :class:`openmc.Region`. This is illustrated in the
following example:
>>> equator = openmc.ZPlane(z0=0.0)
>>> earth = openmc.Sphere(R=637.1e6)
>>> northern_hemisphere = -earth & +equator
>>> southern_hemisphere = -earth & -equator
>>> type(northern_hemisphere)
<class 'openmc.region.Intersection'>
Instances of this class behave like a mutable sequence, e.g., they can be
indexed and have an append() method.
Parameters
----------
nodes : iterable of openmc.Region
Regions to take the intersection of
Attributes
----------
bounding_box : tuple of numpy.array
Lower-left and upper-right coordinates of an axis-aligned bounding box
"""
def __init__(self, nodes):
self._nodes = list(nodes)
def __and__(self, other):
new = Intersection(self)
new &= other
return new
def __iand__(self, other):
if isinstance(other, Intersection):
self.extend(other)
else:
self.append(other)
return self
# Implement mutable sequence protocol by delegating to list
def __getitem__(self, key):
return self._nodes[key]
def __setitem__(self, key, value):
self._nodes[key] = value
def __delitem__(self, key):
del self._nodes[key]
def __len__(self):
return len(self._nodes)
def insert(self, index, value):
self._nodes.insert(index, value)
def __contains__(self, point):
"""Check whether a point is contained in the region.
Parameters
----------
point : 3-tuple of float
Cartesian coordinates, :math:`(x',y',z')`, of the point
Returns
-------
bool
Whether the point is in the region
"""
return all(point in n for n in self)
def __str__(self):
return '(' + ' '.join(map(str, self)) + ')'
@property
def bounding_box(self):
lower_left = np.array([-np.inf, -np.inf, -np.inf])
upper_right = np.array([np.inf, np.inf, np.inf])
for n in self:
lower_left_n, upper_right_n = n.bounding_box
lower_left[:] = np.maximum(lower_left, lower_left_n)
upper_right[:] = np.minimum(upper_right, upper_right_n)
return lower_left, upper_right
def clone(self, memo=None):
"""Create a copy of this region - each of the surfaces in the
intersection's nodes will be cloned and will have new unique IDs.
Parameters
----------
memo : dict or None
A nested dictionary of previously cloned objects. This parameter
is used internally and should not be specified by the user.
Returns
-------
clone : openmc.Intersection
The clone of this intersection
"""
if memo is None:
memo = {}
clone = deepcopy(self)
clone[:] = [n.clone(memo) for n in self]
return clone
class Union(Region, MutableSequence):
r"""Union of two or more regions.
Instances of Union are generally created via the | operator applied to two
instances of :class:`openmc.Region`. This is illustrated in the following
example:
>>> s1 = openmc.ZPlane(z0=0.0)
>>> s2 = openmc.Sphere(R=637.1e6)
>>> type(-s2 | +s1)
<class 'openmc.region.Union'>
Instances of this class behave like a mutable sequence, e.g., they can be
indexed and have an append() method.
Parameters
----------
nodes : iterable of openmc.Region
Regions to take the union of
Attributes
----------
bounding_box : 2-tuple of numpy.array
Lower-left and upper-right coordinates of an axis-aligned bounding box
"""
def __init__(self, nodes):
self._nodes = list(nodes)
def __or__(self, other):
new = Union(self)
new |= other
return new
def __ior__(self, other):
if isinstance(other, Union):
self.extend(other)
else:
self.append(other)
return self
# Implement mutable sequence protocol by delegating to list
def __getitem__(self, key):
return self._nodes[key]
def __setitem__(self, key, value):
self._nodes[key] = value
def __delitem__(self, key):
del self._nodes[key]
def __len__(self):
return len(self._nodes)
def insert(self, index, value):
self._nodes.insert(index, value)
def __contains__(self, point):
"""Check whether a point is contained in the region.
Parameters
----------
point : 3-tuple of float
Cartesian coordinates, :math:`(x',y',z')`, of the point
Returns
-------
bool
Whether the point is in the region
"""
return any(point in n for n in self)
def __str__(self):
return '(' + ' | '.join(map(str, self)) + ')'
@property
def bounding_box(self):
lower_left = np.array([np.inf, np.inf, np.inf])
upper_right = np.array([-np.inf, -np.inf, -np.inf])
for n in self:
lower_left_n, upper_right_n = n.bounding_box
lower_left[:] = np.minimum(lower_left, lower_left_n)
upper_right[:] = np.maximum(upper_right, upper_right_n)
return lower_left, upper_right
def clone(self, memo=None):
"""Create a copy of this region - each of the surfaces in the
union's nodes will be cloned and will have new unique IDs.
Parameters
----------
memo : dict or None
A nested dictionary of previously cloned objects. This parameter
is used internally and should not be specified by the user.
Returns
-------
clone : openmc.Union
The clone of this union
"""
if memo is None:
memo = {}
clone = deepcopy(self)
clone[:] = [n.clone(memo) for n in self]
return clone
class Complement(Region):
"""Complement of a region.
The Complement of an existing :class:`openmc.Region` can be created by using
the ~ operator as the following example demonstrates:
>>> xl = openmc.XPlane(x0=-10.0)
>>> xr = openmc.XPlane(x0=10.0)
>>> yl = openmc.YPlane(y0=-10.0)
>>> yr = openmc.YPlane(y0=10.0)
>>> inside_box = +xl & -xr & +yl & -yl
>>> outside_box = ~inside_box
>>> type(outside_box)
<class 'openmc.region.Complement'>
Parameters
----------
node : openmc.Region
Region to take the complement of
Attributes
----------
node : openmc.Region
Regions to take the complement of
bounding_box : tuple of numpy.array
Lower-left and upper-right coordinates of an axis-aligned bounding box
"""
def __init__(self, node):
self.node = node
def __contains__(self, point):
"""Check whether a point is contained in the region.
Parameters
----------
point : 3-tuple of float
Cartesian coordinates, :math:`(x',y',z')`, of the point
Returns
-------
bool
Whether the point is in the region
"""
return point not in self.node
def __str__(self):
return '~' + str(self.node)
@property
def node(self):
return self._node
@node.setter
def node(self, node):
check_type('node', node, Region)
self._node = node
@property
def bounding_box(self):
# Use De Morgan's laws to distribute the complement operator so that it
# only applies to surface half-spaces, thus allowing us to calculate the
# bounding box in the usual recursive manner.
if isinstance(self.node, Union):
temp_region = Intersection(~n for n in self.node)
elif isinstance(self.node, Intersection):
temp_region = Union(~n for n in self.node)
elif isinstance(self.node, Complement):
temp_region = self.node.node
else:
temp_region = ~self.node
return temp_region.bounding_box
def get_surfaces(self, surfaces=None):
"""
Recursively find and return all the surfaces referenced by the node
Parameters
----------
surfaces: collections.OrderedDict, optional
Dictionary mapping surface IDs to :class:`openmc.Surface` instances
Returns
-------
surfaces: collections.OrderedDict
Dictionary mapping surface IDs to :class:`openmc.Surface` instances
"""
if surfaces is None:
surfaces = OrderedDict()
for region in self.node:
surfaces = region.get_surfaces(surfaces)
return surfaces
def clone(self, memo=None):
"""Create a copy of this region - each of the surfaces in the
complement's node will be cloned and will have new unique IDs.
Parameters
----------
memo : dict or None
A nested dictionary of previously cloned objects. This parameter
is used internally and should not be specified by the user.
Returns
-------
clone : openmc.Complement
The clone of this complement
"""
if memo is None:
memo = {}
clone = deepcopy(self)
clone.node = self.node.clone(memo)
return clone
| mit | -4,142,554,628,031,096,300 | 30.233788 | 90 | 0.543845 | false | 4.538309 | false | false | false |
squilter/ardupilot | Tools/autotest/arduplane.py | 1 | 85180 | #!/usr/bin/env python
# Fly ArduPlane in SITL
from __future__ import print_function
import math
import os
import time
from pymavlink import quaternion
from pymavlink import mavutil
from common import AutoTest
from common import AutoTestTimeoutException
from common import NotAchievedException
from common import PreconditionFailedException
import operator
# get location of scripts
testdir = os.path.dirname(os.path.realpath(__file__))
SITL_START_LOCATION = mavutil.location(-35.362938, 149.165085, 585, 354)
WIND = "0,180,0.2" # speed,direction,variance
class AutoTestPlane(AutoTest):
@staticmethod
def get_not_armable_mode_list():
return []
@staticmethod
def get_not_disarmed_settable_modes_list():
return ["FOLLOW"]
@staticmethod
def get_no_position_not_settable_modes_list():
return []
@staticmethod
def get_position_armable_modes_list():
return ["GUIDED", "AUTO"]
@staticmethod
def get_normal_armable_modes_list():
return ["MANUAL", "STABILIZE", "ACRO"]
def log_name(self):
return "ArduPlane"
def test_filepath(self):
return os.path.realpath(__file__)
def sitl_start_location(self):
return SITL_START_LOCATION
def defaults_filepath(self):
return os.path.join(testdir, 'default_params/plane-jsbsim.parm')
def set_current_test_name(self, name):
self.current_test_name_directory = "ArduPlane_Tests/" + name + "/"
def default_frame(self):
return "plane-elevrev"
def apply_defaultfile_parameters(self):
# plane passes in a defaults_filepath in place of applying
# parameters afterwards.
pass
def is_plane(self):
return True
def get_stick_arming_channel(self):
return int(self.get_parameter("RCMAP_YAW"))
def get_disarm_delay(self):
return int(self.get_parameter("LAND_DISARMDELAY"))
def set_autodisarm_delay(self, delay):
self.set_parameter("LAND_DISARMDELAY", delay)
def takeoff(self, alt=150, alt_max=None, relative=True):
"""Takeoff to altitude."""
if alt_max is None:
alt_max = alt + 30
self.change_mode("FBWA")
self.wait_ready_to_arm()
self.arm_vehicle()
# some rudder to counteract the prop torque
self.set_rc(4, 1700)
# some up elevator to keep the tail down
self.set_rc(2, 1200)
# get it moving a bit first
self.set_rc(3, 1300)
self.wait_groundspeed(6, 100)
# a bit faster again, straighten rudder
self.set_rc(3, 1600)
self.set_rc(4, 1500)
self.wait_groundspeed(12, 100)
# hit the gas harder now, and give it some more elevator
self.set_rc(2, 1100)
self.set_rc(3, 2000)
# gain a bit of altitude
self.wait_altitude(alt, alt_max, timeout=30, relative=relative)
# level off
self.set_rc(2, 1500)
self.progress("TAKEOFF COMPLETE")
def fly_left_circuit(self):
"""Fly a left circuit, 200m on a side."""
self.mavproxy.send('switch 4\n')
self.wait_mode('FBWA')
self.set_rc(3, 2000)
self.wait_level_flight()
self.progress("Flying left circuit")
# do 4 turns
for i in range(0, 4):
# hard left
self.progress("Starting turn %u" % i)
self.set_rc(1, 1000)
self.wait_heading(270 - (90*i), accuracy=10)
self.set_rc(1, 1500)
self.progress("Starting leg %u" % i)
self.wait_distance(100, accuracy=20)
self.progress("Circuit complete")
def fly_RTL(self):
"""Fly to home."""
self.progress("Flying home in RTL")
self.mavproxy.send('switch 2\n')
self.wait_mode('RTL')
self.wait_location(self.homeloc,
accuracy=120,
target_altitude=self.homeloc.alt+100,
height_accuracy=20,
timeout=180)
self.progress("RTL Complete")
def fly_LOITER(self, num_circles=4):
"""Loiter where we are."""
self.progress("Testing LOITER for %u turns" % num_circles)
self.mavproxy.send('loiter\n')
self.wait_mode('LOITER')
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
initial_alt = m.alt
self.progress("Initial altitude %u\n" % initial_alt)
while num_circles > 0:
self.wait_heading(0, accuracy=10, timeout=60)
self.wait_heading(180, accuracy=10, timeout=60)
num_circles -= 1
self.progress("Loiter %u circles left" % num_circles)
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
final_alt = m.alt
self.progress("Final altitude %u initial %u\n" %
(final_alt, initial_alt))
self.mavproxy.send('mode FBWA\n')
self.wait_mode('FBWA')
if abs(final_alt - initial_alt) > 20:
raise NotAchievedException("Failed to maintain altitude")
self.progress("Completed Loiter OK")
def fly_CIRCLE(self, num_circles=1):
"""Circle where we are."""
self.progress("Testing CIRCLE for %u turns" % num_circles)
self.mavproxy.send('mode CIRCLE\n')
self.wait_mode('CIRCLE')
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
initial_alt = m.alt
self.progress("Initial altitude %u\n" % initial_alt)
while num_circles > 0:
self.wait_heading(0, accuracy=10, timeout=60)
self.wait_heading(180, accuracy=10, timeout=60)
num_circles -= 1
self.progress("CIRCLE %u circles left" % num_circles)
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
final_alt = m.alt
self.progress("Final altitude %u initial %u\n" %
(final_alt, initial_alt))
self.mavproxy.send('mode FBWA\n')
self.wait_mode('FBWA')
if abs(final_alt - initial_alt) > 20:
raise NotAchievedException("Failed to maintain altitude")
self.progress("Completed CIRCLE OK")
def wait_level_flight(self, accuracy=5, timeout=30):
"""Wait for level flight."""
tstart = self.get_sim_time()
self.progress("Waiting for level flight")
self.set_rc(1, 1500)
self.set_rc(2, 1500)
self.set_rc(4, 1500)
while self.get_sim_time_cached() < tstart + timeout:
m = self.mav.recv_match(type='ATTITUDE', blocking=True)
roll = math.degrees(m.roll)
pitch = math.degrees(m.pitch)
self.progress("Roll=%.1f Pitch=%.1f" % (roll, pitch))
if math.fabs(roll) <= accuracy and math.fabs(pitch) <= accuracy:
self.progress("Attained level flight")
return
raise NotAchievedException("Failed to attain level flight")
def change_altitude(self, altitude, accuracy=30):
"""Get to a given altitude."""
self.mavproxy.send('mode FBWA\n')
self.wait_mode('FBWA')
alt_error = self.mav.messages['VFR_HUD'].alt - altitude
if alt_error > 0:
self.set_rc(2, 2000)
else:
self.set_rc(2, 1000)
self.wait_altitude(altitude-accuracy/2, altitude+accuracy/2)
self.set_rc(2, 1500)
self.progress("Reached target altitude at %u" %
self.mav.messages['VFR_HUD'].alt)
return self.wait_level_flight()
def axial_left_roll(self, count=1):
"""Fly a left axial roll."""
# full throttle!
self.set_rc(3, 2000)
self.change_altitude(self.homeloc.alt+300)
# fly the roll in manual
self.mavproxy.send('switch 6\n')
self.wait_mode('MANUAL')
while count > 0:
self.progress("Starting roll")
self.set_rc(1, 1000)
try:
self.wait_roll(-150, accuracy=90)
self.wait_roll(150, accuracy=90)
self.wait_roll(0, accuracy=90)
except Exception as e:
self.set_rc(1, 1500)
raise e
count -= 1
# back to FBWA
self.set_rc(1, 1500)
self.mavproxy.send('switch 4\n')
self.wait_mode('FBWA')
self.set_rc(3, 1700)
return self.wait_level_flight()
def inside_loop(self, count=1):
"""Fly a inside loop."""
# full throttle!
self.set_rc(3, 2000)
self.change_altitude(self.homeloc.alt+300)
# fly the loop in manual
self.mavproxy.send('switch 6\n')
self.wait_mode('MANUAL')
while count > 0:
self.progress("Starting loop")
self.set_rc(2, 1000)
self.wait_pitch(-60, accuracy=20)
self.wait_pitch(0, accuracy=20)
count -= 1
# back to FBWA
self.set_rc(2, 1500)
self.mavproxy.send('switch 4\n')
self.wait_mode('FBWA')
self.set_rc(3, 1700)
return self.wait_level_flight()
def set_attitude_target(self, tolerance=10):
"""Test setting of attitude target in guided mode."""
self.change_mode("GUIDED")
# self.set_parameter("STALL_PREVENTION", 0)
state_roll_over = "roll-over"
state_stabilize_roll = "stabilize-roll"
state_hold = "hold"
state_roll_back = "roll-back"
state_done = "done"
tstart = self.get_sim_time()
try:
state = state_roll_over
while state != state_done:
m = self.mav.recv_match(type='ATTITUDE',
blocking=True,
timeout=0.1)
now = self.get_sim_time_cached()
if now - tstart > 20:
raise AutoTestTimeoutException("Manuevers not completed")
if m is None:
continue
r = math.degrees(m.roll)
if state == state_roll_over:
target_roll_degrees = 60
if abs(r - target_roll_degrees) < tolerance:
state = state_stabilize_roll
stabilize_start = now
elif state == state_stabilize_roll:
# just give it a little time to sort it self out
if now - stabilize_start > 2:
state = state_hold
hold_start = now
elif state == state_hold:
target_roll_degrees = 60
if now - hold_start > tolerance:
state = state_roll_back
if abs(r - target_roll_degrees) > tolerance:
raise NotAchievedException("Failed to hold attitude")
elif state == state_roll_back:
target_roll_degrees = 0
if abs(r - target_roll_degrees) < tolerance:
state = state_done
else:
raise ValueError("Unknown state %s" % str(state))
m_nav = self.mav.messages['NAV_CONTROLLER_OUTPUT']
self.progress("%s Roll: %f desired=%f set=%f" %
(state, r, m_nav.nav_roll, target_roll_degrees))
time_boot_millis = 0 # FIXME
target_system = 1 # FIXME
target_component = 1 # FIXME
type_mask = 0b10000001 ^ 0xFF # FIXME
# attitude in radians:
q = quaternion.Quaternion([math.radians(target_roll_degrees),
0,
0])
roll_rate_radians = 0.5
pitch_rate_radians = 0
yaw_rate_radians = 0
thrust = 1.0
self.mav.mav.set_attitude_target_send(time_boot_millis,
target_system,
target_component,
type_mask,
q,
roll_rate_radians,
pitch_rate_radians,
yaw_rate_radians,
thrust)
except Exception as e:
self.mavproxy.send('mode FBWA\n')
self.wait_mode('FBWA')
self.set_rc(3, 1700)
raise e
# back to FBWA
self.mavproxy.send('mode FBWA\n')
self.wait_mode('FBWA')
self.set_rc(3, 1700)
self.wait_level_flight()
def test_stabilize(self, count=1):
"""Fly stabilize mode."""
# full throttle!
self.set_rc(3, 2000)
self.set_rc(2, 1300)
self.change_altitude(self.homeloc.alt+300)
self.set_rc(2, 1500)
self.mavproxy.send("mode STABILIZE\n")
self.wait_mode('STABILIZE')
while count > 0:
self.progress("Starting roll")
self.set_rc(1, 2000)
self.wait_roll(-150, accuracy=90)
self.wait_roll(150, accuracy=90)
self.wait_roll(0, accuracy=90)
count -= 1
self.set_rc(1, 1500)
self.wait_roll(0, accuracy=5)
# back to FBWA
self.mavproxy.send('mode FBWA\n')
self.wait_mode('FBWA')
self.set_rc(3, 1700)
return self.wait_level_flight()
def test_acro(self, count=1):
"""Fly ACRO mode."""
# full throttle!
self.set_rc(3, 2000)
self.set_rc(2, 1300)
self.change_altitude(self.homeloc.alt+300)
self.set_rc(2, 1500)
self.mavproxy.send("mode ACRO\n")
self.wait_mode('ACRO')
while count > 0:
self.progress("Starting roll")
self.set_rc(1, 1000)
self.wait_roll(-150, accuracy=90)
self.wait_roll(150, accuracy=90)
self.wait_roll(0, accuracy=90)
count -= 1
self.set_rc(1, 1500)
# back to FBWA
self.mavproxy.send('mode FBWA\n')
self.wait_mode('FBWA')
self.wait_level_flight()
self.mavproxy.send("mode ACRO\n")
self.wait_mode('ACRO')
count = 2
while count > 0:
self.progress("Starting loop")
self.set_rc(2, 1000)
self.wait_pitch(-60, accuracy=20)
self.wait_pitch(0, accuracy=20)
count -= 1
self.set_rc(2, 1500)
# back to FBWA
self.mavproxy.send('mode FBWA\n')
self.wait_mode('FBWA')
self.set_rc(3, 1700)
return self.wait_level_flight()
def test_FBWB(self, mode='FBWB'):
"""Fly FBWB or CRUISE mode."""
self.mavproxy.send("mode %s\n" % mode)
self.wait_mode(mode)
self.set_rc(3, 1700)
self.set_rc(2, 1500)
# lock in the altitude by asking for an altitude change then releasing
self.set_rc(2, 1000)
self.wait_distance(50, accuracy=20)
self.set_rc(2, 1500)
self.wait_distance(50, accuracy=20)
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
initial_alt = m.alt
self.progress("Initial altitude %u\n" % initial_alt)
self.progress("Flying right circuit")
# do 4 turns
for i in range(0, 4):
# hard left
self.progress("Starting turn %u" % i)
self.set_rc(1, 1800)
try:
self.wait_heading(0 + (90*i), accuracy=20, timeout=60)
except Exception as e:
self.set_rc(1, 1500)
raise e
self.set_rc(1, 1500)
self.progress("Starting leg %u" % i)
self.wait_distance(100, accuracy=20)
self.progress("Circuit complete")
self.progress("Flying rudder left circuit")
# do 4 turns
for i in range(0, 4):
# hard left
self.progress("Starting turn %u" % i)
self.set_rc(4, 1900)
try:
self.wait_heading(360 - (90*i), accuracy=20, timeout=60)
except Exception as e:
self.set_rc(4, 1500)
raise e
self.set_rc(4, 1500)
self.progress("Starting leg %u" % i)
self.wait_distance(100, accuracy=20)
self.progress("Circuit complete")
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
final_alt = m.alt
self.progress("Final altitude %u initial %u\n" %
(final_alt, initial_alt))
# back to FBWA
self.mavproxy.send('mode FBWA\n')
self.wait_mode('FBWA')
if abs(final_alt - initial_alt) > 20:
raise NotAchievedException("Failed to maintain altitude")
return self.wait_level_flight()
def fly_mission(self, filename, mission_timeout=60.0):
"""Fly a mission from a file."""
self.progress("Flying mission %s" % filename)
self.load_mission(filename)
self.mavproxy.send('switch 1\n') # auto mode
self.wait_mode('AUTO')
self.wait_waypoint(1, 7, max_dist=60)
self.wait_groundspeed(0, 0.5, timeout=mission_timeout)
self.mavproxy.expect("Auto disarmed")
self.progress("Mission OK")
def fly_do_reposition(self):
self.progress("Takeoff")
self.takeoff(alt=50)
self.set_rc(3, 1500)
self.progress("Entering guided and flying somewhere constant")
self.change_mode("GUIDED")
loc = self.mav.location()
self.location_offset_ne(loc, 500, 500)
new_alt = 100
self.run_cmd_int(
mavutil.mavlink.MAV_CMD_DO_REPOSITION,
0,
0,
0,
0,
int(loc.lat*1e7),
int(loc.lng*1e7),
new_alt, # alt
frame=mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT,
)
self.wait_altitude(new_alt-10, new_alt, timeout=30, relative=True)
self.fly_home_land_and_disarm()
def fly_deepstall(self):
# self.fly_deepstall_absolute()
self.fly_deepstall_relative()
def fly_deepstall_absolute(self):
self.start_subtest("DeepStall Relative Absolute")
self.set_parameter("LAND_TYPE", 1)
deepstall_elevator_pwm = 1661
self.set_parameter("LAND_DS_ELEV_PWM", deepstall_elevator_pwm)
self.load_mission("plane-deepstall-mission.txt")
self.change_mode("AUTO")
self.wait_ready_to_arm()
self.arm_vehicle()
self.progress("Waiting for deepstall messages")
self.wait_text("Deepstall: Entry: ", timeout=240)
# assume elevator is on channel 2:
self.wait_servo_channel_value(2, deepstall_elevator_pwm)
self.disarm_wait(timeout=120)
self.progress("Flying home")
self.takeoff(10)
self.set_parameter("LAND_TYPE", 0)
self.fly_home_land_and_disarm()
def fly_deepstall_relative(self):
self.start_subtest("DeepStall Relative")
self.set_parameter("LAND_TYPE", 1)
deepstall_elevator_pwm = 1661
self.set_parameter("LAND_DS_ELEV_PWM", deepstall_elevator_pwm)
self.load_mission("plane-deepstall-relative-mission.txt")
self.change_mode("AUTO")
self.wait_ready_to_arm()
self.arm_vehicle()
self.progress("Waiting for deepstall messages")
self.wait_text("Deepstall: Entry: ", timeout=240)
# assume elevator is on channel 2:
self.wait_servo_channel_value(2, deepstall_elevator_pwm)
self.disarm_wait(timeout=120)
self.progress("Flying home")
self.takeoff(100)
self.set_parameter("LAND_TYPE", 0)
self.fly_home_land_and_disarm(timeout=240)
def fly_do_change_speed(self):
# the following lines ensure we revert these parameter values
# - DO_CHANGE_AIRSPEED is a permanent vehicle change!
self.set_parameter("TRIM_ARSPD_CM", self.get_parameter("TRIM_ARSPD_CM"))
self.set_parameter("MIN_GNDSPD_CM", self.get_parameter("MIN_GNDSPD_CM"))
self.progress("Takeoff")
self.takeoff(alt=100)
self.set_rc(3, 1500)
# ensure we know what the airspeed is:
self.progress("Entering guided and flying somewhere constant")
self.change_mode("GUIDED")
self.run_cmd_int(
mavutil.mavlink.MAV_CMD_DO_REPOSITION,
0,
0,
0,
0,
12345, # lat*1e7
12345, # lon*1e7
100 # alt
)
self.delay_sim_time(10)
self.progress("Ensuring initial speed is known and relatively constant")
initial_speed = 21.5;
timeout = 10
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > timeout:
break
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
self.progress("GroundSpeed: %f want=%f" %
(m.groundspeed, initial_speed))
if abs(initial_speed - m.groundspeed) > 1:
raise NotAchievedException("Initial speed not as expected (want=%f got=%f" % (initial_speed, m.groundspeed))
self.progress("Setting groundspeed")
new_target_groundspeed = initial_speed + 5
self.run_cmd(
mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED,
1, # groundspeed
new_target_groundspeed,
-1, # throttle / no change
0, # absolute values
0,
0,
0)
self.wait_groundspeed(new_target_groundspeed-0.5, new_target_groundspeed+0.5, timeout=40)
self.progress("Adding some wind, ensuring groundspeed holds")
self.set_parameter("SIM_WIND_SPD", 5)
self.delay_sim_time(5)
self.wait_groundspeed(new_target_groundspeed-0.5, new_target_groundspeed+0.5, timeout=40)
self.set_parameter("SIM_WIND_SPD", 0)
self.progress("Setting airspeed")
new_target_airspeed = initial_speed + 5
self.run_cmd(
mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED,
0, # airspeed
new_target_airspeed,
-1, # throttle / no change
0, # absolute values
0,
0,
0)
self.wait_groundspeed(new_target_airspeed-0.5, new_target_airspeed+0.5)
self.progress("Adding some wind, hoping groundspeed increases/decreases")
self.set_parameter("SIM_WIND_SPD", 5)
self.set_parameter("SIM_WIND_DIR", 270)
self.delay_sim_time(5)
timeout = 10
tstart = self.get_sim_time()
while True:
if self.get_sim_time_cached() - tstart > timeout:
raise NotAchievedException("Did not achieve groundspeed delta")
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
delta = abs(m.airspeed - m.groundspeed)
want_delta = 4
self.progress("groundspeed and airspeed should be different (have=%f want=%f)" % (delta, want_delta))
if delta > want_delta:
break
self.fly_home_land_and_disarm()
def fly_home_land_and_disarm(self, timeout=120):
filename = "flaps.txt"
self.progress("Using %s to fly home" % filename)
num_wp = self.load_mission(filename)
self.change_mode("AUTO")
self.mavproxy.send('wp set 7\n')
self.drain_mav()
# TODO: reflect on file to find this magic waypoint number?
# self.wait_waypoint(7, num_wp-1, timeout=500) # we tend to miss the final waypoint by a fair bit, and this is probably too noisy anyway?
self.wait_disarmed(timeout=timeout)
def fly_flaps(self):
"""Test flaps functionality."""
filename = "flaps.txt"
self.context_push()
ex = None
try:
flaps_ch = 5
servo_ch = 5
self.set_parameter("SERVO%u_FUNCTION" % servo_ch, 3) # flapsauto
self.set_parameter("RC%u_OPTION" % flaps_ch, 208) # Flaps RCx_OPTION
self.set_parameter("LAND_FLAP_PERCNT", 50)
self.set_parameter("LOG_DISARMED", 1)
flaps_ch_min = 1000
flaps_ch_trim = 1500
flaps_ch_max = 2000
self.set_parameter("RC%u_MIN" % flaps_ch, flaps_ch_min)
self.set_parameter("RC%u_MAX" % flaps_ch, flaps_ch_max)
self.set_parameter("RC%u_TRIM" % flaps_ch, flaps_ch_trim)
servo_ch_min = 1200
servo_ch_trim = 1300
servo_ch_max = 1800
self.set_parameter("SERVO%u_MIN" % servo_ch, servo_ch_min)
self.set_parameter("SERVO%u_MAX" % servo_ch, servo_ch_max)
self.set_parameter("SERVO%u_TRIM" % servo_ch, servo_ch_trim)
self.progress("check flaps are not deployed")
self.set_rc(flaps_ch, flaps_ch_min)
self.wait_servo_channel_value(servo_ch, servo_ch_min)
self.progress("deploy the flaps")
self.set_rc(flaps_ch, flaps_ch_max)
tstart = self.get_sim_time()
self.wait_servo_channel_value(servo_ch, servo_ch_max)
tstop = self.get_sim_time_cached()
delta_time = tstop - tstart
delta_time_min = 0.5
delta_time_max = 1.5
if delta_time < delta_time_min or delta_time > delta_time_max:
raise NotAchievedException((
"Flaps Slew not working (%f seconds)" % (delta_time,)))
self.progress("undeploy flaps")
self.set_rc(flaps_ch, flaps_ch_min)
self.wait_servo_channel_value(servo_ch, servo_ch_min)
self.progress("Flying mission %s" % filename)
self.load_mission(filename)
self.mavproxy.send('wp set 1\n')
self.mavproxy.send('switch 1\n') # auto mode
self.wait_mode('AUTO')
self.wait_ready_to_arm()
self.arm_vehicle()
last_mission_current_msg = 0
last_seq = None
while self.armed():
m = self.mav.recv_match(type='MISSION_CURRENT', blocking=True)
time_delta = (self.get_sim_time_cached() -
last_mission_current_msg)
if (time_delta > 1 or m.seq != last_seq):
dist = None
x = self.mav.messages.get("NAV_CONTROLLER_OUTPUT", None)
if x is not None:
dist = x.wp_dist
self.progress("MISSION_CURRENT.seq=%u (dist=%s)" %
(m.seq, str(dist)))
last_mission_current_msg = self.get_sim_time_cached()
last_seq = m.seq
# flaps should undeploy at the end
self.wait_servo_channel_value(servo_ch, servo_ch_min, timeout=30)
# do a short flight in FBWA, watching for flaps
# self.mavproxy.send('switch 4\n')
# self.wait_mode('FBWA')
# self.delay_sim_time(10)
# self.mavproxy.send('switch 6\n')
# self.wait_mode('MANUAL')
# self.delay_sim_time(10)
self.progress("Flaps OK")
except Exception as e:
ex = e
self.context_pop()
if ex:
if self.armed():
self.disarm_vehicle()
raise ex
def test_rc_relay(self):
'''test toggling channel 12 toggles relay'''
self.set_parameter("RC12_OPTION", 28) # Relay On/Off
self.set_rc(12, 1000)
self.reboot_sitl() # needed for RC12_OPTION to take effect
off = self.get_parameter("SIM_PIN_MASK")
if off:
raise PreconditionFailedException("SIM_MASK_PIN off")
# allow time for the RC library to register initial value:
self.delay_sim_time(1)
self.set_rc(12, 2000)
self.wait_heartbeat()
self.wait_heartbeat()
on = self.get_parameter("SIM_PIN_MASK")
if not on:
raise NotAchievedException("SIM_PIN_MASK doesn't reflect ON")
self.set_rc(12, 1000)
self.wait_heartbeat()
self.wait_heartbeat()
off = self.get_parameter("SIM_PIN_MASK")
if off:
raise NotAchievedException("SIM_PIN_MASK doesn't reflect OFF")
def test_rc_option_camera_trigger(self):
'''test toggling channel 12 takes picture'''
self.set_parameter("RC12_OPTION", 9) # CameraTrigger
self.reboot_sitl() # needed for RC12_OPTION to take effect
x = self.mav.messages.get("CAMERA_FEEDBACK", None)
if x is not None:
raise PreconditionFailedException("Receiving CAMERA_FEEDBACK?!")
self.set_rc(12, 2000)
tstart = self.get_sim_time()
while self.get_sim_time_cached() - tstart < 10:
x = self.mav.messages.get("CAMERA_FEEDBACK", None)
if x is not None:
break
self.wait_heartbeat()
self.set_rc(12, 1000)
if x is None:
raise NotAchievedException("No CAMERA_FEEDBACK message received")
def test_throttle_failsafe(self):
self.change_mode('MANUAL')
m = self.mav.recv_match(type='SYS_STATUS', blocking=True)
receiver_bit = mavutil.mavlink.MAV_SYS_STATUS_SENSOR_RC_RECEIVER
self.progress("Testing receiver enabled")
if (not (m.onboard_control_sensors_enabled & receiver_bit)):
raise PreconditionFailedException()
self.progress("Testing receiver present")
if (not (m.onboard_control_sensors_present & receiver_bit)):
raise PreconditionFailedException()
self.progress("Testing receiver health")
if (not (m.onboard_control_sensors_health & receiver_bit)):
raise PreconditionFailedException()
self.progress("Ensure we know original throttle value")
self.wait_rc_channel_value(3, 1000)
self.set_parameter("THR_FS_VALUE", 960)
self.progress("Failing receiver (throttle-to-950)")
self.context_collect("HEARTBEAT")
self.set_parameter("SIM_RC_FAIL", 2) # throttle-to-950
self.wait_mode('RTL') # long failsafe
if (not self.get_mode_from_mode_mapping("CIRCLE") in [x.custom_mode for x in self.context_stop_collecting("HEARTBEAT")]):
raise NotAchievedException("Did not go via circle mode")
self.progress("Ensure we've had our throttle squashed to 950")
self.wait_rc_channel_value(3, 950)
self.drain_mav_unparsed()
m = self.mav.recv_match(type='SYS_STATUS', blocking=True)
print("%s" % str(m))
self.progress("Testing receiver enabled")
if (not (m.onboard_control_sensors_enabled & receiver_bit)):
raise NotAchievedException("Receiver not enabled")
self.progress("Testing receiver present")
if (not (m.onboard_control_sensors_present & receiver_bit)):
raise NotAchievedException("Receiver not present")
# skip this until RC is fixed
# self.progress("Testing receiver health")
# if (m.onboard_control_sensors_health & receiver_bit):
# raise NotAchievedException("Sensor healthy when it shouldn't be")
self.set_parameter("SIM_RC_FAIL", 0)
self.drain_mav_unparsed()
# have to allow time for RC to be fetched from SITL
self.delay_sim_time(0.5)
m = self.mav.recv_match(type='SYS_STATUS', blocking=True)
self.progress("Testing receiver enabled")
if (not (m.onboard_control_sensors_enabled & receiver_bit)):
raise NotAchievedException("Receiver not enabled")
self.progress("Testing receiver present")
if (not (m.onboard_control_sensors_present & receiver_bit)):
raise NotAchievedException("Receiver not present")
self.progress("Testing receiver health")
if (not (m.onboard_control_sensors_health & receiver_bit)):
raise NotAchievedException("Receiver not healthy2")
self.change_mode('MANUAL')
self.progress("Failing receiver (no-pulses)")
self.context_collect("HEARTBEAT")
self.set_parameter("SIM_RC_FAIL", 1) # no-pulses
self.wait_mode('RTL') # long failsafe
if (not self.get_mode_from_mode_mapping("CIRCLE") in [x.custom_mode for x in self.context_stop_collecting("HEARTBEAT")]):
raise NotAchievedException("Did not go via circle mode")
self.drain_mav_unparsed()
m = self.mav.recv_match(type='SYS_STATUS', blocking=True)
print("%s" % str(m))
self.progress("Testing receiver enabled")
if (not (m.onboard_control_sensors_enabled & receiver_bit)):
raise NotAchievedException("Receiver not enabled")
self.progress("Testing receiver present")
if (not (m.onboard_control_sensors_present & receiver_bit)):
raise NotAchievedException("Receiver not present")
self.progress("Testing receiver health")
if (m.onboard_control_sensors_health & receiver_bit):
raise NotAchievedException("Sensor healthy when it shouldn't be")
self.progress("Making RC work again")
self.set_parameter("SIM_RC_FAIL", 0)
# have to allow time for RC to be fetched from SITL
self.progress("Giving receiver time to recover")
self.delay_sim_time(0.5)
self.drain_mav_unparsed()
m = self.mav.recv_match(type='SYS_STATUS', blocking=True)
self.progress("Testing receiver enabled")
if (not (m.onboard_control_sensors_enabled & receiver_bit)):
raise NotAchievedException("Receiver not enabled")
self.progress("Testing receiver present")
if (not (m.onboard_control_sensors_present & receiver_bit)):
raise NotAchievedException("Receiver not present")
self.progress("Testing receiver health")
if (not (m.onboard_control_sensors_health & receiver_bit)):
raise NotAchievedException("Receiver not healthy")
self.change_mode('MANUAL')
self.progress("Ensure long failsafe can trigger when short failsafe disabled")
self.context_push()
self.context_collect("STATUSTEXT")
ex = None
try:
self.set_parameter("FS_SHORT_ACTN", 3) # 3 means disabled
self.set_parameter("SIM_RC_FAIL", 1)
self.wait_statustext("Long event on", check_context=True)
self.wait_mode("RTL")
# self.context_clear_collection("STATUSTEXT")
self.set_parameter("SIM_RC_FAIL", 0)
self.wait_text("Long event off", check_context=True)
self.change_mode("MANUAL")
self.progress("Trying again with THR_FS_VALUE")
self.set_parameter("THR_FS_VALUE", 960)
self.set_parameter("SIM_RC_FAIL", 2)
self.wait_statustext("Long event on", check_context=True)
self.wait_mode("RTL")
except Exception as e:
self.progress("Exception caught:")
self.progress(self.get_exception_stacktrace(e))
ex = e
self.context_pop()
if ex is not None:
raise ex
def test_throttle_failsafe_fence(self):
fence_bit = mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE
self.progress("Checking fence is not present before being configured")
m = self.mav.recv_match(type='SYS_STATUS', blocking=True)
print("%s" % str(m))
if (m.onboard_control_sensors_enabled & fence_bit):
raise NotAchievedException("Fence enabled before being configured")
self.change_mode('MANUAL')
self.wait_ready_to_arm()
self.load_fence("CMAC-fence.txt")
self.set_parameter("FENCE_CHANNEL", 7)
self.set_parameter("FENCE_ACTION", 4)
self.set_rc(3, 1000)
self.set_rc(7, 2000)
self.progress("Checking fence is initially OK")
m = self.mav.recv_match(type='SYS_STATUS', blocking=True)
print("%s" % str(m))
if (not (m.onboard_control_sensors_enabled & fence_bit)):
raise NotAchievedException("Fence not initially enabled")
self.set_parameter("THR_FS_VALUE", 960)
self.progress("Failing receiver (throttle-to-950)")
self.set_parameter("SIM_RC_FAIL", 2) # throttle-to-950
self.wait_mode("CIRCLE")
self.delay_sim_time(1) # give
self.drain_mav_unparsed()
self.progress("Checking fence is OK after receiver failure (bind-values)")
fence_bit = mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE
m = self.mav.recv_match(type='SYS_STATUS', blocking=True)
print("%s" % str(m))
if (not (m.onboard_control_sensors_enabled & fence_bit)):
raise NotAchievedException("Fence not enabled after RC fail")
def test_gripper_mission(self):
self.context_push()
ex = None
try:
self.load_mission("plane-gripper-mission.txt")
self.mavproxy.send("wp set 1\n")
self.change_mode('AUTO')
self.wait_ready_to_arm()
self.arm_vehicle()
self.mavproxy.expect("Gripper Grabbed")
self.mavproxy.expect("Gripper Released")
self.mavproxy.expect("Auto disarmed")
except Exception as e:
self.progress("Exception caught:")
self.progress(self.get_exception_stacktrace(e))
ex = e
self.context_pop()
if ex is not None:
raise ex
def assert_fence_sys_status(self, present, enabled, health):
self.delay_sim_time(1)
self.drain_mav_unparsed()
m = self.mav.recv_match(type='SYS_STATUS', blocking=True, timeout=1)
if m is None:
raise NotAchievedException("Did not receive SYS_STATUS")
tests = [ ( "present", present, m.onboard_control_sensors_present ),
( "enabled", enabled, m.onboard_control_sensors_enabled ),
( "health", health, m.onboard_control_sensors_health ),
]
bit = mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE
for test in tests:
(name, want, field) = test
got = (field & bit) != 0
if want != got:
raise NotAchievedException("fence status incorrect; %s want=%u got=%u" %
(name, want, got))
def do_fence_en_or_dis_able(self, value, want_result=mavutil.mavlink.MAV_RESULT_ACCEPTED):
if value:
p1 = 1
else:
p1 = 0
self.run_cmd(mavutil.mavlink.MAV_CMD_DO_FENCE_ENABLE,
p1, # param1
0, # param2
0, # param3
0, # param4
0, # param5
0, # param6
0, # param7
want_result=want_result)
def do_fence_enable(self, want_result=mavutil.mavlink.MAV_RESULT_ACCEPTED):
self.do_fence_en_or_dis_able(True, want_result=want_result)
def do_fence_disable(self, want_result=mavutil.mavlink.MAV_RESULT_ACCEPTED):
self.do_fence_en_or_dis_able(False, want_result=want_result)
def wait_circling_point_with_radius(self, loc, want_radius, epsilon=5.0, min_circle_time=5, timeout=120):
on_radius_start_heading = None
average_radius = 0.0
circle_time_start = 0
done_time = False
done_angle = False
tstart = self.get_sim_time()
while True:
if self.get_sim_time() - tstart > timeout:
raise AutoTestTimeoutException("Did not get onto circle")
here = self.mav.location()
got_radius = self.get_distance(loc, here)
average_radius = 0.95*average_radius + 0.05*got_radius
on_radius = abs(got_radius - want_radius) < epsilon
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
heading = m.heading
on_string = "off"
got_angle = ""
if on_radius_start_heading is not None:
got_angle = "%0.2f" % abs(on_radius_start_heading - heading) # FIXME
on_string = "on"
want_angle = 180 # we don't actually get this (angle-substraction issue. But we get enough...
self.progress("wait-circling: got-r=%0.2f want-r=%f avg-r=%f %s want-a=%0.1f got-a=%s" %
(got_radius, want_radius, average_radius, on_string, want_angle, got_angle))
if on_radius:
if on_radius_start_heading is None:
on_radius_start_heading = heading
average_radius = got_radius
circle_time_start = self.get_sim_time()
continue
if abs(on_radius_start_heading - heading) > want_angle: # FIXME
done_angle = True
if self.get_sim_time() - circle_time_start > min_circle_time:
done_time = True
if done_time and done_angle:
return
continue
if on_radius_start_heading is not None:
average_radius = 0.0
on_radius_start_heading = None
circle_time_start = 0
def test_fence_static(self):
ex = None
try:
self.progress("Checking for bizarre healthy-when-not-present-or-enabled")
self.assert_fence_sys_status(False, False, True)
self.load_fence("CMAC-fence.txt")
m = self.mav.recv_match(type='FENCE_STATUS', blocking=True, timeout=2)
if m is not None:
raise NotAchievedException("Got FENCE_STATUS unexpectedly");
self.drain_mav_unparsed()
self.set_parameter("FENCE_ACTION", mavutil.mavlink.FENCE_ACTION_NONE) # report only
self.assert_fence_sys_status(False, False, True)
self.set_parameter("FENCE_ACTION", mavutil.mavlink.FENCE_ACTION_RTL) # report only
self.assert_fence_sys_status(True, False, True)
self.mavproxy.send('fence enable\n')
self.mavproxy.expect("fence enabled")
self.assert_fence_sys_status(True, True, True)
m = self.mav.recv_match(type='FENCE_STATUS', blocking=True, timeout=2)
if m is None:
raise NotAchievedException("Did not get FENCE_STATUS");
if m.breach_status:
raise NotAchievedException("Breached fence unexpectedly (%u)" %
(m.breach_status))
self.mavproxy.send('fence disable\n')
self.mavproxy.expect("fence disabled")
self.assert_fence_sys_status(True, False, True)
self.set_parameter("FENCE_ACTION", mavutil.mavlink.FENCE_ACTION_NONE)
self.assert_fence_sys_status(False, False, True)
self.set_parameter("FENCE_ACTION", mavutil.mavlink.FENCE_ACTION_RTL)
self.assert_fence_sys_status(True, False, True)
self.mavproxy.send("fence clear\n")
self.mavproxy.expect("fence removed")
if self.get_parameter("FENCE_TOTAL") != 0:
raise NotAchievedException("Expected zero points remaining")
self.assert_fence_sys_status(False, False, True)
self.progress("Trying to enable fence with no points")
self.do_fence_enable(want_result=mavutil.mavlink.MAV_RESULT_FAILED)
# test a rather unfortunate behaviour:
self.progress("Killing a live fence with fence-clear")
self.load_fence("CMAC-fence.txt")
self.set_parameter("FENCE_ACTION", mavutil.mavlink.FENCE_ACTION_RTL)
self.do_fence_enable()
self.assert_fence_sys_status(True, True, True)
self.mavproxy.send("fence clear\n")
self.mavproxy.expect("fence removed")
if self.get_parameter("FENCE_TOTAL") != 0:
raise NotAchievedException("Expected zero points remaining")
self.assert_fence_sys_status(False, False, True)
except Exception as e:
self.progress("Exception caught:")
self.progress(self.get_exception_stacktrace(e))
ex = e
self.mavproxy.send('fence clear\n')
if ex is not None:
raise ex
def test_fence_breach_circle_at(self, loc, disable_on_breach=False):
ex = None
try:
self.load_fence("CMAC-fence.txt")
want_radius = 100
# when ArduPlane is fixed, remove this fudge factor
REALLY_BAD_FUDGE_FACTOR = 1.16
expected_radius = REALLY_BAD_FUDGE_FACTOR * want_radius
self.set_parameter("RTL_RADIUS", want_radius)
self.set_parameter("NAVL1_LIM_BANK", 60)
self.set_parameter("FENCE_ACTION", mavutil.mavlink.FENCE_ACTION_RTL)
self.do_fence_enable()
self.assert_fence_sys_status(True, True, True)
self.takeoff(alt=45, alt_max=300)
tstart = self.get_sim_time()
while True:
if self.get_sim_time() - tstart > 30:
raise NotAchievedException("Did not breach fence")
m = self.mav.recv_match(type='FENCE_STATUS', blocking=True, timeout=2)
if m is None:
raise NotAchievedException("Did not get FENCE_STATUS");
if m.breach_status == 0:
continue
# we've breached; check our state;
if m.breach_type != mavutil.mavlink.FENCE_BREACH_BOUNDARY:
raise NotAchievedException("Unexpected breach type %u" %
(m.breach_type,))
if m.breach_count == 0:
raise NotAchievedException("Unexpected breach count %u" %
(m.breach_count,))
self.assert_fence_sys_status(True, True, False)
break
if disable_on_breach:
self.do_fence_disable()
self.wait_circling_point_with_radius(loc, expected_radius)
self.disarm_vehicle(force=True)
self.reboot_sitl()
except Exception as e:
self.progress("Exception caught:")
self.progress(self.get_exception_stacktrace(e))
ex = e
self.mavproxy.send('fence clear\n')
if ex is not None:
raise ex
def test_fence_rtl(self):
self.progress("Testing FENCE_ACTION_RTL no rally point")
# have to disable the fence once we've breached or we breach
# it as part of the loiter-at-home!
self.test_fence_breach_circle_at(self.home_position_as_mav_location(),
disable_on_breach=True)
def test_fence_rtl_rally(self):
ex = None
target_system = 1
target_component = 1
try:
self.progress("Testing FENCE_ACTION_RTL with rally point")
self.wait_ready_to_arm()
loc = self.home_position_as_mav_location()
self.location_offset_ne(loc, 50, -50)
self.set_parameter("RALLY_TOTAL", 1)
self.mav.mav.rally_point_send(target_system,
target_component,
0, # sequence number
1, # total count
int(loc.lat * 1e7),
int(loc.lng * 1e7),
15,
0, # "break" alt?!
0, # "land dir"
0) # flags
self.delay_sim_time(1)
self.mavproxy.send("rally list\n")
self.test_fence_breach_circle_at(loc)
except Exception as e:
self.progress("Exception caught:")
self.progress(self.get_exception_stacktrace(e))
ex = e
self.mavproxy.send('rally clear\n')
if ex is not None:
raise ex
def test_parachute(self):
self.set_rc(9, 1000)
self.set_parameter("CHUTE_ENABLED", 1)
self.set_parameter("CHUTE_TYPE", 10)
self.set_parameter("SERVO9_FUNCTION", 27)
self.set_parameter("SIM_PARA_ENABLE", 1)
self.set_parameter("SIM_PARA_PIN", 9)
self.load_mission("plane-parachute-mission.txt")
self.mavproxy.send("wp set 1\n")
self.change_mode('AUTO')
self.wait_ready_to_arm()
self.arm_vehicle()
self.mavproxy.expect("BANG")
self.disarm_vehicle(force=True)
self.reboot_sitl()
def test_parachute_sinkrate(self):
self.set_rc(9, 1000)
self.set_parameter("CHUTE_ENABLED", 1)
self.set_parameter("CHUTE_TYPE", 10)
self.set_parameter("SERVO9_FUNCTION", 27)
self.set_parameter("SIM_PARA_ENABLE", 1)
self.set_parameter("SIM_PARA_PIN", 9)
self.set_parameter("CHUTE_CRT_SINK", 9)
self.progress("Takeoff")
self.takeoff(alt=300)
self.progress("Diving")
self.set_rc(2, 2000)
self.mavproxy.expect("BANG")
self.disarm_vehicle(force=True)
self.reboot_sitl()
def run_subtest(self, desc, func):
self.start_subtest(desc)
func()
def test_main_flight(self):
self.change_mode('MANUAL')
self.progress("Asserting we don't support transfer of fence via mission item protocol")
self.assert_no_capability(mavutil.mavlink.MAV_PROTOCOL_CAPABILITY_MISSION_FENCE)
# grab home position:
self.mav.recv_match(type='HOME_POSITION', blocking=True)
self.homeloc = self.mav.location()
self.run_subtest("Takeoff", self.takeoff)
self.run_subtest("Set Attitude Target", self.set_attitude_target)
self.run_subtest("Fly left circuit", self.fly_left_circuit)
self.run_subtest("Left roll", lambda: self.axial_left_roll(1))
self.run_subtest("Inside loop", self.inside_loop)
self.run_subtest("Stablize test", self.test_stabilize)
self.run_subtest("ACRO test", self.test_acro)
self.run_subtest("FBWB test", self.test_FBWB)
self.run_subtest("CRUISE test", lambda: self.test_FBWB(mode='CRUISE'))
self.run_subtest("RTL test", self.fly_RTL)
self.run_subtest("LOITER test", self.fly_LOITER)
self.run_subtest("CIRCLE test", self.fly_CIRCLE)
self.run_subtest("Mission test",
lambda: self.fly_mission("ap1.txt"))
def airspeed_autocal(self):
self.progress("Ensure no AIRSPEED_AUTOCAL on ground")
self.set_parameter("ARSPD_AUTOCAL", 1)
m = self.mav.recv_match(type='AIRSPEED_AUTOCAL',
blocking=True,
timeout=5)
if m is not None:
raise NotAchievedException("Got autocal on ground")
mission_filepath = "flaps.txt"
num_wp = self.load_mission(mission_filepath)
self.wait_ready_to_arm()
self.arm_vehicle()
self.change_mode("AUTO")
self.progress("Ensure AIRSPEED_AUTOCAL in air")
m = self.mav.recv_match(type='AIRSPEED_AUTOCAL',
blocking=True,
timeout=5)
self.wait_waypoint(7, num_wp-1, timeout=500)
self.wait_disarmed(timeout=120)
def deadreckoning_main(self, disable_airspeed_sensor=False):
self.gpi = None
self.simstate = None
self.last_print = 0
self.max_divergence = 0
def validate_global_position_int_against_simstate(mav, m):
if m.get_type() == 'GLOBAL_POSITION_INT':
self.gpi = m
elif m.get_type() == 'SIMSTATE':
self.simstate = m
if self.gpi is None:
return
if self.simstate is None:
return
divergence = self.get_distance_int(self.gpi, self.simstate)
max_allowed_divergence = 200
if time.time() - self.last_print > 1:
self.progress("position-estimate-divergence=%fm" % (divergence,))
self.last_print = time.time()
if divergence > max_allowed_divergence:
raise NotAchievedException("global-position-int diverged from simstate by >%fm" % (max_allowed_divergence,))
if divergence > self.max_divergence:
self.max_divergence = divergence
self.install_message_hook(validate_global_position_int_against_simstate)
try:
# wind is from the West:
self.set_parameter("SIM_WIND_DIR", 270)
# light winds:
self.set_parameter("SIM_WIND_SPD", 10)
if disable_airspeed_sensor:
self.set_parameter("ARSPD_USE", 0)
self.takeoff(50)
loc = self.mav.location()
loc.lat = -35.35690712
loc.lng = 149.17083386
self.run_cmd_int(
mavutil.mavlink.MAV_CMD_DO_REPOSITION,
0,
mavutil.mavlink.MAV_DO_REPOSITION_FLAGS_CHANGE_MODE,
0,
0,
int(loc.lat*1e7),
int(loc.lng*1e7),
100, # alt
frame=mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT,
)
self.wait_location(loc, accuracy=100)
self.progress("Stewing")
self.delay_sim_time(20)
self.set_parameter("SIM_GPS_DISABLE", 1)
self.progress("Roasting")
self.delay_sim_time(20)
self.change_mode("RTL")
self.wait_distance_to_home(100, 200, timeout=200)
self.set_parameter("SIM_GPS_DISABLE", 0)
self.delay_sim_time(10)
self.set_rc(3, 1000)
self.fly_home_land_and_disarm()
self.progress("max-divergence: %fm" % (self.max_divergence,))
finally:
self.remove_message_hook(validate_global_position_int_against_simstate)
def deadreckoning(self):
self.deadreckoning_main()
self.deadreckoning_main(disable_airspeed_sensor=True)
def sample_enable_parameter(self):
return "Q_ENABLE"
def test_rangefinder(self):
ex = None
self.context_push()
self.progress("Making sure we don't ordinarily get RANGEFINDER")
m = None
try:
m = self.mav.recv_match(type='RANGEFINDER',
blocking=True,
timeout=5)
except Exception as e:
self.progress("Caught exception: %s" %
self.get_exception_stacktrace(e))
if m is not None:
raise NotAchievedException("Received unexpected RANGEFINDER msg")
try:
self.set_analog_rangefinder_parameters()
self.reboot_sitl()
'''ensure rangefinder gives height-above-ground'''
self.load_mission("plane-gripper-mission.txt") # borrow this
self.mavproxy.send("wp set 1\n")
self.change_mode('AUTO')
self.wait_ready_to_arm()
self.arm_vehicle()
self.wait_waypoint(5, 5, max_dist=100)
rf = self.mav.recv_match(type="RANGEFINDER", timeout=1, blocking=True)
if rf is None:
raise NotAchievedException("Did not receive rangefinder message")
gpi = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True, timeout=1)
if gpi is None:
raise NotAchievedException("Did not receive GLOBAL_POSITION_INT message")
if abs(rf.distance - gpi.relative_alt/1000.0) > 3:
raise NotAchievedException("rangefinder alt (%s) disagrees with global-position-int.relative_alt (%s)" % (rf.distance, gpi.relative_alt/1000.0))
self.mavproxy.expect("Auto disarmed")
self.progress("Ensure RFND messages in log")
if not self.current_onboard_log_contains_message("RFND"):
raise NotAchievedException("No RFND messages in log")
except Exception as e:
self.progress("Exception caught:")
self.progress(self.get_exception_stacktrace(e))
ex = e
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def rc_defaults(self):
ret = super(AutoTestPlane, self).rc_defaults()
ret[3] = 1000
ret[8] = 1800
return ret
def default_mode(self):
return "MANUAL"
def test_pid_tuning(self):
self.change_mode("FBWA") # we don't update PIDs in MANUAL
super(AutoTestPlane, self).test_pid_tuning()
def test_setting_modes_via_auxswitches(self):
self.set_parameter("FLTMODE5", 1)
self.mavproxy.send('switch 1\n') # random mode
self.wait_heartbeat()
self.change_mode('MANUAL')
self.mavproxy.send('switch 5\n') # acro mode
self.wait_mode("CIRCLE")
self.set_rc(9, 1000)
self.set_rc(10, 1000)
self.set_parameter("RC9_OPTION", 4) # RTL
self.set_parameter("RC10_OPTION", 55) # guided
self.set_rc(9, 1900)
self.wait_mode("RTL")
self.set_rc(10, 1900)
self.wait_mode("GUIDED")
self.progress("resetting both switches - should go back to CIRCLE")
self.set_rc(9, 1000)
self.set_rc(10, 1000)
self.wait_mode("CIRCLE")
self.set_rc(9, 1900)
self.wait_mode("RTL")
self.set_rc(10, 1900)
self.wait_mode("GUIDED")
self.progress("Resetting switch should repoll mode switch")
self.set_rc(10, 1000) # this re-polls the mode switch
self.wait_mode("CIRCLE")
self.set_rc(9, 1000)
def wait_for_collision_threat_to_clear(self):
'''wait to get a "clear" collision message", then slurp remaining
messages'''
last_collision = self.get_sim_time()
while True:
now = self.get_sim_time()
if now - last_collision > 5:
return
self.progress("Waiting for collision message")
m = self.mav.recv_match(type='COLLISION', blocking=True, timeout=1)
self.progress("Got (%s)" % str(m))
if m is None:
continue
last_collision = now
def test_adsb_send_threatening_adsb_message(self, here):
self.progress("Sending ABSD_VEHICLE message")
self.mav.mav.adsb_vehicle_send(37, # ICAO address
int(here.lat * 1e7),
int(here.lng * 1e7),
mavutil.mavlink.ADSB_ALTITUDE_TYPE_PRESSURE_QNH,
int(here.alt*1000 + 10000), # 10m up
0, # heading in cdeg
0, # horizontal velocity cm/s
0, # vertical velocity cm/s
"bob".encode("ascii"), # callsign
mavutil.mavlink.ADSB_EMITTER_TYPE_LIGHT,
1, # time since last communication
65535, # flags
17 # squawk
)
def test_adsb(self):
self.context_push()
ex = None
try:
# message ADSB_VEHICLE 37 -353632614 1491652305 0 584070 0 0 0 "bob" 3 1 255 17
self.set_parameter("RC12_OPTION", 38) # avoid-adsb
self.set_rc(12, 2000)
self.set_parameter("ADSB_ENABLE", 1)
self.set_parameter("AVD_ENABLE", 1)
self.set_parameter("AVD_F_ACTION", mavutil.mavlink.MAV_COLLISION_ACTION_RTL)
self.reboot_sitl()
self.wait_ready_to_arm()
here = self.mav.location()
self.change_mode("FBWA")
self.delay_sim_time(2) # TODO: work out why this is required...
self.test_adsb_send_threatening_adsb_message(here)
self.progress("Waiting for collision message")
m = self.mav.recv_match(type='COLLISION', blocking=True, timeout=4)
if m is None:
raise NotAchievedException("Did not get collision message")
if m.threat_level != 2:
raise NotAchievedException("Expected some threat at least")
if m.action != mavutil.mavlink.MAV_COLLISION_ACTION_RTL:
raise NotAchievedException("Incorrect action; want=%u got=%u" %
(mavutil.mavlink.MAV_COLLISION_ACTION_RTL, m.action))
self.wait_mode("RTL")
self.progress("Sending far-away ABSD_VEHICLE message")
self.mav.mav.adsb_vehicle_send(37, # ICAO address
int(here.lat+1 * 1e7),
int(here.lng * 1e7),
mavutil.mavlink.ADSB_ALTITUDE_TYPE_PRESSURE_QNH,
int(here.alt*1000 + 10000), # 10m up
0, # heading in cdeg
0, # horizontal velocity cm/s
0, # vertical velocity cm/s
"bob".encode("ascii"), # callsign
mavutil.mavlink.ADSB_EMITTER_TYPE_LIGHT,
1, # time since last communication
65535, # flags
17 # squawk
)
self.wait_for_collision_threat_to_clear()
self.change_mode("FBWA")
self.progress("Disabling ADSB-avoidance with RC channel")
self.set_rc(12, 1000)
self.delay_sim_time(1) # let the switch get polled
self.test_adsb_send_threatening_adsb_message(here)
m = self.mav.recv_match(type='COLLISION', blocking=True, timeout=4)
print("Got (%s)" % str(m))
if m is not None:
raise NotAchievedException("Got collision message when I shouldn't have")
except Exception as e:
ex = e
self.context_pop()
self.reboot_sitl()
if ex is not None:
raise ex
def fly_do_guided_request(self, target_system=1, target_component=1):
self.progress("Takeoff")
self.takeoff(alt=50)
self.set_rc(3, 1500)
self.start_subtest("Ensure command bounced outside guided mode")
desired_relative_alt = 33
loc = self.mav.location()
self.location_offset_ne(loc, 300, 300)
loc.alt += desired_relative_alt
self.mav.mav.mission_item_int_send(
target_system,
target_component,
0, # seq
mavutil.mavlink.MAV_FRAME_GLOBAL,
mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,
2, # current - guided-mode request
0, # autocontinue
0, # p1
0, # p2
0, # p3
0, # p4
int(loc.lat *1e7), # latitude
int(loc.lng *1e7), # longitude
loc.alt, # altitude
mavutil.mavlink.MAV_MISSION_TYPE_MISSION)
m = self.mav.recv_match(type='MISSION_ACK', blocking=True, timeout=5)
if m is None:
raise NotAchievedException("Did not get MISSION_ACK")
if m.type != mavutil.mavlink.MAV_MISSION_ERROR:
raise NotAchievedException("Did not get appropriate error")
self.start_subtest("Enter guided and flying somewhere constant")
self.change_mode("GUIDED")
self.mav.mav.mission_item_int_send(
target_system,
target_component,
0, # seq
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT,
mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,
2, # current - guided-mode request
0, # autocontinue
0, # p1
0, # p2
0, # p3
0, # p4
int(loc.lat *1e7), # latitude
int(loc.lng *1e7), # longitude
desired_relative_alt, # altitude
mavutil.mavlink.MAV_MISSION_TYPE_MISSION)
m = self.mav.recv_match(type='MISSION_ACK', blocking=True, timeout=5)
if m is None:
raise NotAchievedException("Did not get MISSION_ACK")
if m.type != mavutil.mavlink.MAV_MISSION_ACCEPTED:
raise NotAchievedException("Did not get accepted response")
self.wait_location(loc, accuracy=100) # based on loiter radius
self.delay_sim_time(20)
self.wait_altitude(altitude_min=desired_relative_alt-3,
altitude_max=desired_relative_alt+3,
relative=True)
self.fly_home_land_and_disarm()
def LOITER(self):
self.takeoff(alt=200)
self.set_rc(3, 1500)
self.change_mode("LOITER")
self.progress("Doing a bit of loitering to start with")
tstart = self.get_sim_time()
while True:
now = self.get_sim_time_cached()
if now - tstart > 60:
break
m = self.mav.recv_match(type='VFR_HUD', blocking=True, timeout=5)
if m is None:
raise NotAchievedException("Did not get VFR_HUD")
new_throttle = m.throttle
alt = m.alt
m = self.mav.recv_match(type='ATTITUDE', blocking=True, timeout=5)
if m is None:
raise NotAchievedException("Did not get ATTITUDE")
pitch = math.degrees(m.pitch)
self.progress("Pitch:%f throttle:%u alt:%f" % (pitch, new_throttle, alt))
m = self.mav.recv_match(type='VFR_HUD', blocking=True, timeout=5)
if m is None:
raise NotAchievedException("Did not get VFR_HUD")
initial_throttle = m.throttle
initial_alt = m.alt
self.progress("Initial throttle: %u" % initial_throttle)
# pitch down, ensure throttle decreases:
rc2_max = self.get_parameter("RC2_MAX")
self.set_rc(2, rc2_max)
tstart = self.get_sim_time()
while True:
now = self.get_sim_time_cached()
'''stick-mixing is pushing the aircraft down. It doesn't want to go
down (the target loiter altitude hasn't changed), so it
tries to add energy by increasing the throttle.
'''
if now - tstart > 60:
raise NotAchievedException("Did not see increase in throttle")
m = self.mav.recv_match(type='VFR_HUD', blocking=True, timeout=5)
if m is None:
raise NotAchievedException("Did not get VFR_HUD")
new_throttle = m.throttle
alt = m.alt
m = self.mav.recv_match(type='ATTITUDE', blocking=True, timeout=5)
if m is None:
raise NotAchievedException("Did not get ATTITUDE")
pitch = math.degrees(m.pitch)
self.progress("Pitch:%f throttle:%u alt:%f" % (pitch, new_throttle, alt))
if new_throttle - initial_throttle > 20:
self.progress("Throttle delta achieved")
break
self.progress("Centering elevator and ensuring we get back to loiter altitude")
self.set_rc(2, 1500)
self.wait_altitude(initial_alt-1, initial_alt+1)
self.fly_home_land_and_disarm()
def CPUFailsafe(self):
'''In lockup Plane should copy RC inputs to RC outputs'''
self.plane_CPUFailsafe()
def test_large_missions(self):
self.load_mission("Kingaroy-vlarge.txt")
self.load_mission("Kingaroy-vlarge2.txt")
def fly_soaring(self):
model="plane-soaring"
self.customise_SITL_commandline([],
model=model,
defaults_filepath=self.model_defaults_filepath("ArduPlane",model),
wipe=True)
self.load_mission('CMAC-soar.txt')
self.mavproxy.send("wp set 1\n")
self.change_mode('AUTO')
self.wait_ready_to_arm()
self.arm_vehicle()
# Enable thermalling RC
rc_chan = 0
for i in range(8):
rcx_option = self.get_parameter('RC{0}_OPTION'.format(i+1))
if rcx_option==88:
rc_chan = i+1;
break
if rc_chan==0:
raise NotAchievedException("Did not find soaring enable channel option.")
self.send_set_rc(rc_chan, 1900)
# Use trim airspeed.
self.send_set_rc(3, 1500)
# Wait to detect thermal
self.progress("Waiting for thermal")
self.wait_mode('THERMAL',timeout=600)
# Wait to climb to SOAR_ALT_MAX
self.progress("Waiting for climb to max altitude")
alt_max = self.get_parameter('SOAR_ALT_MAX')
self.wait_altitude(alt_max-10, alt_max, timeout=600, relative=True)
# Wait for AUTO
self.progress("Waiting for AUTO mode")
self.wait_mode('AUTO')
# Disable thermals
self.set_parameter("SIM_THML_SCENARI", 0)
# Wait to descend to SOAR_ALT_MIN
self.progress("Waiting for glide to min altitude")
alt_min = self.get_parameter('SOAR_ALT_MIN')
self.wait_altitude(alt_min-10, alt_min, timeout=600, relative=True)
self.progress("Waiting for throttle up")
self.wait_servo_channel_value(3, 1200, timeout=2, comparator=operator.gt)
self.progress("Waiting for climb to cutoff altitude")
alt_ctf = self.get_parameter('SOAR_ALT_CUTOFF')
self.wait_altitude(alt_ctf-10, alt_ctf, timeout=600, relative=True)
# Allow time to suppress throttle and start descent.
self.delay_sim_time(20)
# Now set FBWB mode
self.change_mode('FBWB')
self.delay_sim_time(5)
# Now disable soaring (should hold altitude)
self.set_parameter("SOAR_ENABLE", 0)
self.delay_sim_time(10)
#And reenable. This should force throttle-down
self.set_parameter("SOAR_ENABLE", 1)
self.delay_sim_time(10)
# Now wait for descent and check throttle up
self.wait_altitude(alt_min-10, alt_min, timeout=600, relative=True)
self.progress("Waiting for climb")
self.wait_altitude(alt_ctf-10, alt_ctf, timeout=600, relative=True)
# Back to auto
self.change_mode('AUTO')
# Reenable thermals
self.set_parameter("SIM_THML_SCENARI", 1)
# Disable soaring using RC channel.
self.send_set_rc(rc_chan, 1100)
# Wait to get back to waypoint before thermal.
self.progress("Waiting to get back to position")
self.wait_current_waypoint(3,timeout=1200)
# Enable soaring with mode changes suppressed)
self.send_set_rc(rc_chan, 1500)
# Make sure this causes throttle down.
self.wait_servo_channel_value(3, 1200, timeout=2, comparator=operator.lt)
self.progress("Waiting for next WP with no thermalling")
self.wait_waypoint(4,4,timeout=1200,max_dist=120)
# Disarm
self.disarm_vehicle()
self.progress("Mission OK")
def fly_terrain_mission(self):
self.customise_SITL_commandline([], wipe=True)
self.mavproxy.send("wp set 1\n")
self.wait_ready_to_arm()
self.arm_vehicle()
self.fly_mission("ap-terrain.txt", mission_timeout=600)
def ekf_lane_switch(self):
self.context_push()
ex = None
# new lane swtich available only with EK3
self.set_parameter("EK3_ENABLE", 1)
self.set_parameter("EK2_ENABLE", 0)
self.set_parameter("AHRS_EKF_TYPE", 3)
self.set_parameter("EK3_AFFINITY", 15) # enable affinity for all sensors
self.set_parameter("EK3_IMU_MASK", 3) # use only 2 IMUs
self.set_parameter("GPS_TYPE2", 1)
self.set_parameter("SIM_GPS2_DISABLE", 0)
self.set_parameter("SIM_BARO2_DISABL", 0)
self.set_parameter("SIM_BARO_COUNT", 2)
self.set_parameter("ARSPD2_TYPE", 2)
self.set_parameter("ARSPD2_USE", 1)
self.set_parameter("ARSPD2_PIN", 2)
# some parameters need reboot to take effect
self.reboot_sitl()
self.lane_switches = []
# add an EKF lane switch hook
def statustext_hook(mav, message):
if message.get_type() != 'STATUSTEXT':
return
# example msg: EKF3 lane switch 1
if not message.text.startswith("EKF3 lane switch "):
return
newlane = int(message.text[-1])
self.lane_switches.append(newlane)
self.install_message_hook(statustext_hook)
# get flying
self.takeoff(alt=50)
self.change_mode('CIRCLE')
try:
#####################################################################################################################################################
self.progress("Checking EKF3 Lane Switching trigger from all sensors")
#####################################################################################################################################################
self.start_subtest("ACCELEROMETER: Change z-axis offset")
# create an accelerometer error by changing the Z-axis offset
self.context_collect("STATUSTEXT")
old_parameter = self.get_parameter("INS_ACCOFFS_Z")
self.wait_statustext(text="EKF3 lane switch", timeout=30, the_function=self.set_parameter("INS_ACCOFFS_Z", old_parameter + 5), check_context=True)
if self.lane_switches != [1]:
raise NotAchievedException("Expected lane switch 1, got %s" % str(self.lane_switches[-1]))
# Cleanup
self.set_parameter("INS_ACCOFFS_Z", old_parameter)
self.context_clear_collection("STATUSTEXT")
self.wait_heading(0, accuracy=10, timeout=60)
self.wait_heading(180, accuracy=10, timeout=60)
#####################################################################################################################################################
self.start_subtest("BAROMETER: Freeze to last measured value")
self.context_collect("STATUSTEXT")
# create a barometer error by inhibiting any pressure change while changing altitude
old_parameter = self.get_parameter("SIM_BARO2_FREEZE")
self.set_parameter("SIM_BARO2_FREEZE", 1)
self.wait_statustext(text="EKF3 lane switch", timeout=30, the_function=lambda: self.set_rc(2, 2000), check_context=True)
if self.lane_switches != [1, 0]:
raise NotAchievedException("Expected lane switch 0, got %s" % str(self.lane_switches[-1]))
# Cleanup
self.set_rc(2, 1500)
self.set_parameter("SIM_BARO2_FREEZE", old_parameter)
self.context_clear_collection("STATUSTEXT")
self.wait_heading(0, accuracy=10, timeout=60)
self.wait_heading(180, accuracy=10, timeout=60)
#####################################################################################################################################################
self.start_subtest("GPS: Apply GPS Velocity Error in NED")
self.context_push()
self.context_collect("STATUSTEXT")
# create a GPS velocity error by adding a random 2m/s noise on each axis
def sim_gps_verr():
self.set_parameter("SIM_GPS_VERR_X", self.get_parameter("SIM_GPS_VERR_X") + 2)
self.set_parameter("SIM_GPS_VERR_Y", self.get_parameter("SIM_GPS_VERR_Y") + 2)
self.set_parameter("SIM_GPS_VERR_Z", self.get_parameter("SIM_GPS_VERR_Z") + 2)
self.wait_statustext(text="EKF3 lane switch", timeout=30, the_function=sim_gps_verr(), check_context=True)
if self.lane_switches != [1, 0, 1]:
raise NotAchievedException("Expected lane switch 1, got %s" % str(self.lane_switches[-1]))
# Cleanup
self.context_pop()
self.context_clear_collection("STATUSTEXT")
self.wait_heading(0, accuracy=10, timeout=60)
self.wait_heading(180, accuracy=10, timeout=60)
#####################################################################################################################################################
self.start_subtest("MAGNETOMETER: Change X-Axis Offset")
self.context_collect("STATUSTEXT")
# create a magnetometer error by changing the X-axis offset
old_parameter = self.get_parameter("SIM_MAG2_OFS_X")
self.wait_statustext(text="EKF3 lane switch", timeout=30, the_function=self.set_parameter("SIM_MAG2_OFS_X", old_parameter + 150), check_context=True)
if self.lane_switches != [1, 0, 1, 0]:
raise NotAchievedException("Expected lane switch 0, got %s" % str(self.lane_switches[-1]))
# Cleanup
self.set_parameter("SIM_MAG2_OFS_X", old_parameter)
self.context_clear_collection("STATUSTEXT")
self.wait_heading(0, accuracy=10, timeout=60)
self.wait_heading(180, accuracy=10, timeout=60)
#####################################################################################################################################################
self.start_subtest("AIRSPEED: Fail to constant value")
self.context_push()
self.context_collect("STATUSTEXT")
# create an airspeed sensor error by freezing to the current airspeed then changing the groundspeed
old_parameter = self.get_parameter("SIM_ARSPD_FAIL")
m = self.mav.recv_match(type='VFR_HUD', blocking=True)
self.set_parameter("SIM_ARSPD_FAIL", m.airspeed)
def change_speed():
self.change_mode("GUIDED")
self.run_cmd_int(
mavutil.mavlink.MAV_CMD_DO_REPOSITION,
0,
0,
0,
0,
12345, # lat*1e7
12345, # lon*1e7
50 # alt
)
self.delay_sim_time(5)
new_target_groundspeed = m.groundspeed + 5
self.run_cmd(
mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED,
1, # groundspeed
new_target_groundspeed,
-1, # throttle / no change
0, # absolute values
0,
0,
0
)
self.wait_statustext(text="EKF3 lane switch", timeout=30, the_function=change_speed(), check_context=True)
if self.lane_switches != [1, 0, 1, 0, 1]:
raise NotAchievedException("Expected lane switch 1, got %s" % str(self.lane_switches[-1]))
# Cleanup
self.change_mode('CIRCLE')
self.context_pop()
self.context_clear_collection("STATUSTEXT")
self.wait_heading(0, accuracy=10, timeout=60)
self.wait_heading(180, accuracy=10, timeout=60)
#####################################################################################################################################################
self.progress("GYROSCOPE: Change Y-Axis Offset")
self.context_collect("STATUSTEXT")
# create a gyroscope error by changing the Y-axis offset
old_parameter = self.get_parameter("INS_GYR2OFFS_Y")
self.wait_statustext(text="EKF3 lane switch", timeout=30, the_function=self.set_parameter("INS_GYR2OFFS_Y", old_parameter + 1), check_context=True)
if self.lane_switches != [1, 0, 1, 0, 1, 0]:
raise NotAchievedException("Expected lane switch 0, got %s" % str(self.lane_switches[-1]))
# Cleanup
self.set_parameter("INS_GYR2OFFS_Y", old_parameter)
self.context_clear_collection("STATUSTEXT")
#####################################################################################################################################################
self.disarm_vehicle()
except Exception as e:
self.progress("Caught exception: %s" % self.get_exception_stacktrace(e))
ex = e
self.remove_message_hook(statustext_hook)
self.context_pop()
if ex is not None:
raise ex
def tests(self):
'''return list of all tests'''
ret = super(AutoTestPlane, self).tests()
ret.extend([
("AuxModeSwitch",
"Set modes via auxswitches",
self.test_setting_modes_via_auxswitches),
("TestRCCamera",
"Test RC Option - Camera Trigger",
self.test_rc_option_camera_trigger),
("TestRCRelay", "Test Relay RC Channel Option", self.test_rc_relay),
("ThrottleFailsafe",
"Fly throttle failsafe",
self.test_throttle_failsafe),
("ThrottleFailsafeFence",
"Fly fence survives throttle failsafe",
self.test_throttle_failsafe_fence),
("TestFlaps", "Flaps", self.fly_flaps),
("DO_CHANGE_SPEED", "Test mavlink DO_CHANGE_SPEED command", self.fly_do_change_speed),
("DO_REPOSITION",
"Test mavlink DO_REPOSITION command",
self.fly_do_reposition),
("GuidedRequest",
"Test handling of MISSION_ITEM in guided mode",
self.fly_do_guided_request),
("MainFlight",
"Lots of things in one flight",
self.test_main_flight),
("TestGripperMission",
"Test Gripper mission items",
self.test_gripper_mission),
("Parachute", "Test Parachute", self.test_parachute),
("ParachuteSinkRate", "Test Parachute (SinkRate triggering)", self.test_parachute_sinkrate),
("AIRSPEED_AUTOCAL", "Test AIRSPEED_AUTOCAL", self.airspeed_autocal),
("RangeFinder",
"Test RangeFinder Basic Functionality",
self.test_rangefinder),
("FenceStatic",
"Test Basic Fence Functionality",
self.test_fence_static),
("FenceRTL",
"Test Fence RTL",
self.test_fence_rtl),
("FenceRTLRally",
"Test Fence RTL Rally",
self.test_fence_rtl_rally),
("ADSB",
"Test ADSB",
self.test_adsb),
("Button",
"Test Buttons",
self.test_button),
("FRSkySPort",
"Test FrSky SPort mode",
self.test_frsky_sport),
("FRSkyPassThrough",
"Test FrSky PassThrough serial output",
self.test_frsky_passthrough),
("FRSkyD",
"Test FrSkyD serial output",
self.test_frsky_d),
("LTM",
"Test LTM serial output",
self.test_ltm),
("AdvancedFailsafe",
"Test Advanced Failsafe",
self.test_advanced_failsafe),
("LOITER",
"Test Loiter mode",
self.LOITER),
("DeepStall",
"Test DeepStall Landing",
self.fly_deepstall),
("LargeMissions",
"Test Manipulation of Large missions",
self.test_large_missions),
("Soaring",
"Test Soaring feature",
self.fly_soaring),
("Terrain",
"Test terrain following in mission",
self.fly_terrain_mission),
("Deadreckoning",
"Test deadreckoning support",
self.deadreckoning),
("EKFlaneswitch",
"Test EKF3 Affinity and Lane Switching",
self.ekf_lane_switch),
("LogUpload",
"Log upload",
self.log_upload),
])
return ret
def disabled_tests(self):
return {
"Button": "See https://github.com/ArduPilot/ardupilot/issues/15259",
}
| gpl-3.0 | -238,449,084,716,790,980 | 38.840973 | 161 | 0.547441 | false | 3.816308 | true | false | false |
akinaru/ffmpeg-image-sequencer | ffmpeg-appender-test.py | 1 | 3157 | #!/usr/bin/python
#####################################################################################
#####################################################################################
#
# title : ffmpeg-appender-test.py
# authors : Bertrand Martel
# copyrights : Copyright (c) 2015 Bertrand Martel
# license : The MIT License (MIT)
# date : 16/08/2015
# description : create video if not exist and append a series of image to this video taken from WEB
# usage : python ffmpeg-appender-test.py
#
#####################################################################################
#####################################################################################
import sys, getopt, os, subprocess
def main(argv):
output_file_name = "video_space"
temporary_file_name = "temp_space"
temporary_file_name_video = "temp_video"
picture_array = [ "https://upload.wikimedia.org/wikipedia/commons/4/4e/Anttlers101.jpg", \
"https://upload.wikimedia.org/wikipedia/commons/3/3b/NASA-SpiralGalaxyM101-20140505.jpg", \
"https://upload.wikimedia.org/wikipedia/commons/b/b0/Supernova_in_M101_2011-08-25.jpg", \
"http://1.1.1.5/bmi/images.nationalgeographic.com/wpf/media-live/photos/000/061/cache/earth-full-view_6125_990x742.jpg" ]
this_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(this_dir)
output_file_path = ''.join([this_dir , "/",output_file_name,".avi"])
temporary_file_path_avi = ''.join([this_dir,"/",temporary_file_name,".avi"])
temporary_file_name_jpg = ''.join([this_dir,"/",temporary_file_name,".jpg"])
temporary_file_name_video = ''.join([this_dir,"/",temporary_file_name_video,".avi"])
#remove files
try:
os.remove(output_file_path)
except OSError:
pass
try:
os.remove(temporary_file_path_avi)
except OSError:
pass
try:
os.remove(temporary_file_name_jpg)
except OSError:
pass
try:
os.remove(temporary_file_name_video)
except OSError:
pass
for picture in picture_array:
subprocess.call(["wget", picture, "-O", temporary_file_name_jpg])
subprocess.call(["ffmpeg -nostdin -v verbose -f image2 -pattern_type sequence -start_number 0 -r 1 -i " + temporary_file_name_jpg + " -s 1920x1080 " + temporary_file_path_avi],shell=True)
try:
os.remove(temporary_file_name_jpg)
except OSError:
pass
if os.path.exists(output_file_path):
# concat this video and former video
subprocess.call(['cd ' + this_dir + ' | ffmpeg -nostdin -v verbose -i "concat:' + output_file_name + '.avi|' + temporary_file_name + '.avi" -c copy ' + temporary_file_name_video],shell=True)
try:
os.remove(temporary_file_path_avi)
except OSError:
pass
try:
os.remove(output_file_path)
except OSError:
pass
os.rename(temporary_file_name_video, output_file_path)
else:
os.rename(temporary_file_path_avi, output_file_path)
if __name__ == "__main__":
main(sys.argv[1:])
__author__ = "Bertrand Martel"
__copyright__ = "Copyright 2015, Bertrand Martel"
__credits__ = ["Bertrand Martel"]
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Bertrand Martel"
__email__ = "[email protected]"
__status__ = "POC" | mit | -8,222,219,400,538,782,000 | 30.58 | 193 | 0.602471 | false | 3.095098 | false | false | false |
csangani/ReproducingSprout | extract_traces.py | 1 | 1317 | ## Create a network trace from the saturator output
import glob
import os
import sys
INPUT_PATH = 'raw_traces'
OUTPUT_PATH = 'cleaned_traces'
def extract_trace(filePath, targetFilePath):
with open(filePath) as f:
with open(targetFilePath, 'w+') as wf:
firstLine = True
for line in f:
value = long(line.lstrip('recv_time=').rstrip(',\n'))
if firstLine:
base = value
firstLine = False
value = (value - base) / 1000000
wf.write('%s\n' % value)
if __name__ == '__main__':
if len(sys.argv) >= 2:
source = sys.argv[1]
else:
source = INPUT_PATH
if len(sys.argv) >= 3:
destination = sys.argv[2]
else:
destination = OUTPUT_PATH
if not os.path.exists(destination):
os.makedirs(destination)
networks = glob.glob('%s/*' % source)
for network in networks:
if not os.path.exists(network.replace(source, destination)):
os.makedirs(network.replace(source, destination))
files = glob.glob('%s/*.rx' % network)
for file in files:
extract_trace(file, file.replace(source, destination).replace('.rx', '.pps'))
| mit | -2,875,549,895,375,812,000 | 27.630435 | 89 | 0.535308 | false | 4.115625 | false | false | false |
meshulam/sly | deps/shapely/geos.py | 1 | 25191 | """
Proxies for the libgeos_c shared lib, GEOS-specific exceptions, and utilities
"""
import os
import re
import sys
import atexit
import logging
import threading
from ctypes import CDLL, cdll, pointer, c_void_p, c_size_t, c_char_p, string_at
from ctypes.util import find_library
from . import ftools
from .ctypes_declarations import prototype, EXCEPTION_HANDLER_FUNCTYPE
# Add message handler to this module's logger
LOG = logging.getLogger(__name__)
if 'all' in sys.warnoptions:
# show GEOS messages in console with: python -W all
logging.basicConfig()
else:
# no handler messages shown
class NullHandler(logging.Handler):
def emit(self, record):
pass
LOG.addHandler(NullHandler())
# Find and load the GEOS and C libraries
# If this ever gets any longer, we'll break it into separate modules
def load_dll(libname, fallbacks=None):
lib = find_library(libname)
if lib is not None:
try:
return CDLL(lib)
except OSError:
pass
if fallbacks is not None:
for name in fallbacks:
try:
return CDLL(name)
except OSError:
# move on to the next fallback
pass
# No shared library was loaded. Raise OSError.
raise OSError(
"Could not find library %s or load any of its variants %s" % (
libname, fallbacks or []))
if sys.platform.startswith('linux'):
_lgeos = load_dll('geos_c', fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])
free = load_dll('c').free
free.argtypes = [c_void_p]
free.restype = None
elif sys.platform == 'darwin':
if hasattr(sys, 'frozen'):
# .app file from py2app
alt_paths = [os.path.join(os.environ['RESOURCEPATH'],
'..', 'Frameworks', 'libgeos_c.dylib')]
else:
alt_paths = [
# The Framework build from Kyng Chaos:
"/Library/Frameworks/GEOS.framework/Versions/Current/GEOS",
# macports
'/opt/local/lib/libgeos_c.dylib',
]
_lgeos = load_dll('geos_c', fallbacks=alt_paths)
free = load_dll('c').free
free.argtypes = [c_void_p]
free.restype = None
elif sys.platform == 'win32':
try:
egg_dlls = os.path.abspath(os.path.join(os.path.dirname(__file__),
"DLLs"))
wininst_dlls = os.path.abspath(os.__file__ + "../../../DLLs")
original_path = os.environ['PATH']
os.environ['PATH'] = "%s;%s;%s" % \
(egg_dlls, wininst_dlls, original_path)
_lgeos = CDLL("geos.dll")
except (ImportError, WindowsError, OSError):
raise
def free(m):
try:
cdll.msvcrt.free(m)
except WindowsError:
# XXX: See http://trac.gispython.org/projects/PCL/ticket/149
pass
elif sys.platform == 'sunos5':
_lgeos = load_dll('geos_c', fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])
free = CDLL('libc.so.1').free
free.argtypes = [c_void_p]
free.restype = None
else: # other *nix systems
_lgeos = load_dll('geos_c', fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])
free = load_dll('c', fallbacks=['libc.so.6']).free
free.argtypes = [c_void_p]
free.restype = None
def _geos_version():
# extern const char GEOS_DLL *GEOSversion();
GEOSversion = _lgeos.GEOSversion
GEOSversion.restype = c_char_p
GEOSversion.argtypes = []
#define GEOS_CAPI_VERSION "@VERSION@-CAPI-@CAPI_VERSION@"
geos_version_string = GEOSversion()
if sys.version_info[0] >= 3:
geos_version_string = geos_version_string.decode('ascii')
res = re.findall(r'(\d+)\.(\d+)\.(\d+)', geos_version_string)
assert len(res) == 2, res
geos_version = tuple(int(x) for x in res[0])
capi_version = tuple(int(x) for x in res[1])
return geos_version_string, geos_version, capi_version
geos_version_string, geos_version, geos_capi_version = _geos_version()
# If we have the new interface, then record a baseline so that we know what
# additional functions are declared in ctypes_declarations.
if geos_version >= (3, 1, 0):
start_set = set(_lgeos.__dict__)
# Apply prototypes for the libgeos_c functions
prototype(_lgeos, geos_version)
# If we have the new interface, automatically detect all function
# declarations, and declare their re-entrant counterpart.
if geos_version >= (3, 1, 0):
end_set = set(_lgeos.__dict__)
new_func_names = end_set - start_set
for func_name in new_func_names:
new_func_name = "%s_r" % func_name
if hasattr(_lgeos, new_func_name):
new_func = getattr(_lgeos, new_func_name)
old_func = getattr(_lgeos, func_name)
new_func.restype = old_func.restype
if old_func.argtypes is None:
# Handle functions that didn't take an argument before,
# finishGEOS.
new_func.argtypes = [c_void_p]
else:
new_func.argtypes = [c_void_p] + old_func.argtypes
if old_func.errcheck is not None:
new_func.errcheck = old_func.errcheck
# Handle special case.
_lgeos.initGEOS_r.restype = c_void_p
_lgeos.initGEOS_r.argtypes = \
[EXCEPTION_HANDLER_FUNCTYPE, EXCEPTION_HANDLER_FUNCTYPE]
_lgeos.finishGEOS_r.argtypes = [c_void_p]
# Exceptions
class ReadingError(Exception):
pass
class DimensionError(Exception):
pass
class TopologicalError(Exception):
pass
class PredicateError(Exception):
pass
def error_handler(fmt, *args):
if sys.version_info[0] >= 3:
fmt = fmt.decode('ascii')
args = [arg.decode('ascii') for arg in args]
LOG.error(fmt, *args)
def notice_handler(fmt, args):
if sys.version_info[0] >= 3:
fmt = fmt.decode('ascii')
args = args.decode('ascii')
LOG.warning(fmt, args)
error_h = EXCEPTION_HANDLER_FUNCTYPE(error_handler)
notice_h = EXCEPTION_HANDLER_FUNCTYPE(notice_handler)
class WKTReader(object):
_lgeos = None
_reader = None
def __init__(self, lgeos):
"""Create WKT Reader"""
self._lgeos = lgeos
self._reader = self._lgeos.GEOSWKTReader_create()
def __del__(self):
"""Destroy WKT Reader"""
if self._lgeos is not None:
self._lgeos.GEOSWKTReader_destroy(self._reader)
self._reader = None
self._lgeos = None
def read(self, text):
"""Returns geometry from WKT"""
if sys.version_info[0] >= 3:
text = text.encode('ascii')
geom = self._lgeos.GEOSWKTReader_read(self._reader, c_char_p(text))
if not geom:
raise ReadingError("Could not create geometry because of errors "
"while reading input.")
# avoid circular import dependency
from shapely.geometry.base import geom_factory
return geom_factory(geom)
class WKTWriter(object):
_lgeos = None
_writer = None
# Establish default output settings
defaults = {}
if geos_version >= (3, 3, 0):
defaults['trim'] = True
defaults['output_dimension'] = 3
# GEOS' defaults for methods without "get"
_trim = False
_rounding_precision = -1
_old_3d = False
@property
def trim(self):
"""Trimming of unnecessary decimals (default: True)"""
return getattr(self, '_trim')
@trim.setter
def trim(self, value):
self._trim = bool(value)
self._lgeos.GEOSWKTWriter_setTrim(self._writer, self._trim)
@property
def rounding_precision(self):
"""Rounding precision when writing the WKT.
A precision of -1 (default) disables it."""
return getattr(self, '_rounding_precision')
@rounding_precision.setter
def rounding_precision(self, value):
self._rounding_precision = int(value)
self._lgeos.GEOSWKTWriter_setRoundingPrecision(
self._writer, self._rounding_precision)
@property
def output_dimension(self):
"""Output dimension, either 2 or 3 (default)"""
return self._lgeos.GEOSWKTWriter_getOutputDimension(
self._writer)
@output_dimension.setter
def output_dimension(self, value):
self._lgeos.GEOSWKTWriter_setOutputDimension(
self._writer, int(value))
@property
def old_3d(self):
"""Show older style for 3D WKT, without 'Z' (default: False)"""
return getattr(self, '_old_3d')
@old_3d.setter
def old_3d(self, value):
self._old_3d = bool(value)
self._lgeos.GEOSWKTWriter_setOld3D(self._writer, self._old_3d)
def __init__(self, lgeos, **settings):
"""Create WKT Writer
Note: writer defaults are set differently for GEOS 3.3.0 and up.
For example, with 'POINT Z (1 2 3)':
newer: POINT Z (1 2 3)
older: POINT (1.0000000000000000 2.0000000000000000)
The older formatting can be achieved for GEOS 3.3.0 and up by setting
the properties:
trim = False
output_dimension = 2
"""
self._lgeos = lgeos
self._writer = self._lgeos.GEOSWKTWriter_create()
applied_settings = self.defaults.copy()
applied_settings.update(settings)
for name in applied_settings:
setattr(self, name, applied_settings[name])
def __setattr__(self, name, value):
"""Limit setting attributes"""
if hasattr(self, name):
object.__setattr__(self, name, value)
else:
raise AttributeError('%r object has no attribute %r' %
(self.__class__.__name__, name))
def __del__(self):
"""Destroy WKT Writer"""
if self._lgeos is not None:
self._lgeos.GEOSWKTWriter_destroy(self._writer)
self._writer = None
self._lgeos = None
def write(self, geom):
"""Returns WKT string for geometry"""
if geom is None or geom._geom is None:
raise ValueError("Null geometry supports no operations")
result = self._lgeos.GEOSWKTWriter_write(self._writer, geom._geom)
text = string_at(result)
lgeos.GEOSFree(result)
if sys.version_info[0] >= 3:
return text.decode('ascii')
else:
return text
class WKBReader(object):
_lgeos = None
_reader = None
def __init__(self, lgeos):
"""Create WKB Reader"""
self._lgeos = lgeos
self._reader = self._lgeos.GEOSWKBReader_create()
def __del__(self):
"""Destroy WKB Reader"""
if self._lgeos is not None:
self._lgeos.GEOSWKBReader_destroy(self._reader)
self._reader = None
self._lgeos = None
def read(self, data):
"""Returns geometry from WKB"""
geom = self._lgeos.GEOSWKBReader_read(
self._reader, c_char_p(data), c_size_t(len(data)))
if not geom:
raise ReadingError("Could not create geometry because of errors "
"while reading input.")
# avoid circular import dependency
from shapely import geometry
return geometry.base.geom_factory(geom)
def read_hex(self, data):
"""Returns geometry from WKB hex"""
if sys.version_info[0] >= 3:
data = data.encode('ascii')
geom = self._lgeos.GEOSWKBReader_readHEX(
self._reader, c_char_p(data), c_size_t(len(data)))
if not geom:
raise ReadingError("Could not create geometry because of errors "
"while reading input.")
# avoid circular import dependency
from shapely import geometry
return geometry.base.geom_factory(geom)
class WKBWriter(object):
_lgeos = None
_writer = None
# EndianType enum in ByteOrderValues.h
_ENDIAN_BIG = 0
_ENDIAN_LITTLE = 1
# Establish default output setting
defaults = {'output_dimension': 3}
@property
def output_dimension(self):
"""Output dimension, either 2 or 3 (default)"""
return self._lgeos.GEOSWKBWriter_getOutputDimension(self._writer)
@output_dimension.setter
def output_dimension(self, value):
self._lgeos.GEOSWKBWriter_setOutputDimension(
self._writer, int(value))
@property
def big_endian(self):
"""Byte order is big endian, True (default) or False"""
return (self._lgeos.GEOSWKBWriter_getByteOrder(self._writer) ==
self._ENDIAN_BIG)
@big_endian.setter
def big_endian(self, value):
self._lgeos.GEOSWKBWriter_setByteOrder(
self._writer, self._ENDIAN_BIG if value else self._ENDIAN_LITTLE)
@property
def include_srid(self):
"""Include SRID, True or False (default)"""
return bool(self._lgeos.GEOSWKBWriter_getIncludeSRID(self._writer))
@include_srid.setter
def include_srid(self, value):
self._lgeos.GEOSWKBWriter_setIncludeSRID(self._writer, bool(value))
def __init__(self, lgeos, **settings):
"""Create WKB Writer"""
self._lgeos = lgeos
self._writer = self._lgeos.GEOSWKBWriter_create()
applied_settings = self.defaults.copy()
applied_settings.update(settings)
for name in applied_settings:
setattr(self, name, applied_settings[name])
def __setattr__(self, name, value):
"""Limit setting attributes"""
if hasattr(self, name):
object.__setattr__(self, name, value)
else:
raise AttributeError('%r object has no attribute %r' %
(self.__class__.__name__, name))
def __del__(self):
"""Destroy WKB Writer"""
if self._lgeos is not None:
self._lgeos.GEOSWKBWriter_destroy(self._writer)
self._writer = None
self._lgeos = None
def write(self, geom):
"""Returns WKB byte string for geometry"""
if geom is None or geom._geom is None:
raise ValueError("Null geometry supports no operations")
size = c_size_t()
result = self._lgeos.GEOSWKBWriter_write(
self._writer, geom._geom, pointer(size))
data = string_at(result, size.value)
lgeos.GEOSFree(result)
return data
def write_hex(self, geom):
"""Returns WKB hex string for geometry"""
if geom is None or geom._geom is None:
raise ValueError("Null geometry supports no operations")
size = c_size_t()
result = self._lgeos.GEOSWKBWriter_writeHEX(
self._writer, geom._geom, pointer(size))
data = string_at(result, size.value)
lgeos.GEOSFree(result)
if sys.version_info[0] >= 3:
return data.decode('ascii')
else:
return data
# Errcheck functions for ctypes
def errcheck_wkb(result, func, argtuple):
'''Returns bytes from a C pointer'''
if not result:
return None
size_ref = argtuple[-1]
size = size_ref.contents
retval = string_at(result, size.value)[:]
lgeos.GEOSFree(result)
return retval
def errcheck_just_free(result, func, argtuple):
'''Returns string from a C pointer'''
retval = string_at(result)
lgeos.GEOSFree(result)
if sys.version_info[0] >= 3:
return retval.decode('ascii')
else:
return retval
def errcheck_predicate(result, func, argtuple):
'''Result is 2 on exception, 1 on True, 0 on False'''
if result == 2:
raise PredicateError("Failed to evaluate %s" % repr(func))
return result
class LGEOSBase(threading.local):
"""Proxy for GEOS C API
This is a base class. Do not instantiate.
"""
methods = {}
def __init__(self, dll):
self._lgeos = dll
self.geos_handle = None
def __del__(self):
"""Cleanup GEOS related processes"""
if self._lgeos is not None:
self._lgeos.finishGEOS()
self._lgeos = None
self.geos_handle = None
class LGEOS300(LGEOSBase):
"""Proxy for GEOS 3.0.0-CAPI-1.4.1
"""
geos_version = (3, 0, 0)
geos_capi_version = (1, 4, 0)
def __init__(self, dll):
super(LGEOS300, self).__init__(dll)
self.geos_handle = self._lgeos.initGEOS(notice_h, error_h)
keys = list(self._lgeos.__dict__.keys())
for key in keys:
setattr(self, key, getattr(self._lgeos, key))
self.GEOSFree = self._lgeos.free
# Deprecated
self.GEOSGeomToWKB_buf.errcheck = errcheck_wkb
self.GEOSGeomToWKT.errcheck = errcheck_just_free
self.GEOSRelate.errcheck = errcheck_just_free
for pred in (
self.GEOSDisjoint,
self.GEOSTouches,
self.GEOSIntersects,
self.GEOSCrosses,
self.GEOSWithin,
self.GEOSContains,
self.GEOSOverlaps,
self.GEOSEquals,
self.GEOSEqualsExact,
self.GEOSisEmpty,
self.GEOSisValid,
self.GEOSisSimple,
self.GEOSisRing,
self.GEOSHasZ):
pred.errcheck = errcheck_predicate
self.methods['area'] = self.GEOSArea
self.methods['boundary'] = self.GEOSBoundary
self.methods['buffer'] = self.GEOSBuffer
self.methods['centroid'] = self.GEOSGetCentroid
self.methods['representative_point'] = self.GEOSPointOnSurface
self.methods['convex_hull'] = self.GEOSConvexHull
self.methods['distance'] = self.GEOSDistance
self.methods['envelope'] = self.GEOSEnvelope
self.methods['length'] = self.GEOSLength
self.methods['has_z'] = self.GEOSHasZ
self.methods['is_empty'] = self.GEOSisEmpty
self.methods['is_ring'] = self.GEOSisRing
self.methods['is_simple'] = self.GEOSisSimple
self.methods['is_valid'] = self.GEOSisValid
self.methods['disjoint'] = self.GEOSDisjoint
self.methods['touches'] = self.GEOSTouches
self.methods['intersects'] = self.GEOSIntersects
self.methods['crosses'] = self.GEOSCrosses
self.methods['within'] = self.GEOSWithin
self.methods['contains'] = self.GEOSContains
self.methods['overlaps'] = self.GEOSOverlaps
self.methods['equals'] = self.GEOSEquals
self.methods['equals_exact'] = self.GEOSEqualsExact
self.methods['relate'] = self.GEOSRelate
self.methods['difference'] = self.GEOSDifference
self.methods['symmetric_difference'] = self.GEOSSymDifference
self.methods['union'] = self.GEOSUnion
self.methods['intersection'] = self.GEOSIntersection
self.methods['simplify'] = self.GEOSSimplify
self.methods['topology_preserve_simplify'] = \
self.GEOSTopologyPreserveSimplify
class LGEOS310(LGEOSBase):
"""Proxy for GEOS 3.1.0-CAPI-1.5.0
"""
geos_version = (3, 1, 0)
geos_capi_version = (1, 5, 0)
def __init__(self, dll):
super(LGEOS310, self).__init__(dll)
self.geos_handle = self._lgeos.initGEOS_r(notice_h, error_h)
keys = list(self._lgeos.__dict__.keys())
for key in [x for x in keys if not x.endswith('_r')]:
if key + '_r' in keys:
reentr_func = getattr(self._lgeos, key + '_r')
attr = ftools.partial(reentr_func, self.geos_handle)
attr.__name__ = reentr_func.__name__
setattr(self, key, attr)
else:
setattr(self, key, getattr(self._lgeos, key))
if not hasattr(self, 'GEOSFree'):
# GEOS < 3.1.1
self.GEOSFree = self._lgeos.free
# Deprecated
self.GEOSGeomToWKB_buf.func.errcheck = errcheck_wkb
self.GEOSGeomToWKT.func.errcheck = errcheck_just_free
self.GEOSRelate.func.errcheck = errcheck_just_free
for pred in (
self.GEOSDisjoint,
self.GEOSTouches,
self.GEOSIntersects,
self.GEOSCrosses,
self.GEOSWithin,
self.GEOSContains,
self.GEOSOverlaps,
self.GEOSEquals,
self.GEOSEqualsExact,
self.GEOSisEmpty,
self.GEOSisValid,
self.GEOSisSimple,
self.GEOSisRing,
self.GEOSHasZ):
pred.func.errcheck = errcheck_predicate
self.GEOSisValidReason.func.errcheck = errcheck_just_free
self.methods['area'] = self.GEOSArea
self.methods['boundary'] = self.GEOSBoundary
self.methods['buffer'] = self.GEOSBuffer
self.methods['centroid'] = self.GEOSGetCentroid
self.methods['representative_point'] = self.GEOSPointOnSurface
self.methods['convex_hull'] = self.GEOSConvexHull
self.methods['distance'] = self.GEOSDistance
self.methods['envelope'] = self.GEOSEnvelope
self.methods['length'] = self.GEOSLength
self.methods['has_z'] = self.GEOSHasZ
self.methods['is_empty'] = self.GEOSisEmpty
self.methods['is_ring'] = self.GEOSisRing
self.methods['is_simple'] = self.GEOSisSimple
self.methods['is_valid'] = self.GEOSisValid
self.methods['disjoint'] = self.GEOSDisjoint
self.methods['touches'] = self.GEOSTouches
self.methods['intersects'] = self.GEOSIntersects
self.methods['crosses'] = self.GEOSCrosses
self.methods['within'] = self.GEOSWithin
self.methods['contains'] = self.GEOSContains
self.methods['overlaps'] = self.GEOSOverlaps
self.methods['equals'] = self.GEOSEquals
self.methods['equals_exact'] = self.GEOSEqualsExact
self.methods['relate'] = self.GEOSRelate
self.methods['difference'] = self.GEOSDifference
self.methods['symmetric_difference'] = self.GEOSSymDifference
self.methods['union'] = self.GEOSUnion
self.methods['intersection'] = self.GEOSIntersection
self.methods['prepared_intersects'] = self.GEOSPreparedIntersects
self.methods['prepared_contains'] = self.GEOSPreparedContains
self.methods['prepared_contains_properly'] = \
self.GEOSPreparedContainsProperly
self.methods['prepared_covers'] = self.GEOSPreparedCovers
self.methods['simplify'] = self.GEOSSimplify
self.methods['topology_preserve_simplify'] = \
self.GEOSTopologyPreserveSimplify
self.methods['cascaded_union'] = self.GEOSUnionCascaded
class LGEOS311(LGEOS310):
"""Proxy for GEOS 3.1.1-CAPI-1.6.0
"""
geos_version = (3, 1, 1)
geos_capi_version = (1, 6, 0)
def __init__(self, dll):
super(LGEOS311, self).__init__(dll)
class LGEOS320(LGEOS311):
"""Proxy for GEOS 3.2.0-CAPI-1.6.0
"""
geos_version = (3, 2, 0)
geos_capi_version = (1, 6, 0)
def __init__(self, dll):
super(LGEOS320, self).__init__(dll)
self.methods['parallel_offset'] = self.GEOSSingleSidedBuffer
self.methods['project'] = self.GEOSProject
self.methods['project_normalized'] = self.GEOSProjectNormalized
self.methods['interpolate'] = self.GEOSInterpolate
self.methods['interpolate_normalized'] = \
self.GEOSInterpolateNormalized
self.methods['buffer_with_style'] = self.GEOSBufferWithStyle
class LGEOS330(LGEOS320):
"""Proxy for GEOS 3.3.0-CAPI-1.7.0
"""
geos_version = (3, 3, 0)
geos_capi_version = (1, 7, 0)
def __init__(self, dll):
super(LGEOS330, self).__init__(dll)
# GEOS 3.3.8 from homebrew has, but doesn't advertise
# GEOSPolygonize_full. We patch it in explicitly here.
key = 'GEOSPolygonize_full'
func = getattr(self._lgeos, key + '_r')
attr = ftools.partial(func, self.geos_handle)
attr.__name__ = func.__name__
setattr(self, key, attr)
for pred in (self.GEOSisClosed,):
pred.func.errcheck = errcheck_predicate
self.methods['unary_union'] = self.GEOSUnaryUnion
self.methods['is_closed'] = self.GEOSisClosed
self.methods['cascaded_union'] = self.methods['unary_union']
self.methods['snap'] = self.GEOSSnap
class LGEOS340(LGEOS330):
"""Proxy for GEOS 3.4.0-CAPI-1.8.0
"""
geos_version = (3, 4, 0)
geos_capi_version = (1, 8, 0)
def __init__(self, dll):
super(LGEOS340, self).__init__(dll)
self.methods['delaunay_triangulation'] = self.GEOSDelaunayTriangulation
self.methods['nearest_points'] = self.GEOSNearestPoints
if geos_version >= (3, 4, 0):
L = LGEOS340
elif geos_version >= (3, 3, 0):
L = LGEOS330
elif geos_version >= (3, 2, 0):
L = LGEOS320
elif geos_version >= (3, 1, 1):
L = LGEOS311
elif geos_version >= (3, 1, 0):
L = LGEOS310
else:
L = LGEOS300
lgeos = L(_lgeos)
def cleanup(proxy):
del proxy
atexit.register(cleanup, lgeos)
| mit | 9,089,816,898,955,361,000 | 32.277411 | 79 | 0.596403 | false | 3.756487 | false | false | false |
philipgian/pre-commit | tests/make_archives_test.py | 1 | 1979 | from __future__ import absolute_import
from __future__ import unicode_literals
import os.path
import tarfile
import mock
import pytest
from pre_commit import make_archives
from pre_commit.util import cmd_output
from pre_commit.util import cwd
from testing.fixtures import git_dir
from testing.util import get_head_sha
from testing.util import skipif_slowtests_false
def test_make_archive(tempdir_factory):
output_dir = tempdir_factory.get()
git_path = git_dir(tempdir_factory)
# Add a files to the git directory
with cwd(git_path):
cmd_output('touch', 'foo')
cmd_output('git', 'add', '.')
cmd_output('git', 'commit', '-m', 'foo')
# We'll use this sha
head_sha = get_head_sha('.')
# And check that this file doesn't exist
cmd_output('touch', 'bar')
cmd_output('git', 'add', '.')
cmd_output('git', 'commit', '-m', 'bar')
# Do the thing
archive_path = make_archives.make_archive(
'foo', git_path, head_sha, output_dir,
)
assert archive_path == os.path.join(output_dir, 'foo.tar.gz')
assert os.path.exists(archive_path)
extract_dir = tempdir_factory.get()
# Extract the tar
with tarfile.open(archive_path) as tf:
tf.extractall(extract_dir)
# Verify the contents of the tar
assert os.path.exists(os.path.join(extract_dir, 'foo'))
assert os.path.exists(os.path.join(extract_dir, 'foo', 'foo'))
assert not os.path.exists(os.path.join(extract_dir, 'foo', '.git'))
assert not os.path.exists(os.path.join(extract_dir, 'foo', 'bar'))
@skipif_slowtests_false
@pytest.mark.integration
def test_main(tempdir_factory):
path = tempdir_factory.get()
# Don't actually want to make these in the current repo
with mock.patch.object(make_archives, 'RESOURCES_DIR', path):
make_archives.main()
for archive, _, _ in make_archives.REPOS:
assert os.path.exists(os.path.join(path, archive + '.tar.gz'))
| mit | -4,190,765,153,830,089,700 | 29.921875 | 71 | 0.656897 | false | 3.417962 | true | false | false |
slimta/python-slimta | slimta/util/__init__.py | 1 | 4971 | # Copyright (c) 2016 Ian C. Good
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
"""Package containing a variety of useful modules utilities that didn't really
belong anywhere else.
"""
from __future__ import absolute_import
from gevent import socket
__all__ = ['build_ipv4_socket_creator', 'create_connection_ipv4',
'create_listeners']
def build_ipv4_socket_creator(only_ports=None):
"""Returns a function that will act like
:py:func:`socket.create_connection` but only using IPv4 addresses. This
function can be used as the ``socket_creator`` argument to some classes
like :class:`~slimta.relay.smtp.mx.MxSmtpRelay`.
:param only_ports: If given, can be a list to limit which ports are
restricted to IPv4. Connections to all other ports may
be IPv6.
"""
def socket_creator(*args, **kwargs):
return create_connection_ipv4(*args, only_ports=only_ports, **kwargs)
return socket_creator
def create_connection_ipv4(address, timeout=None, source_address=None,
only_ports=None):
"""Attempts to mimick to :py:func:`socket.create_connection`, but
connections are only made to IPv4 addresses.
:param only_ports: If given, can be a list to limit which ports are
restricted to IPv4. Connections to all other ports may
be IPv6.
"""
host, port = address
if only_ports and port not in only_ports:
return socket.create_connection(address, timeout, source_address)
last_exc = None
for res in socket.getaddrinfo(host, port, socket.AF_INET):
_, _, _, _, sockaddr = res
try:
return socket.create_connection(sockaddr, timeout, source_address)
except socket.error as exc:
last_exc = exc
if last_exc is not None:
raise last_exc
else:
raise socket.error('getaddrinfo returns an empty list')
def create_listeners(address,
family=socket.AF_UNSPEC,
socktype=socket.SOCK_STREAM,
proto=socket.IPPROTO_IP):
"""Uses :func:`socket.getaddrinfo` to create listening sockets for
available socket parameters. For example, giving *address* as
``('localhost', 80)`` on a system with IPv6 would return one socket bound
to ``127.0.0.1`` and one bound to ``::1`.
May also be used for ``socket.AF_UNIX`` with a file path to produce a
single unix domain socket listening on that path.
:param address: A ``(host, port)`` tuple to listen on.
:param family: the socket family, default ``AF_UNSPEC``.
:param socktype: the socket type, default ``SOCK_STREAM``.
:param proto: the socket protocol, default ``IPPROTO_IP``.
"""
if family == socket.AF_UNIX:
sock = socket.socket(family, socktype, proto)
_init_socket(sock, address)
return [sock]
elif not isinstance(address, tuple) or len(address) != 2:
raise ValueError(address)
flags = socket.AI_PASSIVE
host, port = address
listeners = []
last_exc = None
for res in socket.getaddrinfo(host, port, family, socktype, proto, flags):
fam, typ, prt, _, sockaddr = res
try:
sock = socket.socket(fam, typ, prt)
_init_socket(sock, sockaddr)
except socket.error as exc:
last_exc = exc
else:
listeners.append(sock)
if last_exc and not listeners:
raise last_exc
return listeners
def _init_socket(sock, sockaddr):
try:
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
except socket.error:
pass
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except socket.error:
pass
sock.setblocking(0)
sock.bind(sockaddr)
if sock.type != socket.SOCK_DGRAM:
sock.listen(socket.SOMAXCONN)
# vim:et:fdm=marker:sts=4:sw=4:ts=4
| mit | 1,704,426,083,830,367,700 | 36.097015 | 79 | 0.662442 | false | 4.028363 | false | false | false |
jeromecc/doctoctocbot | src/crowdfunding/migrations/0013_tiers.py | 1 | 1118 | # Generated by Django 2.0.13 on 2019-02-25 05:21
from decimal import Decimal
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('crowdfunding', '0012_auto_20190224_0523'),
]
operations = [
migrations.CreateModel(
name='Tiers',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('tag', models.CharField(max_length=191)),
('description', models.CharField(max_length=191)),
('emoji', models.CharField(blank=True, max_length=4)),
('image', models.ImageField(blank=True, upload_to='')),
('min', models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=12)),
('max', models.DecimalField(decimal_places=2, default=Decimal('Infinity'), max_digits=12)),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='crowdfunding.Project')),
],
),
]
| mpl-2.0 | -3,936,454,583,790,252,500 | 38.928571 | 119 | 0.601073 | false | 4.007168 | false | false | false |
yanni4night/ursa-django | app/settings.py | 1 | 2208 | """
Django settings for ursa-django project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'dev')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'uq==k2a4+j^3i3)wns^+3%9)ww+eysjo0)-sg(hu5q$6=uqg^+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'app.urls'
WSGI_APPLICATION = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'zh-cn'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = False
USE_L10N = False
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_DIRS = [os.path.join(PROJECT_ROOT, 'templates')] | mit | 2,840,151,740,766,177,000 | 24.988235 | 84 | 0.717391 | false | 3.190751 | false | false | false |
iotaledger/iota.lib.py | iota/multisig/commands/prepare_multisig_transfer.py | 1 | 5102 | from typing import List, Optional
import filters as f
from iota import Address, ProposedTransaction
from iota.commands import FilterCommand, RequestFilter
from iota.commands.core import GetBalancesCommand
from iota.exceptions import with_context
from iota.filters import Trytes
from iota.multisig.transaction import ProposedMultisigBundle
from iota.multisig.types import MultisigAddress
__all__ = [
'PrepareMultisigTransferCommand',
]
class PrepareMultisigTransferCommand(FilterCommand):
"""
Implements `prepare_multisig_transfer` multisig API command.
References:
- :py:meth:`iota.multisig.api.MultisigIota.prepare_multisig_transfer`
"""
command = 'prepareMultisigTransfer'
def get_request_filter(self) -> 'PrepareMultisigTransferRequestFilter':
return PrepareMultisigTransferRequestFilter()
def get_response_filter(self):
pass
async def _execute(self, request: dict) -> dict:
change_address: Optional[Address] = request['changeAddress']
multisig_input: MultisigAddress = request['multisigInput']
transfers: List[ProposedTransaction] = request['transfers']
bundle = ProposedMultisigBundle(transfers)
want_to_spend = bundle.balance
if want_to_spend > 0:
gb_response = await GetBalancesCommand(self.adapter)(
addresses=[multisig_input],
)
multisig_input.balance = gb_response['balances'][0]
if multisig_input.balance < want_to_spend:
raise with_context(
exc=ValueError(
'Insufficient balance; found {found}, need {need} '
'(``exc.context`` has more info).'.format(
found=multisig_input.balance,
need=want_to_spend,
),
),
# The structure of this context object is intended
# to match the one from ``PrepareTransferCommand``.
context={
'available_to_spend': multisig_input.balance,
'confirmed_inputs': [multisig_input],
'request': request,
'want_to_spend': want_to_spend,
},
)
bundle.add_inputs([multisig_input])
if bundle.balance < 0:
if change_address:
bundle.send_unspent_inputs_to(change_address)
else:
#
# Unlike :py:meth:`iota.api.Iota.prepare_transfer`
# where all of the inputs are owned by the same
# seed, creating a multisig transfer usually
# involves multiple people.
#
# It would be unfair to the participants of the
# transaction if we were to automatically generate a
# change address using the seed of whoever happened
# to invoke the
# :py:meth:`MultisigIota.prepare_multisig_transfer`
# method!
#
raise with_context(
exc=ValueError(
'Bundle has unspent inputs, '
'but no change address specified.',
),
context={
'available_to_spend': multisig_input.balance,
'balance': bundle.balance,
'confirmed_inputs': [multisig_input],
'request': request,
'want_to_spend': want_to_spend,
},
)
else:
raise with_context(
exc=ValueError(
'Use ``prepare_transfer`` '
'to create a bundle without spending IOTAs.',
),
context={
'request': request,
},
)
bundle.finalize()
# Return the bundle with inputs unsigned.
return {
'trytes': bundle.as_tryte_strings(),
}
class PrepareMultisigTransferRequestFilter(RequestFilter):
def __init__(self) -> None:
super(PrepareMultisigTransferRequestFilter, self).__init__(
{
'changeAddress': Trytes(Address),
'multisigInput': f.Required | f.Type(MultisigAddress),
'transfers':
f.Required | f.Array | f.FilterRepeater(
f.Required | f.Type(ProposedTransaction),
),
},
allow_missing_keys={
'changeAddress',
},
)
| mit | -2,375,090,809,166,574,000 | 35.971014 | 83 | 0.488828 | false | 5.232821 | false | false | false |
alexis-roche/nipy | nipy/testing/__init__.py | 2 | 1369 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""The testing directory contains a small set of imaging files to be
used for doctests only. More thorough tests and example data will be
stored in a nipy data packages that you can download separately.
.. note:
We use the ``nose`` testing framework for tests.
Nose is a dependency for the tests, but should not be a dependency
for running the algorithms in the NIPY library. This file should
import without nose being present on the python path.
Examples
--------
>>> from nipy.testing import funcfile
>>> from nipy.io.api import load_image
>>> img = load_image(funcfile)
>>> img.shape
(17, 21, 3, 20)
"""
from __future__ import absolute_import
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
# Overwrites numpy.testing.Tester
from .nosetester import NipyNoseTester as Tester
test = Tester().test
bench = Tester().bench
from . import decorators as dec
# Allow failed import of nose if not now running tests
try:
from nose.tools import assert_true, assert_false
except ImportError:
pass
| bsd-3-clause | -6,188,143,799,394,715,000 | 26.38 | 73 | 0.723156 | false | 3.413965 | true | false | false |
openstack/mistral | mistral/api/controllers/v2/execution.py | 1 | 17181 | # Copyright 2013 - Mirantis, Inc.
# Copyright 2015 - StackStorm, Inc.
# Copyright 2015 Huawei Technologies Co., Ltd.
# Copyright 2016 - Brocade Communications Systems, Inc.
# Copyright 2018 - Extreme Networks, Inc.
# Copyright 2019 - NetCracker Technology Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from oslo_log import log as logging
from oslo_utils import uuidutils
from pecan import rest
from wsme import types as wtypes
import wsmeext.pecan as wsme_pecan
from mistral.api import access_control as acl
from mistral.api.controllers.v2 import execution_report
from mistral.api.controllers.v2 import resources
from mistral.api.controllers.v2 import sub_execution
from mistral.api.controllers.v2 import task
from mistral.api.controllers.v2 import types
from mistral import context
from mistral.db.v2 import api as db_api
from mistral.db.v2.sqlalchemy import models as db_models
from mistral import exceptions as exc
from mistral.rpc import clients as rpc
from mistral.services import workflows as wf_service
from mistral.utils import filter_utils
from mistral.utils import rest_utils
from mistral.workflow import data_flow
from mistral.workflow import states
from mistral_lib.utils import merge_dicts
LOG = logging.getLogger(__name__)
STATE_TYPES = wtypes.Enum(
str,
states.IDLE,
states.RUNNING,
states.SUCCESS,
states.ERROR,
states.PAUSED,
states.CANCELLED
)
def _get_workflow_execution_resource_with_output(wf_ex):
rest_utils.load_deferred_fields(wf_ex, ['params', 'input', 'output'])
return resources.Execution.from_db_model(wf_ex)
def _get_workflow_execution_resource(wf_ex):
rest_utils.load_deferred_fields(wf_ex, ['params', 'input'])
return resources.Execution.from_db_model(wf_ex)
# Use retries to prevent possible failures.
@rest_utils.rest_retry_on_db_error
def _get_workflow_execution(id, must_exist=True):
with db_api.transaction():
if must_exist:
wf_ex = db_api.get_workflow_execution(id)
else:
wf_ex = db_api.load_workflow_execution(id)
return rest_utils.load_deferred_fields(
wf_ex,
['params', 'input', 'output', 'context', 'spec']
)
# TODO(rakhmerov): Make sure to make all needed renaming on public API.
class ExecutionsController(rest.RestController):
tasks = task.ExecutionTasksController()
report = execution_report.ExecutionReportController()
executions = sub_execution.SubExecutionsController()
@rest_utils.wrap_wsme_controller_exception
@wsme_pecan.wsexpose(resources.Execution, wtypes.text)
def get(self, id):
"""Return the specified Execution.
:param id: UUID of execution to retrieve.
"""
acl.enforce("executions:get", context.ctx())
LOG.debug("Fetch execution [id=%s]", id)
wf_ex = _get_workflow_execution(id)
resource = resources.Execution.from_db_model(wf_ex)
resource.published_global = (
data_flow.get_workflow_execution_published_global(wf_ex)
)
return resource
@rest_utils.wrap_wsme_controller_exception
@wsme_pecan.wsexpose(
resources.Execution,
wtypes.text,
body=resources.Execution
)
def put(self, id, wf_ex):
"""Update the specified workflow execution.
:param id: UUID of execution to update.
:param wf_ex: Execution object.
"""
acl.enforce('executions:update', context.ctx())
LOG.debug('Update execution [id=%s, execution=%s]', id, wf_ex)
@rest_utils.rest_retry_on_db_error
def _compute_delta(wf_ex):
with db_api.transaction():
# ensure that workflow execution exists
db_api.get_workflow_execution(
id,
fields=(db_models.WorkflowExecution.id,)
)
delta = {}
if wf_ex.state:
delta['state'] = wf_ex.state
if wf_ex.description:
delta['description'] = wf_ex.description
if wf_ex.params and wf_ex.params.get('env'):
delta['env'] = wf_ex.params.get('env')
# Currently we can change only state, description, or env.
if len(delta.values()) <= 0:
raise exc.InputException(
'The property state, description, or env '
'is not provided for update.'
)
# Description cannot be updated together with state.
if delta.get('description') and delta.get('state'):
raise exc.InputException(
'The property description must be updated '
'separately from state.'
)
# If state change, environment cannot be updated
# if not RUNNING.
if (delta.get('env') and
delta.get('state') and
delta['state'] != states.RUNNING):
raise exc.InputException(
'The property env can only be updated when workflow '
'execution is not running or on resume from pause.'
)
if delta.get('description'):
wf_ex = db_api.update_workflow_execution(
id,
{'description': delta['description']}
)
if not delta.get('state') and delta.get('env'):
wf_ex = db_api.get_workflow_execution(id)
wf_ex = wf_service.update_workflow_execution_env(
wf_ex,
delta.get('env')
)
return delta, wf_ex
delta, wf_ex = _compute_delta(wf_ex)
if delta.get('state'):
if states.is_paused(delta.get('state')):
wf_ex = rpc.get_engine_client().pause_workflow(id)
elif delta.get('state') == states.RUNNING:
wf_ex = rpc.get_engine_client().resume_workflow(
id,
env=delta.get('env')
)
elif states.is_completed(delta.get('state')):
msg = wf_ex.state_info if wf_ex.state_info else None
wf_ex = rpc.get_engine_client().stop_workflow(
id,
delta.get('state'),
msg
)
else:
# To prevent changing state in other cases throw a message.
raise exc.InputException(
"Cannot change state to %s. Allowed states are: '%s" % (
wf_ex.state,
', '.join([
states.RUNNING,
states.PAUSED,
states.SUCCESS,
states.ERROR,
states.CANCELLED
])
)
)
return resources.Execution.from_dict(
wf_ex if isinstance(wf_ex, dict) else wf_ex.to_dict()
)
@rest_utils.wrap_wsme_controller_exception
@wsme_pecan.wsexpose(
resources.Execution,
body=resources.Execution,
status_code=201
)
def post(self, wf_ex):
"""Create a new Execution.
:param wf_ex: Execution object with input content.
"""
acl.enforce('executions:create', context.ctx())
LOG.debug("Create execution [execution=%s]", wf_ex)
exec_dict = wf_ex.to_dict()
exec_id = exec_dict.get('id')
if not exec_id:
exec_id = uuidutils.generate_uuid()
LOG.debug("Generated execution id [exec_id=%s]", exec_id)
exec_dict.update({'id': exec_id})
wf_ex = None
else:
# If ID is present we need to check if such execution exists.
# If yes, the method just returns the object. If not, the ID
# will be used to create a new execution.
wf_ex = _get_workflow_execution(exec_id, must_exist=False)
if wf_ex:
return resources.Execution.from_db_model(wf_ex)
source_execution_id = exec_dict.get('source_execution_id')
source_exec_dict = None
if source_execution_id:
# If source execution is present we will perform a lookup for
# previous workflow execution model and the information to start
# a new workflow based on that information.
source_exec_dict = db_api.get_workflow_execution(
source_execution_id).to_dict()
exec_dict['description'] = "{} Based on the execution '{}'".format(
exec_dict['description'],
source_execution_id
)
exec_dict['description'] = exec_dict['description'].strip()
result_exec_dict = merge_dicts(source_exec_dict, exec_dict)
if not (result_exec_dict.get('workflow_id') or
result_exec_dict.get('workflow_name')):
raise exc.WorkflowException(
"Workflow ID or workflow name must be provided. Workflow ID is"
" recommended."
)
engine = rpc.get_engine_client()
result = engine.start_workflow(
result_exec_dict.get(
'workflow_id',
result_exec_dict.get('workflow_name')
),
result_exec_dict.get('workflow_namespace', ''),
result_exec_dict.get('id'),
result_exec_dict.get('input'),
description=result_exec_dict.get('description', ''),
**result_exec_dict.get('params') or {}
)
return resources.Execution.from_dict(result)
@rest_utils.wrap_wsme_controller_exception
@wsme_pecan.wsexpose(None, wtypes.text, bool, status_code=204)
def delete(self, id, force=False):
"""Delete the specified Execution.
:param id: UUID of execution to delete.
:param force: Optional. Force the deletion of unfinished executions.
Default: false. While the api is backward compatible
the behaviour is not the same. The new default is the
safer option
"""
acl.enforce('executions:delete', context.ctx())
LOG.debug("Delete execution [id=%s]", id)
if not force:
state = db_api.get_workflow_execution(
id,
fields=(db_models.WorkflowExecution.state,)
)[0]
if not states.is_completed(state):
raise exc.NotAllowedException(
"Only completed executions can be deleted. "
"Use --force to override this. "
"Execution {} is in {} state".format(id, state)
)
return rest_utils.rest_retry_on_db_error(
db_api.delete_workflow_execution
)(id)
@rest_utils.wrap_wsme_controller_exception
@wsme_pecan.wsexpose(resources.Executions, types.uuid, int,
types.uniquelist, types.list, types.uniquelist,
wtypes.text, types.uuid, wtypes.text,
types.uniquelist, types.jsontype, types.uuid,
types.uuid, STATE_TYPES, wtypes.text,
types.jsontype, types.jsontype, wtypes.text,
wtypes.text, bool, types.uuid,
bool, types.list)
def get_all(self, marker=None, limit=None,
sort_keys='created_at', sort_dirs='asc', fields='',
workflow_name=None, workflow_id=None, description=None,
tags=None, params=None, task_execution_id=None,
root_execution_id=None, state=None, state_info=None,
input=None, output=None, created_at=None,
updated_at=None, include_output=None, project_id=None,
all_projects=False, nulls=''):
"""Return all Executions.
:param marker: Optional. Pagination marker for large data sets.
:param limit: Optional. Maximum number of resources to return in a
single result. Default value is None for backward
compatibility.
:param sort_keys: Optional. Columns to sort results by.
Default: created_at, which is backward compatible.
:param sort_dirs: Optional. Directions to sort corresponding to
sort_keys, "asc" or "desc" can be chosen.
Default: desc. The length of sort_dirs can be equal
or less than that of sort_keys.
:param fields: Optional. A specified list of fields of the resource to
be returned. 'id' will be included automatically in
fields if it's provided, since it will be used when
constructing 'next' link.
:param workflow_name: Optional. Keep only resources with a specific
workflow name.
:param workflow_id: Optional. Keep only resources with a specific
workflow ID.
:param description: Optional. Keep only resources with a specific
description.
:param tags: Optional. Keep only resources containing specific tags.
:param params: Optional. Keep only resources with specific parameters.
:param task_execution_id: Optional. Keep only resources with a
specific task execution ID.
:param root_execution_id: Optional. Keep only resources with a
specific root execution ID.
:param state: Optional. Keep only resources with a specific state.
:param state_info: Optional. Keep only resources with specific
state information.
:param input: Optional. Keep only resources with a specific input.
:param output: Optional. Keep only resources with a specific output.
:param created_at: Optional. Keep only resources created at a specific
time and date.
:param updated_at: Optional. Keep only resources with specific latest
update time and date.
:param include_output: Optional. Include the output for all executions
in the list.
:param project_id: Optional. Only get executions belong to the project.
Admin required.
:param all_projects: Optional. Get resources of all projects. Admin
required.
:param nulls: Optional. The names of the columns with null value in
the query.
"""
acl.enforce('executions:list', context.ctx())
db_models.WorkflowExecution.check_allowed_none_values(nulls)
if all_projects or project_id:
acl.enforce('executions:list:all_projects', context.ctx())
filters = filter_utils.create_filters_from_request_params(
none_values=nulls,
created_at=created_at,
workflow_name=workflow_name,
workflow_id=workflow_id,
tags=tags,
params=params,
task_execution_id=task_execution_id,
state=state,
state_info=state_info,
input=input,
output=output,
updated_at=updated_at,
description=description,
project_id=project_id,
root_execution_id=root_execution_id,
)
LOG.debug(
"Fetch executions. marker=%s, limit=%s, sort_keys=%s, "
"sort_dirs=%s, filters=%s, all_projects=%s", marker, limit,
sort_keys, sort_dirs, filters, all_projects
)
if include_output:
resource_function = _get_workflow_execution_resource_with_output
else:
resource_function = _get_workflow_execution_resource
return rest_utils.get_all(
resources.Executions,
resources.Execution,
db_api.get_workflow_executions,
db_api.get_workflow_execution,
resource_function=resource_function,
marker=marker,
limit=limit,
sort_keys=sort_keys,
sort_dirs=sort_dirs,
fields=fields,
all_projects=all_projects,
**filters
)
| apache-2.0 | -1,259,276,599,923,299,800 | 37.436242 | 79 | 0.569117 | false | 4.408776 | false | false | false |
kgullikson88/TS23-Scripts | CheckSyntheticTemperature.py | 1 | 14868 | import os
import re
from collections import defaultdict
from operator import itemgetter
import logging
import pandas
from scipy.interpolate import InterpolatedUnivariateSpline as spline
from george import kernels
import matplotlib.pyplot as plt
import numpy as np
import george
import emcee
import StarData
import SpectralTypeRelations
def classify_filename(fname, type='bright'):
"""
Given a CCF filename, it classifies the star combination, temperature, metallicity, and vsini
:param fname:
:return:
"""
# First, remove any leading directories
fname = fname.split('/')[-1]
# Star combination
m1 = re.search('\.[0-9]+kps', fname)
stars = fname[:m1.start()]
star1 = stars.split('+')[0].replace('_', ' ')
star2 = stars.split('+')[1].split('_{}'.format(type))[0].replace('_', ' ')
# secondary star vsini
vsini = float(fname[m1.start() + 1:].split('kps')[0])
# Temperature
m2 = re.search('[0-9]+\.0K', fname)
temp = float(m2.group()[:-1])
# logg
m3 = re.search('K\+[0-9]\.[0-9]', fname)
logg = float(m3.group()[1:])
# metallicity
metal = float(fname.split(str(logg))[-1])
return star1, star2, vsini, temp, logg, metal
def get_ccf_data(basedir, primary_name=None, secondary_name=None, vel_arr=np.arange(-900.0, 900.0, 0.1), type='bright'):
"""
Searches the given directory for CCF files, and classifies
by star, temperature, metallicity, and vsini
:param basedir: The directory to search for CCF files
:keyword primary_name: Optional keyword. If given, it will only get the requested primary star data
:keyword secondary_name: Same as primary_name, but only reads ccfs for the given secondary
:keyword vel_arr: The velocities to interpolate each ccf at
:return: pandas DataFrame
"""
if not basedir.endswith('/'):
basedir += '/'
all_files = ['{}{}'.format(basedir, f) for f in os.listdir(basedir) if type in f.lower()]
primary = []
secondary = []
vsini_values = []
temperature = []
gravity = []
metallicity = []
ccf = []
for fname in all_files:
star1, star2, vsini, temp, logg, metal = classify_filename(fname, type=type)
if primary_name is not None and star1.lower() != primary_name.lower():
continue
if secondary_name is not None and star2.lower() != secondary_name.lower():
continue
vel, corr = np.loadtxt(fname, unpack=True)
fcn = spline(vel, corr)
ccf.append(fcn(vel_arr))
primary.append(star1)
secondary.append(star2)
vsini_values.append(vsini)
temperature.append(temp)
gravity.append(logg)
metallicity.append(metal)
# Make a pandas dataframe with all this data
df = pandas.DataFrame(data={'Primary': primary, 'Secondary': secondary, 'Temperature': temperature,
'vsini': vsini_values, 'logg': gravity, '[Fe/H]': metallicity, 'CCF': ccf})
return df
def get_ccf_summary(basedir, vel_arr=np.arange(-900.0, 900.0, 0.1), velocity='highest', type='bright'):
"""
Very similar to get_ccf_data, but does it in a way that is more memory efficient
:param basedir: The directory to search for CCF files
:keyword velocity: The velocity to measure the CCF at. The default is 'highest', and uses the maximum of the ccf
:keyword vel_arr: The velocities to interpolate each ccf at
:return: pandas DataFrame
"""
if not basedir.endswith('/'):
basedir += '/'
all_files = ['{}{}'.format(basedir, f) for f in os.listdir(basedir) if type in f.lower()]
file_dict = defaultdict(lambda: defaultdict(list))
for fname in all_files:
star1, star2, vsini, temp, logg, metal = classify_filename(fname, type=type)
file_dict[star1][star2].append(fname)
# Now, read the ccfs for each primary/secondary combo, and find the best combination
summary_dfs = []
for primary in file_dict.keys():
for secondary in file_dict[primary].keys():
data = get_ccf_data(basedir, primary_name=primary, secondary_name=secondary,
vel_arr=vel_arr, type=type)
summary_dfs.append(find_best_pars(data, velocity=velocity, vel_arr=vel_arr))
return pandas.concat(summary_dfs, ignore_index=True)
def find_best_pars(df, velocity='highest', vel_arr=np.arange(-900.0, 900.0, 0.1)):
"""
Find the 'best-fit' parameters for each combination of primary and secondary star
:param df: the dataframe to search in
:keyword velocity: The velocity to measure the CCF at. The default is 'highest', and uses the maximum of the ccf
:keyword vel_arr: The velocities to interpolate each ccf at
:return: a dataframe with keys of primary, secondary, and the parameters
"""
# Get the names of the primary and secondary stars
primary_names = pandas.unique(df.Primary)
secondary_names = pandas.unique(df.Secondary)
# Find the ccf value at the given velocity
if velocity == 'highest':
fcn = lambda row: (np.max(row), vel_arr[np.argmax(row)])
vals = df['CCF'].map(fcn)
df['ccf_max'] = vals.map(lambda l: l[0])
df['rv'] = vals.map(lambda l: l[1])
# df['ccf_max'] = df['CCF'].map(np.max)
else:
df['ccf_max'] = df['CCF'].map(lambda arr: arr[np.argmin(np.abs(vel_arr - velocity))])
# Find the best parameter for each combination
d = defaultdict(list)
for primary in primary_names:
for secondary in secondary_names:
good = df.loc[(df.Primary == primary) & (df.Secondary == secondary)]
best = good.loc[good.ccf_max == good.ccf_max.max()]
d['Primary'].append(primary)
d['Secondary'].append(secondary)
d['Temperature'].append(best['Temperature'].item())
d['vsini'].append(best['vsini'].item())
d['logg'].append(best['logg'].item())
d['[Fe/H]'].append(best['[Fe/H]'].item())
d['rv'].append(best['rv'].item())
return pandas.DataFrame(data=d)
def get_detected_objects(df, tol=1.0):
"""
Takes a summary dataframe with RV information. Finds the median rv for each star,
and removes objects that are 'tol' km/s from the median value
:param df: A summary dataframe, such as created by find_best_pars
:param tol: The tolerance, in km/s, to accept an observation as detected
:return: a dataframe containing only detected companions
"""
secondary_names = pandas.unique(df.Secondary)
secondary_to_rv = defaultdict(float)
for secondary in secondary_names:
rv = df.loc[df.Secondary == secondary]['rv'].median()
secondary_to_rv[secondary] = rv
print secondary, rv
keys = df.Secondary.values
good = df.loc[abs(df.rv.values - np.array(itemgetter(*keys)(secondary_to_rv))) < tol]
return good
def add_actual_temperature(df, method='spt'):
"""
Add the actual temperature to a given summary dataframe
:param df: The dataframe to which we will add the actual secondary star temperature
:param method: How to get the actual temperature. Options are:
- 'spt': Use main-sequence relationships to go from spectral type --> temperature
- 'excel': Use tabulated data, available in the file 'SecondaryStar_Temperatures.xls'
:return: copy of the original dataframe, with an extra column for the secondary star temperature
"""
# First, get a list of the secondary stars in the data
secondary_names = pandas.unique(df.Secondary)
secondary_to_temperature = defaultdict(float)
secondary_to_error = defaultdict(float)
if method.lower() == 'spt':
MS = SpectralTypeRelations.MainSequence()
for secondary in secondary_names:
star_data = StarData.GetData(secondary)
spt = star_data.spectype[0] + re.search('[0-9]\.*[0-9]*', star_data.spectype).group()
T_sec = MS.Interpolate(MS.Temperature, spt)
secondary_to_temperature[secondary] = T_sec
elif method.lower() == 'excel':
table = pandas.read_excel('SecondaryStar_Temperatures.xls', 0)
for secondary in secondary_names:
T_sec = table.loc[table.Star.str.lower().str.contains(secondary.strip().lower())]['Literature_Temp'].item()
T_error = table.loc[table.Star.str.lower().str.contains(secondary.strip().lower())][
'Literature_error'].item()
secondary_to_temperature[secondary] = T_sec
secondary_to_error[secondary] = T_error
df['Tactual'] = df['Secondary'].map(lambda s: secondary_to_temperature[s])
df['Tact_err'] = df['Secondary'].map(lambda s: secondary_to_error[s])
return
def make_gaussian_process_samples(df):
"""
Make a gaussian process fitting the Tactual-Tmeasured relationship
:param df: pandas DataFrame with columns 'Temperature' (with the measured temperature)
and 'Tactual' (for the actual temperature)
:return: emcee sampler instance
"""
# First, find the uncertainties at each actual temperature
# Tactual = df['Tactual'].values
#Tmeasured = df['Temperature'].values
#error = df['Tact_err'].values
temp = df.groupby('Temperature').mean()['Tactual']
Tmeasured = temp.keys().values
Tactual = temp.values
error = np.nan_to_num(df.groupby('Temperature').std(ddof=1)['Tactual'].values)
default = np.median(error[error > 1])
error = np.maximum(error, np.ones(error.size) * default)
for Tm, Ta, e in zip(Tmeasured, Tactual, error):
print Tm, Ta, e
plt.figure(1)
plt.errorbar(Tmeasured, Tactual, yerr=error, fmt='.k', capsize=0)
plt.plot(Tmeasured, Tmeasured, 'r--')
plt.xlim((min(Tmeasured) - 100, max(Tmeasured) + 100))
plt.xlabel('Measured Temperature')
plt.ylabel('Actual Temperature')
plt.show(block=False)
# Define some functions to use in the GP fit
def model(pars, T):
#polypars = pars[2:]
#return np.poly1d(polypars)(T)
return T
def lnlike(pars, Tact, Tmeas, Terr):
a, tau = np.exp(pars[:2])
gp = george.GP(a * kernels.ExpSquaredKernel(tau))
gp.compute(Tmeas, Terr)
return gp.lnlikelihood(Tact - model(pars, Tmeas))
def lnprior(pars):
lna, lntau = pars[:2]
polypars = pars[2:]
if -20 < lna < 20 and 4 < lntau < 20:
return 0.0
return -np.inf
def lnprob(pars, x, y, yerr):
lp = lnprior(pars)
return lp + lnlike(pars, x, y, yerr) if np.isfinite(lp) else -np.inf
# Set up the emcee fitter
initial = np.array([0, 6])#, 1.0, 0.0])
ndim = len(initial)
nwalkers = 100
p0 = [np.array(initial) + 1e-8 * np.random.randn(ndim) for i in xrange(nwalkers)]
sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(Tactual, Tmeasured, error))
print 'Running first burn-in'
p1, lnp, _ = sampler.run_mcmc(p0, 500)
sampler.reset()
print "Running second burn-in..."
p_best = p1[np.argmax(lnp)]
p2 = [p_best + 1e-8 * np.random.randn(ndim) for i in xrange(nwalkers)]
p3, _, _ = sampler.run_mcmc(p2, 250)
sampler.reset()
print "Running production..."
sampler.run_mcmc(p3, 1000)
# Plot a bunch of the fits
print "Plotting..."
N = 100
Tvalues = np.arange(3300, 7000, 20)
idx = np.argsort(-sampler.lnprobability.flatten())[:N] # Get N 'best' curves
par_vals = sampler.flatchain[idx]
for i, pars in enumerate(par_vals):
a, tau = np.exp(pars[:2])
gp = george.GP(a * kernels.ExpSquaredKernel(tau))
gp.compute(Tmeasured, error)
s = gp.sample_conditional(Tactual - model(pars, Tmeasured), Tvalues) + model(pars, Tvalues)
plt.plot(Tvalues, s, 'b-', alpha=0.1)
plt.draw()
# Finally, get posterior samples at all the possibly measured temperatures
print 'Generating posterior samples at all temperatures...'
N = 10000 # This is 1/10th of the total number of samples!
idx = np.argsort(-sampler.lnprobability.flatten())[:N] # Get N 'best' curves
par_vals = sampler.flatchain[idx]
Tvalues = np.arange(3000, 6900, 100)
gp_posterior = []
for pars in par_vals:
a, tau = np.exp(pars[:2])
gp = george.GP(a * kernels.ExpSquaredKernel(tau))
gp.compute(Tmeasured, error)
s = gp.sample_conditional(Tactual - model(pars, Tmeasured), Tvalues) + model(pars, Tvalues)
gp_posterior.append(s)
# Finally, make confidence intervals for the actual temperatures
gp_posterior = np.array(gp_posterior)
l, m, h = np.percentile(gp_posterior, [16.0, 50.0, 84.0], axis=0)
conf = pandas.DataFrame(data={'Measured Temperature': Tvalues, 'Actual Temperature': m,
'Lower Bound': l, 'Upper bound': h})
conf.to_csv('Confidence_Intervals.csv', index=False)
return sampler, np.array(gp_posterior)
def check_posterior(df, posterior, Tvalues):
"""
Checks the posterior samples: Are 95% of the measurements within 2-sigma of the prediction?
:param df: The summary dataframe
:param posterior: The MCMC predicted values
:param Tvalues: The measured temperatures the posterior was made with
:return: boolean, as well as some warning messages if applicable
"""
# First, make 2-sigma confidence intervals
l, m, h = np.percentile(posterior, [5.0, 50.0, 95.0], axis=0)
# Save the confidence intervals
# conf = pandas.DataFrame(data={'Measured Temperature': Tvalues, 'Actual Temperature': m,
# 'Lower Bound': l, 'Upper bound': h})
#conf.to_csv('Confidence_Intervals.csv', index=False)
Ntot = [] # The total number of observations with the given measured temperature
Nacc = [] # The number that have actual temperatures within the confidence interval
g = df.groupby('Temperature')
for i, T in enumerate(Tvalues):
if T in g.groups.keys():
Ta = g.get_group(T)['Tactual']
low, high = l[i], h[i]
Ntot.append(len(Ta))
Nacc.append(len(Ta.loc[(Ta >= low) & (Ta <= high)]))
p = float(Nacc[-1]) / float(Ntot[-1])
if p < 0.95:
logging.warn(
'Only {}/{} of the samples ({:.2f}%) were accepted for T = {} K'.format(Nacc[-1], Ntot[-1], p * 100,
T))
print low, high
print sorted(Ta)
else:
Ntot.append(0)
Nacc.append(0)
p = float(sum(Nacc)) / float(sum(Ntot))
if p < 0.95:
logging.warn('Only {:.2f}% of the total samples were accepted!'.format(p * 100))
return False
return True
if __name__ == '__main__':
pass
| gpl-3.0 | -920,756,524,181,589,000 | 39.402174 | 120 | 0.625572 | false | 3.54 | false | false | false |
MattDevo/edk2 | BaseTools/Source/Python/Workspace/MetaFileTable.py | 1 | 16975 | ## @file
# This file is used to create/update/query/erase a meta file table
#
# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
##
# Import Modules
#
from __future__ import absolute_import
import uuid
import Common.EdkLogger as EdkLogger
from Common.BuildToolError import FORMAT_INVALID
from CommonDataClass.DataClass import MODEL_FILE_DSC, MODEL_FILE_DEC, MODEL_FILE_INF, \
MODEL_FILE_OTHERS
from Common.DataType import *
class MetaFileTable():
# TRICK: use file ID as the part before '.'
_ID_STEP_ = 1
_ID_MAX_ = 99999999
## Constructor
def __init__(self, DB, MetaFile, FileType, Temporary, FromItem=None):
self.MetaFile = MetaFile
self.TableName = ""
self.DB = DB
self._NumpyTab = None
self.CurrentContent = []
DB.TblFile.append([MetaFile.Name,
MetaFile.Ext,
MetaFile.Dir,
MetaFile.Path,
FileType,
MetaFile.TimeStamp,
FromItem])
self.FileId = len(DB.TblFile)
self.ID = self.FileId * 10**8
if Temporary:
self.TableName = "_%s_%s_%s" % (FileType, len(DB.TblFile), uuid.uuid4().hex)
else:
self.TableName = "_%s_%s" % (FileType, len(DB.TblFile))
def IsIntegrity(self):
try:
TimeStamp = self.MetaFile.TimeStamp
if not self.CurrentContent:
Result = False
else:
Result = self.CurrentContent[-1][0] < 0
if not Result:
# update the timestamp in database
self.DB.SetFileTimeStamp(self.FileId, TimeStamp)
return False
if TimeStamp != self.DB.GetFileTimeStamp(self.FileId):
# update the timestamp in database
self.DB.SetFileTimeStamp(self.FileId, TimeStamp)
return False
except Exception as Exc:
EdkLogger.debug(EdkLogger.DEBUG_5, str(Exc))
return False
return True
def SetEndFlag(self):
self.CurrentContent.append(self._DUMMY_)
def GetAll(self):
return [item for item in self.CurrentContent if item[0] >= 0 ]
## Python class representation of table storing module data
class ModuleTable(MetaFileTable):
_COLUMN_ = '''
ID REAL PRIMARY KEY,
Model INTEGER NOT NULL,
Value1 TEXT NOT NULL,
Value2 TEXT,
Value3 TEXT,
Scope1 TEXT,
Scope2 TEXT,
BelongsToItem REAL NOT NULL,
StartLine INTEGER NOT NULL,
StartColumn INTEGER NOT NULL,
EndLine INTEGER NOT NULL,
EndColumn INTEGER NOT NULL,
Enabled INTEGER DEFAULT 0
'''
# used as table end flag, in case the changes to database is not committed to db file
_DUMMY_ = [-1, -1, '====', '====', '====', '====', '====', -1, -1, -1, -1, -1, -1]
## Constructor
def __init__(self, Db, MetaFile, Temporary):
MetaFileTable.__init__(self, Db, MetaFile, MODEL_FILE_INF, Temporary)
## Insert a record into table Inf
#
# @param Model: Model of a Inf item
# @param Value1: Value1 of a Inf item
# @param Value2: Value2 of a Inf item
# @param Value3: Value3 of a Inf item
# @param Scope1: Arch of a Inf item
# @param Scope2 Platform os a Inf item
# @param BelongsToItem: The item belongs to which another item
# @param StartLine: StartLine of a Inf item
# @param StartColumn: StartColumn of a Inf item
# @param EndLine: EndLine of a Inf item
# @param EndColumn: EndColumn of a Inf item
# @param Enabled: If this item enabled
#
def Insert(self, Model, Value1, Value2, Value3, Scope1=TAB_ARCH_COMMON, Scope2=TAB_COMMON,
BelongsToItem=-1, StartLine=-1, StartColumn=-1, EndLine=-1, EndColumn=-1, Enabled=0):
(Value1, Value2, Value3, Scope1, Scope2) = (Value1.strip(), Value2.strip(), Value3.strip(), Scope1.strip(), Scope2.strip())
self.ID = self.ID + self._ID_STEP_
if self.ID >= (MODEL_FILE_INF + self._ID_MAX_):
self.ID = MODEL_FILE_INF + self._ID_STEP_
row = [ self.ID,
Model,
Value1,
Value2,
Value3,
Scope1,
Scope2,
BelongsToItem,
StartLine,
StartColumn,
EndLine,
EndColumn,
Enabled
]
self.CurrentContent.append(row)
return self.ID
## Query table
#
# @param Model: The Model of Record
# @param Arch: The Arch attribute of Record
# @param Platform The Platform attribute of Record
#
# @retval: A recordSet of all found records
#
def Query(self, Model, Arch=None, Platform=None, BelongsToItem=None):
QueryTab = self.CurrentContent
result = [item for item in QueryTab if item[1] == Model and item[-1]>=0 ]
if Arch is not None and Arch != TAB_ARCH_COMMON:
ArchList = set(['COMMON'])
ArchList.add(Arch)
result = [item for item in result if item[5] in ArchList]
if Platform is not None and Platform != TAB_COMMON:
Platformlist = set( ['COMMON','DEFAULT'])
Platformlist.add(Platform)
result = [item for item in result if item[6] in Platformlist]
if BelongsToItem is not None:
result = [item for item in result if item[7] == BelongsToItem]
result = [ [r[2],r[3],r[4],r[5],r[6],r[0],r[9]] for r in result ]
return result
## Python class representation of table storing package data
class PackageTable(MetaFileTable):
_COLUMN_ = '''
ID REAL PRIMARY KEY,
Model INTEGER NOT NULL,
Value1 TEXT NOT NULL,
Value2 TEXT,
Value3 TEXT,
Scope1 TEXT,
Scope2 TEXT,
BelongsToItem REAL NOT NULL,
StartLine INTEGER NOT NULL,
StartColumn INTEGER NOT NULL,
EndLine INTEGER NOT NULL,
EndColumn INTEGER NOT NULL,
Enabled INTEGER DEFAULT 0
'''
# used as table end flag, in case the changes to database is not committed to db file
_DUMMY_ = [-1, -1, '====', '====', '====', '====', '====', -1, -1, -1, -1, -1, -1]
## Constructor
def __init__(self, Cursor, MetaFile, Temporary):
MetaFileTable.__init__(self, Cursor, MetaFile, MODEL_FILE_DEC, Temporary)
## Insert table
#
# Insert a record into table Dec
#
# @param Model: Model of a Dec item
# @param Value1: Value1 of a Dec item
# @param Value2: Value2 of a Dec item
# @param Value3: Value3 of a Dec item
# @param Scope1: Arch of a Dec item
# @param Scope2: Module type of a Dec item
# @param BelongsToItem: The item belongs to which another item
# @param StartLine: StartLine of a Dec item
# @param StartColumn: StartColumn of a Dec item
# @param EndLine: EndLine of a Dec item
# @param EndColumn: EndColumn of a Dec item
# @param Enabled: If this item enabled
#
def Insert(self, Model, Value1, Value2, Value3, Scope1=TAB_ARCH_COMMON, Scope2=TAB_COMMON,
BelongsToItem=-1, StartLine=-1, StartColumn=-1, EndLine=-1, EndColumn=-1, Enabled=0):
(Value1, Value2, Value3, Scope1, Scope2) = (Value1.strip(), Value2.strip(), Value3.strip(), Scope1.strip(), Scope2.strip())
self.ID = self.ID + self._ID_STEP_
row = [ self.ID,
Model,
Value1,
Value2,
Value3,
Scope1,
Scope2,
BelongsToItem,
StartLine,
StartColumn,
EndLine,
EndColumn,
Enabled
]
self.CurrentContent.append(row)
return self.ID
## Query table
#
# @param Model: The Model of Record
# @param Arch: The Arch attribute of Record
#
# @retval: A recordSet of all found records
#
def Query(self, Model, Arch=None):
QueryTab = self.CurrentContent
result = [item for item in QueryTab if item[1] == Model and item[-1]>=0 ]
if Arch is not None and Arch != TAB_ARCH_COMMON:
ArchList = set(['COMMON'])
ArchList.add(Arch)
result = [item for item in result if item[5] in ArchList]
return [[r[2], r[3], r[4], r[5], r[6], r[0], r[8]] for r in result]
def GetValidExpression(self, TokenSpaceGuid, PcdCName):
QueryTab = self.CurrentContent
result = [[item[2], item[8]] for item in QueryTab if item[3] == TokenSpaceGuid and item[4] == PcdCName]
validateranges = []
validlists = []
expressions = []
try:
for row in result:
comment = row[0]
LineNum = row[1]
comment = comment.strip("#")
comment = comment.strip()
oricomment = comment
if comment.startswith("@ValidRange"):
comment = comment.replace("@ValidRange", "", 1)
validateranges.append(comment.split("|")[1].strip())
if comment.startswith("@ValidList"):
comment = comment.replace("@ValidList", "", 1)
validlists.append(comment.split("|")[1].strip())
if comment.startswith("@Expression"):
comment = comment.replace("@Expression", "", 1)
expressions.append(comment.split("|")[1].strip())
except Exception as Exc:
ValidType = ""
if oricomment.startswith("@ValidRange"):
ValidType = "@ValidRange"
if oricomment.startswith("@ValidList"):
ValidType = "@ValidList"
if oricomment.startswith("@Expression"):
ValidType = "@Expression"
EdkLogger.error('Parser', FORMAT_INVALID, "The syntax for %s of PCD %s.%s is incorrect" % (ValidType, TokenSpaceGuid, PcdCName),
ExtraData=oricomment, File=self.MetaFile, Line=LineNum)
return set(), set(), set()
return set(validateranges), set(validlists), set(expressions)
## Python class representation of table storing platform data
class PlatformTable(MetaFileTable):
_COLUMN_ = '''
ID REAL PRIMARY KEY,
Model INTEGER NOT NULL,
Value1 TEXT NOT NULL,
Value2 TEXT,
Value3 TEXT,
Scope1 TEXT,
Scope2 TEXT,
Scope3 TEXT,
BelongsToItem REAL NOT NULL,
FromItem REAL NOT NULL,
StartLine INTEGER NOT NULL,
StartColumn INTEGER NOT NULL,
EndLine INTEGER NOT NULL,
EndColumn INTEGER NOT NULL,
Enabled INTEGER DEFAULT 0
'''
# used as table end flag, in case the changes to database is not committed to db file
_DUMMY_ = [-1, -1, '====', '====', '====', '====', '====','====', -1, -1, -1, -1, -1, -1, -1]
## Constructor
def __init__(self, Cursor, MetaFile, Temporary, FromItem=0):
MetaFileTable.__init__(self, Cursor, MetaFile, MODEL_FILE_DSC, Temporary, FromItem)
## Insert table
#
# Insert a record into table Dsc
#
# @param Model: Model of a Dsc item
# @param Value1: Value1 of a Dsc item
# @param Value2: Value2 of a Dsc item
# @param Value3: Value3 of a Dsc item
# @param Scope1: Arch of a Dsc item
# @param Scope2: Module type of a Dsc item
# @param BelongsToItem: The item belongs to which another item
# @param FromItem: The item belongs to which dsc file
# @param StartLine: StartLine of a Dsc item
# @param StartColumn: StartColumn of a Dsc item
# @param EndLine: EndLine of a Dsc item
# @param EndColumn: EndColumn of a Dsc item
# @param Enabled: If this item enabled
#
def Insert(self, Model, Value1, Value2, Value3, Scope1=TAB_ARCH_COMMON, Scope2=TAB_COMMON, Scope3=TAB_DEFAULT_STORES_DEFAULT,BelongsToItem=-1,
FromItem=-1, StartLine=-1, StartColumn=-1, EndLine=-1, EndColumn=-1, Enabled=1):
(Value1, Value2, Value3, Scope1, Scope2, Scope3) = (Value1.strip(), Value2.strip(), Value3.strip(), Scope1.strip(), Scope2.strip(), Scope3.strip())
self.ID = self.ID + self._ID_STEP_
row = [ self.ID,
Model,
Value1,
Value2,
Value3,
Scope1,
Scope2,
Scope3,
BelongsToItem,
FromItem,
StartLine,
StartColumn,
EndLine,
EndColumn,
Enabled
]
self.CurrentContent.append(row)
return self.ID
## Query table
#
# @param Model: The Model of Record
# @param Scope1: Arch of a Dsc item
# @param Scope2: Module type of a Dsc item
# @param BelongsToItem: The item belongs to which another item
# @param FromItem: The item belongs to which dsc file
#
# @retval: A recordSet of all found records
#
def Query(self, Model, Scope1=None, Scope2=None, BelongsToItem=None, FromItem=None):
QueryTab = self.CurrentContent
result = [item for item in QueryTab if item[1] == Model and item[-1]>0 ]
if Scope1 is not None and Scope1 != TAB_ARCH_COMMON:
Sc1 = set(['COMMON'])
Sc1.add(Scope1)
result = [item for item in result if item[5] in Sc1]
Sc2 = set( ['COMMON','DEFAULT'])
if Scope2 and Scope2 != TAB_COMMON:
if '.' in Scope2:
Index = Scope2.index('.')
NewScope = TAB_COMMON + Scope2[Index:]
Sc2.add(NewScope)
Sc2.add(Scope2)
result = [item for item in result if item[6] in Sc2]
if BelongsToItem is not None:
result = [item for item in result if item[8] == BelongsToItem]
else:
result = [item for item in result if item[8] < 0]
if FromItem is not None:
result = [item for item in result if item[9] == FromItem]
result = [ [r[2],r[3],r[4],r[5],r[6],r[7],r[0],r[9]] for r in result ]
return result
## Factory class to produce different storage for different type of meta-file
class MetaFileStorage(object):
_FILE_TABLE_ = {
MODEL_FILE_INF : ModuleTable,
MODEL_FILE_DEC : PackageTable,
MODEL_FILE_DSC : PlatformTable,
MODEL_FILE_OTHERS : MetaFileTable,
}
_FILE_TYPE_ = {
".inf" : MODEL_FILE_INF,
".dec" : MODEL_FILE_DEC,
".dsc" : MODEL_FILE_DSC,
}
_ObjectCache = {}
## Constructor
def __new__(Class, Cursor, MetaFile, FileType=None, Temporary=False, FromItem=None):
# no type given, try to find one
key = (MetaFile.Path, FileType,Temporary,FromItem)
if key in Class._ObjectCache:
return Class._ObjectCache[key]
if not FileType:
if MetaFile.Type in self._FILE_TYPE_:
FileType = Class._FILE_TYPE_[MetaFile.Type]
else:
FileType = MODEL_FILE_OTHERS
# don't pass the type around if it's well known
if FileType == MODEL_FILE_OTHERS:
Args = (Cursor, MetaFile, FileType, Temporary)
else:
Args = (Cursor, MetaFile, Temporary)
if FromItem:
Args = Args + (FromItem,)
# create the storage object and return it to caller
reval = Class._FILE_TABLE_[FileType](*Args)
if not Temporary:
Class._ObjectCache[key] = reval
return reval
| bsd-2-clause | 8,104,280,331,112,390,000 | 36.492063 | 155 | 0.544035 | false | 3.958722 | false | false | false |
ssharpjr/taskbuster-boilerplate | taskbuster/apps/taskmanager/models.py | 1 | 2262 | # -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.core.validators import RegexValidator
from . import managers
class Profile(models.Model):
# Relations
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
related_name="profile",
verbose_name=_("user")
)
# Attributes - Mandatory
interaction = models.PositiveIntegerField(
default=0,
verbose_name=_("interaction")
)
# Attributes - Optional
# Object Manager
objects = managers.ProfileManager()
# Custom Properties
@property
def username(self):
return self.user.username
# Methods
# Meta and String
class Meta:
verbose_name = _("Profile")
verbose_name_plural = _("Profiles")
ordering = ("user",)
def __str__(self):
return self.user.username
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_profile_for_new_user(sender, created, instance, **kwargs):
if created:
profile = Profile(user=instance)
profile.save()
class Project(models.Model):
# Relations
user = models.ForeignKey(
Profile,
related_name="projects",
verbose_name=_("user")
)
# Attributes - Mandatory
name = models.CharField(
max_length=100,
verbose_name=_("name"),
help_text=_("Enter the project name")
)
color = models.CharField(
max_length=7,
default="#fff",
validators=[RegexValidator(
"(^#[0-9a-fA-F]{3}$)|(^#[0-9a-fA-F]{6}$)")],
verbose_name=_("color"),
help_text=_("Enter the hex color code, like #ccc or #cccccc")
)
# Attributes - Optional
# Object Manager
objects = managers.ProjectManager()
# Custom Properties
# Methods
# Meta and String
class Meta:
verbose_name = _("Project")
verbose_name_plural = _("Projects")
ordering = ("user", "name")
unique_together = ("user", "name")
def __str__(self):
return "%s - %s" % (self.user, self.name)
| mit | 2,343,749,543,026,243,000 | 25 | 69 | 0.599912 | false | 4.097826 | false | false | false |
CitoEngine/cito_engine | app/cito_engine/actions/json_formatter.py | 1 | 1266 | """Copyright 2014 Cyrus Dasadia
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import re
import simplejson
def create_json_parameters(event_action, incident, message=None):
plugin_parameters = event_action.pluginParameters
plugin_parameters = re.sub('"__EVENTID__"', simplejson.dumps(unicode(incident.event.id)), plugin_parameters)
plugin_parameters = re.sub('"__INCIDENTID__"', simplejson.dumps(unicode(incident.id)), plugin_parameters)
plugin_parameters = re.sub('"__ELEMENT__"', simplejson.dumps(unicode(incident.element)), plugin_parameters)
plugin_parameters = re.sub('"__MESSAGE__"', simplejson.dumps(unicode(message)), plugin_parameters)
return '{"plugin": %s, "parameters": %s}' % (simplejson.dumps(unicode(event_action.plugin.name)), plugin_parameters) | apache-2.0 | 1,861,107,108,582,375,000 | 47.730769 | 120 | 0.756714 | false | 4.044728 | false | false | false |
quantumlib/Cirq | dev_tools/profiling/benchmark_serializers.py | 1 | 4296 | # Copyright 2020 The Cirq Developers
#
# 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.
"""Tool for benchmarking serialization of large circuits.
This tool was originally introduced to enable comparison of the two JSON
serialization protocols (gzip and non-gzip):
https://github.com/quantumlib/Cirq/pull/3662
This is part of the "efficient serialization" effort:
https://github.com/quantumlib/Cirq/issues/3438
Run this benchmark with the following command (make sure to install cirq-dev):
python3 dev_tools/profiling/benchmark_serializers.py \
--num_gates=<int> --nesting_depth=<int> --num_repetitions=<int>
WARNING: runtime increases exponentially with nesting_depth. Values much
higher than nesting_depth=10 are not recommended.
"""
import argparse
import sys
import timeit
import numpy as np
import cirq
_JSON_GZIP = 'json_gzip'
_JSON = 'json'
NUM_QUBITS = 8
SUFFIXES = ['B', 'kB', 'MB', 'GB', 'TB']
def serialize(serializer: str, num_gates: int, nesting_depth: int) -> int:
""""Runs a round-trip of the serializer."""
circuit = cirq.Circuit()
for _ in range(num_gates):
which = np.random.choice(['expz', 'expw', 'exp11'])
if which == 'expw':
q1 = cirq.GridQubit(0, np.random.randint(NUM_QUBITS))
circuit.append(
cirq.PhasedXPowGate(
phase_exponent=np.random.random(), exponent=np.random.random()
).on(q1)
)
elif which == 'expz':
q1 = cirq.GridQubit(0, np.random.randint(NUM_QUBITS))
circuit.append(cirq.Z(q1) ** np.random.random())
elif which == 'exp11':
q1 = cirq.GridQubit(0, np.random.randint(NUM_QUBITS - 1))
q2 = cirq.GridQubit(0, q1.col + 1)
circuit.append(cirq.CZ(q1, q2) ** np.random.random())
cs = [circuit]
for _ in range(1, nesting_depth):
fc = cs[-1].freeze()
cs.append(cirq.Circuit(fc.to_op(), fc.to_op()))
test_circuit = cs[-1]
if serializer == _JSON:
json_data = cirq.to_json(test_circuit)
assert json_data is not None
data_size = len(json_data)
cirq.read_json(json_text=json_data)
elif serializer == _JSON_GZIP:
gzip_data = cirq.to_json_gzip(test_circuit)
assert gzip_data is not None
data_size = len(gzip_data)
cirq.read_json_gzip(gzip_raw=gzip_data)
return data_size
def main(
num_gates: int,
nesting_depth: int,
num_repetitions: int,
setup: str = 'from __main__ import serialize',
):
for serializer in [_JSON_GZIP, _JSON]:
print()
print(f'Using serializer "{serializer}":')
command = f'serialize(\'{serializer}\', {num_gates}, {nesting_depth})'
time = timeit.timeit(command, setup, number=num_repetitions)
print(f'Round-trip serializer time: {time / num_repetitions}s')
data_size = float(serialize(serializer, num_gates, nesting_depth))
suffix_idx = 0
while data_size > 1000:
data_size /= 1024
suffix_idx += 1
print(f'Serialized data size: {data_size} {SUFFIXES[suffix_idx]}.')
def parse_arguments(args):
parser = argparse.ArgumentParser('Benchmark a serializer.')
parser.add_argument(
'--num_gates', default=100, type=int, help='Number of gates at the bottom nesting layer.'
)
parser.add_argument(
'--nesting_depth',
default=1,
type=int,
help='Depth of nested subcircuits. Total gate count will be 2^nesting_depth * num_gates.',
)
parser.add_argument(
'--num_repetitions', default=10, type=int, help='Number of times to repeat serialization.'
)
return vars(parser.parse_args(args))
if __name__ == '__main__':
main(**parse_arguments(sys.argv[1:]))
| apache-2.0 | 1,166,759,302,246,157,000 | 33.368 | 98 | 0.64176 | false | 3.458937 | false | false | false |
Chetox/RCode | Cannon_Avanzado/client.py | 1 | 2002 | #!/usr/bin/python
# -*- coding:utf-8; tab-width:4; mode:python -*-
import sys
import Ice
Ice.loadSlice('-I {} cannon.ice'.format(Ice.getSliceDir()))
import Cannon
import time
from matrix_utils import matrix_multiply
def load_matrix_from_file(filename):
with file(filename) as f:
rows = f.readlines()
order = len(rows[0].split())
retval = Cannon.Matrix(order, [])
for row in rows:
rowdata = row.split()
assert len(rowdata) == order
for n in rowdata:
retval.data.append(float(n))
assert len(retval.data) == order ** 2
return retval
class Client(Ice.Application):
def run(self, argv):
t_dist = 0;
t_secu = 0;
loader = self.string_to_proxy(argv[1], Cannon.OperationsPrx)
example = argv[2]
A = load_matrix_from_file('m/{}A'.format(example))
B = load_matrix_from_file('m/{}B'.format(example))
t_dist = time.time()
C = loader.matrixMultiply(A, B)
t_dist = time.time() - t_dist
t_secu = time.time()
c = matrix_multiply(A,B)
t_secu = time.time() - t_secu
expected = load_matrix_from_file('m/{}C'.format(example))
retval = (C == expected)
print("OK" if retval else "FAIL")
print("El tiempo que ha tardado en distribuido ha sido {}".format(t_dist))
print("El tiempo que ha tardado en secuencial ha sido {}".format(t_secu))
if(C == None): print("Timeout expired")
return not retval
def string_to_proxy(self, str_proxy, iface):
proxy = self.communicator().stringToProxy(str_proxy)
retval = iface.checkedCast(proxy)
if not retval:
raise RuntimeError('Invalid proxy %s' % str_proxy)
return retval
def print_matrix(self, M):
ncols = M.ncols
nrows = len(M.data) / ncols
for r in range(nrows):
print M.data[r * ncols:(r + 1) * ncols]
if __name__ == '__main__':
sys.exit(Client().main(sys.argv))
| apache-2.0 | -3,968,228,681,157,256,000 | 25.342105 | 82 | 0.586414 | false | 3.260586 | false | false | false |
bitcraze/crazyflie-lib-python | test/crtp/test_crtpstack.py | 1 | 2875 | # -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) Bitcraze AB
#
# Crazyflie Nano Quadcopter Client
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import unittest
from cflib.crtp.crtpstack import CRTPPacket
class CRTPPacketTest(unittest.TestCase):
def setUp(self):
self.callback_count = 0
self.sut = CRTPPacket()
def test_that_port_and_channle_is_encoded_in_header(self):
# Fixture
self.sut.set_header(2, 1)
# Test
actual = self.sut.get_header()
# Assert
expected = 0x2d
self.assertEqual(expected, actual)
def test_that_port_is_truncated_in_header(self):
# Fixture
port = 0xff
self.sut.set_header(port, 0)
# Test
actual = self.sut.get_header()
# Assert
expected = 0xfc
self.assertEqual(expected, actual)
def test_that_channel_is_truncated_in_header(self):
# Fixture
channel = 0xff
self.sut.set_header(0, channel)
# Test
actual = self.sut.get_header()
# Assert
expected = 0x0f
self.assertEqual(expected, actual)
def test_that_port_and_channel_is_encoded_in_header_when_set_separat(self):
# Fixture
self.sut.port = 2
self.sut.channel = 1
# Test
actual = self.sut.get_header()
# Assert
expected = 0x2d
self.assertEqual(expected, actual)
def test_that_default_header_is_set_when_constructed(self):
# Fixture
# Test
actual = self.sut.get_header()
# Assert
expected = 0x0c
self.assertEqual(expected, actual)
def test_that_header_is_set_when_constructed(self):
# Fixture
sut = CRTPPacket(header=0x21)
# Test
actual = sut.get_header()
# Assert
self.assertEqual(0x2d, actual)
self.assertEqual(2, sut.port)
self.assertEqual(1, sut.channel)
| gpl-2.0 | 3,989,698,133,982,647 | 26.644231 | 79 | 0.575652 | false | 3.394333 | true | false | false |
csixteen/HackerRank_Python | Algorithms/magic_square.py | 1 | 1071 | class Solution(object):
MAGIC_SQUARES = [
[4, 9, 2, 3, 5, 7, 8, 1, 6],
[2, 9, 4, 7, 5, 3, 6, 1, 8],
[8, 3, 4, 1, 5, 9, 6, 7, 2],
[4, 3, 8, 9, 5, 1, 2, 7, 6],
[6, 1, 8, 7, 5, 3, 2, 9, 4],
[8, 1, 6, 3, 5, 7, 4, 9, 2],
[6, 7, 2, 1, 5, 9, 8, 3, 4],
[2, 7, 6, 9, 5, 1, 4, 3, 8]
]
def magic_square(self, s):
totals = []
for ms in self.MAGIC_SQUARES:
totals.append(sum([abs(ms_e - s_e) for ms_e, s_e in zip(ms, s)]))
return min(totals)
import unittest
class SolutionTest(unittest.TestCase):
def test_magic_square(self):
s = Solution()
self.assertEqual(0, s.magic_square([6, 1, 8, 7, 5, 3, 2, 9, 4]))
self.assertEqual(1, s.magic_square([4, 9, 2, 3, 5, 7, 8, 1, 5]))
self.assertEqual(4, s.magic_square([4, 8, 2, 4, 5, 7, 6, 1, 6]))
self.assertEqual(45, s.magic_square([0, 0, 0, 0, 0, 0, 0, 0, 0]))
self.assertEqual(36, s.magic_square([9, 9, 9, 9, 9, 9, 9, 9, 9]))
if __name__ == "__main__":
unittest.main()
| mit | -3,675,657,614,335,557,600 | 32.46875 | 77 | 0.459384 | false | 2.428571 | true | false | false |
alexpap/exareme | exareme-tools/madis/src/functionslocal/aggregate/approximatedmedian.py | 1 | 2110 | import inspect
import math
import random
import numpy
from fractions import Fraction
import sys
import json
from array import *
class approximatedmedian:
registered = True #Value to define db operator
def __init__(self):
self.n = 0
self.totalnums = 0
self.numberofcolumns = 5
self.colname = []
self.buckets = []
self.minvalues = []
self.maxvalues = []
self.nums = []
def step(self, *args):
try:
self.colname.append(args[0])
self.buckets.append(int(args[1]))
self.minvalues.append(float(args[2]))
self.maxvalues.append(float(args[3]))
self.nums.append(int(args[4]))
self.totalnums += int(args[4])
self.n += 1
except (ValueError, TypeError):
raise
def final(self):
# print self.nums
# print self.totalnums / 2.0
yield ('colname0', 'val', 'bucket', 'numsBeforeMedian', 'numsAfterMedian')
# yield ('attr1', 'attr2', 'val', 'reccount')
currentsum = 0
for i in xrange(0,self.n):
# print i,self.totalnums / 2.0,self.nums[i],currentsum
currentsum += self.nums[i]
if currentsum >= (self.totalnums / 2.0):
break
median = self.minvalues[i]+(currentsum-self.totalnums / 2.0) * (self.maxvalues[i]-self.minvalues[i]) / self.nums[i]
# print (self.totalnums / 2.0), currentsum, currentsum -self.nums[i]
numsBeforeMedian = (self.totalnums / 2.0) - (currentsum - self.nums[i])
numsAfterMedian = currentsum - (self.totalnums / 2.0)
yield self.colname[0], median, i, numsBeforeMedian,numsAfterMedian
if not ('.' in __name__):
"""
This is needed to be able to test the function, put it at the end of every
new function you create
"""
import sys
import setpath
#from functions import *
#testfunction()
if __name__ == "__main__":
reload(sys)
sys.setdefaultencoding('utf-8')
import doctest
doctest.testmod()
| mit | -1,993,861,639,533,290,000 | 23.823529 | 123 | 0.572512 | false | 3.675958 | false | false | false |
fishtown-analytics/dbt | test/integration/041_presto_test/test_simple_presto_view.py | 1 | 2230 | from test.integration.base import DBTIntegrationTest, FakeArgs, use_profile
import random
import time
class TestBasePrestoRun(DBTIntegrationTest):
@property
def schema(self):
return "presto_test_41"
@property
def models(self):
return "models"
@property
def project_config(self):
return {
'config-version': 2,
'data-paths': ['data'],
'macro-paths': ['macros'],
'seeds': {
'quote_columns': False,
},
}
@property
def profile_config(self):
return self.presto_profile()
def assert_nondupes_pass(self):
# The 'dupe' model should fail, but all others should pass
test_results = self.run_dbt(['test'], expect_pass=False)
for result in test_results:
if 'dupe' in result.node.name:
self.assertIsNone(result.error)
self.assertFalse(result.skipped)
self.assertTrue(result.status > 0)
# assert that actual tests pass
else:
self.assertIsNone(result.error)
self.assertFalse(result.skipped)
# status = # of failing rows
self.assertEqual(result.status, 0)
class TestSimplePrestoRun(TestBasePrestoRun):
def setUp(self):
super().setUp()
for conn in self.adapter.connections.in_use.values():
conn.transaction_open
@use_profile('presto')
def test__presto_simple_run(self):
# make sure seed works twice. Full-refresh is a no-op
self.run_dbt(['seed'])
self.run_dbt(['seed', '--full-refresh'])
results = self.run_dbt()
self.assertEqual(len(results), 2)
self.assert_nondupes_pass()
class TestUnderscorePrestoRun(TestBasePrestoRun):
prefix = "_test{}{:04}".format(int(time.time()), random.randint(0, 9999))
@use_profile('presto')
def test_presto_run_twice(self):
self.run_dbt(['seed'])
results = self.run_dbt()
self.assertEqual(len(results), 2)
self.assert_nondupes_pass()
results = self.run_dbt()
self.assertEqual(len(results), 2)
self.assert_nondupes_pass()
| apache-2.0 | 3,608,262,232,624,162,000 | 27.961039 | 77 | 0.583857 | false | 3.891798 | true | false | false |
nihlaeth/Nagios_check_slackpkg | check_slackpkg_nonpriv.py | 1 | 1673 | #!/usr/bin/env python
"""Nagios module for monitoring available updates via slackpkg."""
import subprocess
import sys
import os
# pylint: disable=invalid-name
# run check-updates to poll mirror for changes
result = []
try:
result = subprocess.check_output("myslackpkg check-updates", shell=True).split("\n")
except (OSError, subprocess.CalledProcessError) as error:
print "Failed to check for updates: %s" % error
sys.exit(3)
updates = "idk"
for line in result:
if "good news" in line:
updates = "no"
elif "News on" in line:
updates = "yes"
if updates == "idk":
print "Error parsing slackpkg check-updates status"
sys.exit(3)
elif updates == "yes":
# fetch updated package list
try:
_ = subprocess.check_output("myslackpkg update &> /dev/null", shell=True)
except (OSError, subprocess.CalledProcessError) as error:
print "Failed to update package list: %s" % error
sys.exit(3)
# Now the packages list is up to date, check if we need to upgrade anything
result = []
devnull = open(os.devnull, 'w')
try:
result = subprocess.check_output([
"myslackpkg",
"upgrade-all"], stderr=devnull).split("\n")
except (OSError, subprocess.CalledProcessError) as error:
print "Failed to check for upgrades: %s" % error
sys.exit(3)
packages = []
for line in result:
if ".txz" in line:
packages.append(line.strip())
if "update gpg" in line:
print "Error: need up-to-date gpg key!"
sys.exit(3)
if len(packages) == 0:
print "OK: everything up-to-date"
sys.exit(0)
else:
print "Updates available: " + " ".join(packages)
sys.exit(2)
| gpl-3.0 | 4,253,797,037,185,081,000 | 27.355932 | 88 | 0.654513 | false | 3.529536 | false | false | false |
haphaeu/yoshimi | sql/data_analysis/database.py | 1 | 3122 | from os import path
from sqlalchemy import (create_engine,
Column,
String,
Integer,
Boolean,
Table,
ForeignKey)
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
database_filename = 'twitter.sqlite3'
directory = path.abspath(path.dirname(__file__))
database_filepath = path.join(directory, database_filename)
engine_url = 'sqlite:///{}'.format(database_filepath)
engine = create_engine(engine_url)
# Our database class objects are going to inherit from
# this class
Base = declarative_base(bind=engine)
# create a configured “Session” class
Session = sessionmaker(bind=engine, autoflush=False)
# Create a Session
session = Session()
hashtag_tweet = Table('hashtag_tweet', Base.metadata,
Column('hashtag_id', Integer, ForeignKey('hashtags.id'), nullable=False),
Column('tweet_id', Integer, ForeignKey('tweets.id'), nullable=False))
class Tweet(Base):
__tablename__ = 'tweets'
id = Column(Integer, primary_key=True)
tid = Column(String(100), nullable=False)
tweet = Column(String(300), nullable=False)
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
coordinates = Column(String(50), nullable=True)
user = relationship('User', backref='tweets')
created_at = Column(String(100), nullable=False)
favorite_count = Column(Integer)
in_reply_to_screen_name = Column(String)
in_reply_to_status_id = Column(Integer)
in_reply_to_user_id = Column(Integer)
lang = Column(String)
quoted_status_id = Column(Integer)
retweet_count = Column(Integer)
source = Column(String)
is_retweet = Column(Boolean)
hashtags = relationship('Hashtag',
secondary='hashtag_tweet',
back_populates='tweets')
def __repr__(self):
return '<Tweet {}>'.format(self.id)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
uid = Column(String(50), nullable=False)
name = Column(String(100), nullable=False)
screen_name = Column(String)
created_at = Column(String)
# Nullable
description = Column(String)
followers_count = Column(Integer)
friends_count = Column(Integer)
statuses_count = Column(Integer)
favourites_count = Column(Integer)
listed_count = Column(Integer)
geo_enabled = Column(Boolean)
lang = Column(String)
def __repr__(self):
return '<User {}>'.format(self.id)
class Hashtag(Base):
__tablename__ = 'hashtags'
id = Column(Integer, primary_key=True)
text = Column(String(200), nullable=False)
tweets = relationship('Tweet',
secondary='hashtag_tweet',
back_populates='hashtags')
def __repr__(self):
return '<Hashtag {}>'.format(self.text)
def init_db():
Base.metadata.create_all()
if not path.isfile(database_filepath):
init_db()
| lgpl-3.0 | 5,123,633,034,681,498,000 | 29.271845 | 95 | 0.626042 | false | 3.907268 | false | false | false |
EnceladOnline/interfaX | icon.py | 1 | 1967 | from tkinter import *
from tkinter import ttk
import func
class Icon:
def __init__(self, main, icon):
# Affiche les icon sur le tab
self.main = main
self.master = self.main.cache["CurrentTabID"]
self.icon = icon
if self.icon[1][1] == None:
self.icon_label()
else:
self.icon_image()
def icon_label(self):
self.cadre = ttk.Button(self.main.cache["CurrentTabID"],
text = self.icon[0], command = self.launch,
style = "STYLE_B.TButton", takefocus = 0, cursor = "hand2")
self.icon_tagorid = self.main.cache["CurrentTabID"].create_window(self.icon[2][0],
self.icon[2][1], window = self.cadre, anchor = "se")
self.main.cache["CurrentIconID"] = self.cadre
self.main.cache["CurrentIcon"] = self.icon
# Bind
self.cadre.bind("<Button-3>", self.icon_menu_eventhandler)
# Utilisé dans InterfaX 1
# self.cadre.bind("<Motion>", self.icon_title_eventhandler)
def icon_image(self):
try:
self.main.cache[self.icon[0]] = PhotoImage(file = self.icon[1][1])
except:
self.main.cache[self.icon[0]] = None
self.cadre = ttk.Button(self.main.cache["CurrentTabID"],
image = self.main.cache[self.icon[0]], takefocus = 0,
command = self.launch, cursor = "hand2")
self.icon_tagorid = self.main.cache["CurrentTabID"].create_window(self.icon[2][0],
self.icon[2][1], window = self.cadre, anchor = "se")
# Bind
self.cadre.bind("<Button-3>", self.icon_menu_eventhandler)
self.cadre.bind("<Motion>", self.icon_title_eventhandler)
def launch(self):
path_list = self.icon[3]
func.launcher(path_list)
def icon_menu_eventhandler(self, event):
self.main.cache["CurrentIconID"] = self.cadre
self.main.cache["CurrentIcon"] = self.icon
self.main.cache["CurrentIconTAGORID"] = self.icon_tagorid
self.main.icon_menu_eventhandler()
def icon_title_eventhandler(self, event):
self.main.strvar_icon_title.set(self.icon[0])
| gpl-2.0 | -8,296,808,383,988,564,000 | 22.987805 | 84 | 0.654629 | false | 2.788652 | false | false | false |
wilkinsg/piweb | watched.py | 1 | 2615 | #!/usr/bin/python
import hash
import os
import config
import video_info
watched_cache = {}
def prepwatched( conn ):
global watched_cache
result = conn.execute( "SELECT * FROM history" )
queueitem = result.fetchone()
while( queueitem ):
watched_cache[ queueitem[ 0 ] ] = True
queueitem = result.fetchone()
# def is_list_watched( hashlist, conn ):
# orlist = ( '?,' * len( hashlist ) ).rstrip( ',' )
# result = conn.execute( "SELECT * FROM history WHERE hash in ({})".format( orlist ), tuple( hashlist ) )
# if( result.rowcount() == len( hashlist ) ):
# return( True )
# else:
# return( False )
def is_watched( hash, conn ):
global watched_cache
try:
return( watched_cache[ hash ] )
except KeyError:
result = conn.execute( "SELECT * FROM history WHERE hash = ?", ( hash, ) )
if( result.fetchone() ):
watched_cache[ hash ] = True
return( True )
else:
watched_cache[ hash ] = False
return( False )
def is_directory_watched( dir, conn ):
dir = os.path.join( config.get_media_dir(), dir.lstrip( '/' ) )
for root, dirs, files in os.walk( dir ):
for filename in files:
if( video_info.is_video( filename ) ):
file = os.path.join( root, filename )
if( False == is_watched( hash.hash_name( file ), conn ) ):
return( False )
return( True )
def mark_all_watched( list, conn ):
global watched_cache
for filename in list:
input = hash.hash_name( filename )
if( input and len( input ) == 32 and not is_watched( input, conn ) ):
conn.execute( "INSERT INTO history VALUES( ? )", ( input, ) )
watched_cache[ input ] = True
conn.commit()
def mark_hash_watched( input, conn, docommit=True ):
global watched_cache
if( input and len( input ) == 32 and not is_watched( input, conn ) ):
conn.execute( "INSERT INTO history VALUES( ? )", ( input, ) )
watched_cache[ input ] = True
if( docommit ):
conn.commit()
return True
return( False )
def mark_hash_unwatched( input, conn ):
global watched_cache
if( input and len( input ) == 32 ):
conn.execute( "DELETE FROM history WHERE hash=?", ( input, ) )
watched_cache[ input ] = False
conn.commit()
return True
return( False )
def mark_watched( filename, conn ):
input = hash.hash_name( filename )
mark_hash_watched( input, conn )
| mit | 3,103,893,710,333,927,000 | 30.130952 | 109 | 0.559465 | false | 3.70922 | false | false | false |
yangl1996/libpagure | tests/test_api.py | 1 | 12568 | import pytest
from libpagure import Pagure
@pytest.fixture(scope='module')
def simple_pg():
""" Create a simple Pagure object
to be used in test
"""
pg = Pagure(pagure_repository="testrepo")
return pg
def test_pagure_object():
""" Test the pagure object creation """
pg = Pagure(pagure_token="a token",
pagure_repository="test_repo")
assert pg.token == "a token"
assert pg.repo == "test_repo"
assert pg.namespace is None
assert pg.username is None
assert pg.instance == "https://pagure.io"
assert pg.insecure is False
assert pg.header == {"Authorization": "token a token"}
basic_url_data = [
(None, None, 'testrepo', 'https://pagure.io/api/0/testrepo/'),
(None, 'testnamespace', 'testrepo',
'https://pagure.io/api/0/testnamespace/testrepo/'),
('testfork', None, 'testrepo',
'https://pagure.io/api/0/fork/testfork/testrepo/'),
('testfork', 'testnamespace', 'testrepo',
'https://pagure.io/api/0/fork/testfork/testnamespace/testrepo/'),
]
@pytest.mark.parametrize("user, namespace, repo, expected",
basic_url_data)
def test_create_basic_url(user, namespace, repo, expected):
""" Test creation of url in function of argument
passed to the Pagure class.
"""
pg = Pagure(pagure_repository=repo,
fork_username=user,
namespace=namespace)
url = pg.create_basic_url()
assert url == expected
def test_api_version(mocker, simple_pg):
""" Test the call to the version API """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.api_version()
Pagure._call_api.assert_called_once_with('https://pagure.io/api/0/version')
def test_list_users(mocker, simple_pg):
""" Test the call to the users API """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.list_users(pattern='c')
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/users', params={'pattern': 'c'})
def test_list_tags(mocker, simple_pg):
""" Test the call to the tags API """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.list_tags(pattern='easy')
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/tags', params={'pattern': 'easy'})
def test_list_groups(mocker, simple_pg):
""" Test the call to the groups API """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.list_groups()
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/groups', params=None)
def test_error_codes(mocker, simple_pg):
""" Test the call to the error codes API """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.error_codes()
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/error_codes')
pr_data = [
('teststatus', 'testassignee', 'testauthor',
{'status': 'teststatus', 'assignee': 'testassignee', 'author': 'testauthor'}),
(None, None, None, {})
]
@pytest.mark.parametrize("status, assignee, author, expected", pr_data)
def test_list_requests(mocker, simple_pg, status, assignee, author, expected):
""" Test the API call to the pull-requests endpoint """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.list_requests(status, assignee, author)
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/pull-requests', params=expected)
def test_request_info(mocker, simple_pg):
""" Test the API call to get pull-request info """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.request_info('123')
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/pull-request/123')
def test_merge_request(mocker, simple_pg):
""" Test the API call to merge a pull-request """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.merge_request('123')
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/pull-request/123/merge', method='POST')
def test_close_request(mocker, simple_pg):
""" Test the API call to close a pull-request """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.close_request('123')
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/pull-request/123/close', method='POST')
comment_data = [
("test body", None, None, None, {'comment': 'test body'}),
("test body", "testcommit", "testfilename", "testrow",
{'comment': 'test body', 'commit': 'testcommit', 'filename': 'testfilename',
'row': 'testrow'})
]
@pytest.mark.parametrize("body, commit, filename, row, expected", comment_data)
def test_comment_request(mocker, simple_pg, body, commit, filename, row, expected):
""" Test the API call to comment on a pull-request """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.comment_request('123', body, commit, filename, row)
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/pull-request/123/comment', method='POST',
data=expected)
flag_data = [
('testuser', 'testpercent', 'testcomment', 'testurl', None, None,
{'username': 'testuser', 'percent': 'testpercent', 'comment': 'testcomment',
'url': 'testurl'}),
('testuser', 'testpercent', 'testcomment', 'testurl', 'testuid', 'testcommit',
{'username': 'testuser', 'percent': 'testpercent', 'comment': 'testcomment',
'url': 'testurl', 'uid': 'testuid', 'commit': 'testcommit'})
]
@pytest.mark.parametrize("username, percent, comment, url, uid, commit, expected",
flag_data)
def test_flag_request(mocker, simple_pg, username, percent, comment, url, uid,
commit, expected):
""" Test the API call to flag a pull-request """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.flag_request('123', username, percent, comment, url, uid, commit)
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/pull-request/123/flag', method='POST',
data=expected)
def test_create_issue(mocker, simple_pg):
""" Test the API call to create an issue """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.create_issue('A test issue', 'Some issue content', True)
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/new_issue', method='POST',
data={'title': 'A test issue', 'issue_content': 'Some issue content',
'priority': True})
def test_list_issues(mocker, simple_pg):
""" Test the API call to list all issues of a project """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.list_issues('status', 'tags', 'assignee', 'author',
'milestones', 'priority', 'no_stones', 'since')
expected = {'status': 'status', 'tags': 'tags', 'assignee': 'assignee',
'author': 'author', 'milestones': 'milestones', 'priority': 'priority',
'no_stones': 'no_stones', 'since': 'since'}
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/issues', params=expected)
def test_issue_info(mocker, simple_pg):
""" Test the API call to info about a project issue """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.issue_info('123')
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/issue/123')
def test_list_comment(mocker, simple_pg):
""" Test the API call to info about a project issue """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.get_list_comment('123', '001')
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/issue/123/comment/001')
def test_change_issue_status(mocker, simple_pg):
""" Test the API call to change the status of a project issue """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.change_issue_status('123', 'Closed', 'wontfix')
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/issue/123/status', method='POST',
data={'status': 'Closed', 'close_status': 'wontfix'})
def test_change_issue_milestone(mocker, simple_pg):
""" Test the API call to change the milestone of a project issue """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.change_issue_milestone('123', 'Tomorrow')
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/issue/123/milestone', method='POST',
data={'milestone': 'Tomorrow'})
def test_comment_issue(mocker, simple_pg):
""" Test the API call to change the milestone of a project issue """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.comment_issue('123', 'A comment')
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/issue/123/comment', method='POST',
data={'comment': 'A comment'})
def test_project_tags(mocker, simple_pg):
""" Test the API call to get a project tags """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.project_tags()
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/git/tags')
def test_list_projects(mocker, simple_pg):
""" Test the API call to list all projects on a pagure instance """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.list_projects('tags', 'pattern', 'username', 'owner',
'namespace', 'fork', 'short', 1, 100)
expected = {'tags': 'tags', 'pattern': 'pattern', 'username': 'username',
'owner': 'owner', 'namespace': 'namespace', 'fork': 'fork',
'short': 'short', 'page': '1', 'per_page': '100'}
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/projects', params=expected)
def test_user_info(mocker, simple_pg):
""" Test the API call to get info about a user """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.user_info('auser')
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/user/auser')
def test_new_project(mocker, simple_pg):
""" Test the API call to list all projects on a pagure instance """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.new_project('name', 'description', 'namespace', 'url',
'avatar_email', True, True)
expected = {'name': 'name', 'description': 'description', 'namespace': 'namespace',
'url': 'url', 'avatar_email': 'avatar_email',
'create_readme': True, 'private': True}
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/new', data=expected, method='POST')
def test_project_branches(mocker, simple_pg):
""" Test the API call to get info about a user """
mocker.patch('libpagure.Pagure._call_api')
simple_pg.project_branches()
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/testrepo/git/branches')
def test_user_activity_stats(mocker, simple_pg):
""" Test the API call to get stats about a user activity"""
mocker.patch('libpagure.Pagure._call_api')
simple_pg.user_activity_stats('auser')
expected = {'username': 'auser'}
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/user/auser/activity/stats', params=expected)
def test_user_activity_stats_by_date(mocker, simple_pg):
""" Test the API call to get stats about a user activity by specific date"""
mocker.patch('libpagure.Pagure._call_api')
simple_pg.user_activity_stats_by_date('auser',"2017-12-30")
expected = {'username': 'auser', 'date' : '2017-12-30'}
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/user/auser/activity/2017-12-30', params=expected)
def test_list_pull_requests(mocker, simple_pg):
""" Test the API call to get stats about a user's pull requests"""
mocker.patch('libpagure.Pagure._call_api')
simple_pg.list_pull_requests('auser', 1)
expected = {'username': 'auser', 'page': 1}
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/user/auser/requests/filed', params=expected)
def test_list_prs_actionable_by_user(mocker, simple_pg):
""" Test the API call to list PR's actionable for a given user"""
mocker.patch('libpagure.Pagure._call_api')
simple_pg.list_prs_actionable_by_user('auser', 1)
expected = {'username': 'auser', 'page': 1}
Pagure._call_api.assert_called_once_with(
'https://pagure.io/api/0/user/auser/requests/actionable', params=expected)
| gpl-2.0 | 1,007,721,609,211,840,800 | 38.898413 | 87 | 0.647279 | false | 3.289191 | true | false | false |
nixingyang/Kaggle-Competitions | TalkingData AdTracking Fraud Detection/perform_ensembling.py | 1 | 2489 | import os
import glob
import shutil
import datetime
import numpy as np
import pandas as pd
# Dataset
PROJECT_NAME = "TalkingData AdTracking Fraud Detection"
PROJECT_FOLDER_PATH = os.path.join(os.path.expanduser("~"), "Documents/Dataset",
PROJECT_NAME)
# Submission
TEAM_NAME = "Aurora"
SUBMISSION_FOLDER_PATH = os.path.join(PROJECT_FOLDER_PATH, "submission")
os.makedirs(SUBMISSION_FOLDER_PATH, exist_ok=True)
# Ensembling
WORKSPACE_FOLDER_PATH = os.path.join(PROJECT_FOLDER_PATH, "script/Mar_25_3")
KEYWORD = "DL"
# Generate a zip archive for a file
create_zip_archive = lambda file_path: shutil.make_archive(
file_path[:file_path.rindex(".")], "zip",
os.path.abspath(os.path.join(file_path, "..")), os.path.basename(file_path))
def run():
print("Searching for submissions with keyword {} at {} ...".format(
KEYWORD, WORKSPACE_FOLDER_PATH))
submission_file_path_list = sorted(
glob.glob(os.path.join(WORKSPACE_FOLDER_PATH, "*{}*".format(KEYWORD))))
assert len(submission_file_path_list) != 0
ranking_array_list = []
for submission_file_path in submission_file_path_list:
print("Loading {} ...".format(submission_file_path))
submission_df = pd.read_csv(submission_file_path)
print("Ranking the entries ...")
index_series = submission_df["is_attributed"].argsort()
ranking_array = np.zeros(index_series.shape, dtype=np.uint32)
ranking_array[index_series] = np.arange(len(index_series))
ranking_array_list.append(ranking_array)
ensemble_df = submission_df.copy()
ensemble_prediction_array = np.mean(ranking_array_list, axis=0)
apply_normalization = lambda data_array: 1.0 * (data_array - np.min(
data_array)) / (np.max(data_array) - np.min(data_array))
ensemble_df["is_attributed"] = apply_normalization(
ensemble_prediction_array)
ensemble_file_path = os.path.join(
SUBMISSION_FOLDER_PATH, "{} {} {}.csv".format(
TEAM_NAME, KEYWORD,
str(datetime.datetime.now()).split(".")[0]).replace(" ", "_"))
print("Saving submission to {} ...".format(ensemble_file_path))
ensemble_df.to_csv(ensemble_file_path, float_format="%.6f", index=False)
compressed_ensemble_file_path = create_zip_archive(ensemble_file_path)
print("Saving compressed submission to {} ...".format(
compressed_ensemble_file_path))
print("All done!")
if __name__ == "__main__":
run()
| mit | -8,510,683,944,066,425,000 | 36.712121 | 80 | 0.659703 | false | 3.409589 | false | false | false |
flennerhag/mlens | mlens/externals/sklearn/validation.py | 1 | 27114 | """
Scikit-learn utilities for input validation.
"""
# Authors: Olivier Grisel
# Gael Varoquaux
# Andreas Mueller
# Lars Buitinck
# Alexandre Gramfort
# Nicolas Tresegnie
# License: BSD 3 clause
import warnings
import numbers
import numpy as np
import scipy.sparse as sp
from .. import six
from ...utils.exceptions import NotFittedError, NonBLASDotWarning, \
DataConversionWarning
try:
from inspect import signature
except ImportError:
from mlens.externals.funcsigs import signature
FLOAT_DTYPES = (np.float64, np.float32, np.float16)
# Silenced by default to reduce verbosity. Turn on at runtime for
# performance profiling.
warnings.simplefilter('ignore', NonBLASDotWarning)
def _assert_all_finite(X):
"""Like assert_all_finite, but only for ndarray."""
X = np.asanyarray(X)
# First try an O(n) time, O(1) space solution for the common case that
# everything is finite; fall back to O(n) space np.isfinite to prevent
# false positives from overflow in sum method.
if (X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum())
and not np.isfinite(X).all()):
raise ValueError("Input contains NaN, infinity"
" or a value too large for %r." % X.dtype)
def assert_all_finite(X):
"""Throw a ValueError if X contains NaN or infinity.
Parameters
----------
X : array or sparse matrix
"""
_assert_all_finite(X.data if sp.issparse(X) else X)
def as_float_array(X, copy=True, force_all_finite=True):
"""Converts an array-like to an array of floats.
The new dtype will be np.float32 or np.float64, depending on the original
type. The function can create a copy or modify the argument depending
on the argument copy.
Parameters
----------
X : {array-like, sparse matrix}
copy : bool, optional
If True, a copy of X will be created. If False, a copy may still be
returned if X's dtype is not a floating point type.
force_all_finite : boolean (default=True)
Whether to raise an error on np.inf and np.nan in X.
Returns
-------
XT : {array, sparse matrix}
An array of type np.float
"""
if isinstance(X, np.matrix) or (not isinstance(X, np.ndarray)
and not sp.issparse(X)):
return check_array(X, ['csr', 'csc', 'coo'], dtype=np.float64,
copy=copy, force_all_finite=force_all_finite,
ensure_2d=False)
elif sp.issparse(X) and X.dtype in [np.float32, np.float64]:
return X.copy() if copy else X
elif X.dtype in [np.float32, np.float64]: # is numpy array
return X.copy('F' if X.flags['F_CONTIGUOUS'] else 'C') if copy else X
else:
if X.dtype.kind in 'uib' and X.dtype.itemsize <= 4:
return_dtype = np.float32
else:
return_dtype = np.float64
return X.astype(return_dtype)
def _is_arraylike(x):
"""Returns whether the input is array-like"""
return (hasattr(x, '__len__') or
hasattr(x, 'shape') or
hasattr(x, '__array__'))
def _num_samples(x):
"""Return number of samples in array-like x."""
if hasattr(x, 'fit') and callable(x.fit):
# Don't get num_samples from an ensembles length!
raise TypeError('Expected sequence or array-like, got '
'estimator %s' % x)
if not hasattr(x, '__len__') and not hasattr(x, 'shape'):
if hasattr(x, '__array__'):
x = np.asarray(x)
else:
raise TypeError("Expected sequence or array-like, got %s" %
type(x))
if hasattr(x, 'shape'):
if len(x.shape) == 0:
raise TypeError("Singleton array %r cannot be considered"
" a valid collection." % x)
return x.shape[0]
else:
return len(x)
def _shape_repr(shape):
"""Return a platform independent representation of an array shape
Under Python 2, the `long` type introduces an 'L' suffix when using the
default %r format for tuples of integers (typically used to store the shape
of an array).
Under Windows 64 bit (and Python 2), the `long` type is used by default
in numpy shapes even when the integer dimensions are well below 32 bit.
The platform specific type causes string messages or doctests to change
from one platform to another which is not desirable.
Under Python 3, there is no more `long` type so the `L` suffix is never
introduced in string representation.
>>> _shape_repr((1, 2))
'(1, 2)'
>>> one = 2 ** 64 / 2 ** 64 # force an upcast to `long` under Python 2
>>> _shape_repr((one, 2 * one))
'(1, 2)'
>>> _shape_repr((1,))
'(1,)'
>>> _shape_repr(())
'()'
"""
if len(shape) == 0:
return "()"
joined = ", ".join("%d" % e for e in shape)
if len(shape) == 1:
# special notation for singleton tuples
joined += ','
return "(%s)" % joined
def check_consistent_length(*arrays):
"""Check that all arrays have consistent first dimensions.
Checks whether all objects in arrays have the same shape or length.
Parameters
----------
*arrays : list or tuple of input objects.
Objects that will be checked for consistent length.
"""
lengths = [_num_samples(X) for X in arrays if X is not None]
uniques = np.unique(lengths)
if len(uniques) > 1:
raise ValueError("Found input variables with inconsistent numbers of"
" samples: %r" % [int(l) for l in lengths])
def indexable(*iterables):
"""Make arrays indexable for cross-validation.
Checks consistent length, passes through None, and ensures that everything
can be indexed by converting sparse matrices to csr and converting
non-interable objects to arrays.
Parameters
----------
*iterables : lists, dataframes, arrays, sparse matrices
List of objects to ensure sliceability.
"""
result = []
for X in iterables:
if sp.issparse(X):
result.append(X.tocsr())
elif hasattr(X, "__getitem__") or hasattr(X, "iloc"):
result.append(X)
elif X is None:
result.append(X)
else:
result.append(np.array(X))
check_consistent_length(*result)
return result
def _ensure_sparse_format(spmatrix, accept_sparse, dtype, copy,
force_all_finite):
"""Convert a sparse matrix to a given format.
Checks the sparse format of spmatrix and converts if necessary.
Parameters
----------
spmatrix : scipy sparse matrix
Input to validate and convert.
accept_sparse : string, boolean or list/tuple of strings
String[s] representing allowed sparse matrix formats ('csc',
'csr', 'coo', 'dok', 'bsr', 'lil', 'dia'). If the input is sparse but
not in the allowed format, it will be converted to the first listed
format. True allows the input to be any format. False means
that a sparse matrix input will raise an error.
dtype : string, type or None
Data type of result. If None, the dtype of the input is preserved.
copy : boolean
Whether a forced copy will be triggered. If copy=False, a copy might
be triggered by a conversion.
force_all_finite : boolean
Whether to raise an error on np.inf and np.nan in X.
Returns
-------
spmatrix_converted : scipy sparse matrix.
Matrix that is ensured to have an allowed type.
"""
if dtype is None:
dtype = spmatrix.dtype
changed_format = False
if isinstance(accept_sparse, six.string_types):
accept_sparse = [accept_sparse]
if accept_sparse is False:
raise TypeError('A sparse matrix was passed, but dense '
'data is required. Use X.toarray() to '
'convert to a dense numpy array.')
elif isinstance(accept_sparse, (list, tuple)):
if len(accept_sparse) == 0:
raise ValueError("When providing 'accept_sparse' "
"as a tuple or list, it must contain at "
"least one string value.")
# ensure correct sparse format
if spmatrix.format not in accept_sparse:
# create new with correct sparse
spmatrix = spmatrix.asformat(accept_sparse[0])
changed_format = True
elif accept_sparse is not True:
# any other type
raise ValueError("Parameter 'accept_sparse' should be a string, "
"boolean or list of strings. You provided "
"'accept_sparse={}'.".format(accept_sparse))
if dtype != spmatrix.dtype:
# convert dtype
spmatrix = spmatrix.astype(dtype)
elif copy and not changed_format:
# force copy
spmatrix = spmatrix.copy()
if force_all_finite:
if not hasattr(spmatrix, "data"):
warnings.warn("Can't check %s sparse matrix for nan or inf."
% spmatrix.format)
else:
_assert_all_finite(spmatrix.data)
return spmatrix
def check_array(array, accept_sparse=False, dtype="numeric", order=None,
copy=False, force_all_finite=True, ensure_2d=True,
allow_nd=False, ensure_min_samples=1, ensure_min_features=1,
warn_on_dtype=False, estimator=None):
"""Input validation on an array, list, sparse matrix or similar.
By default, the input is converted to an at least 2D numpy array.
If the dtype of the array is object, attempt converting to float,
raising on failure.
Parameters
----------
array : object
Input object to check / convert.
accept_sparse : string, boolean or list/tuple of strings (default=False)
String[s] representing allowed sparse matrix formats, such as 'csc',
'csr', etc. If the input is sparse but not in the allowed format,
it will be converted to the first listed format. True allows the input
to be any format. False means that a sparse matrix input will
raise an error.
.. deprecated:: 0.19
Passing 'None' to parameter ``accept_sparse`` in methods is
deprecated in version 0.19 "and will be removed in 0.21. Use
``accept_sparse=False`` instead.
dtype : string, type, list of types or None (default="numeric")
Data type of result. If None, the dtype of the input is preserved.
If "numeric", dtype is preserved unless array.dtype is object.
If dtype is a list of types, conversion on the first type is only
performed if the dtype of the input is not in the list.
order : 'F', 'C' or None (default=None)
Whether an array will be forced to be fortran or c-style.
When order is None (default), then if copy=False, nothing is ensured
about the memory layout of the output array; otherwise (copy=True)
the memory layout of the returned array is kept as close as possible
to the original array.
copy : boolean (default=False)
Whether a forced copy will be triggered. If copy=False, a copy might
be triggered by a conversion.
force_all_finite : boolean (default=True)
Whether to raise an error on np.inf and np.nan in X.
ensure_2d : boolean (default=True)
Whether to raise a value error if X is not 2d.
allow_nd : boolean (default=False)
Whether to allow X.ndim > 2.
ensure_min_samples : int (default=1)
Make sure that the array has a minimum number of samples in its first
axis (rows for a 2D array). Setting to 0 disables this check.
ensure_min_features : int (default=1)
Make sure that the 2D array has some minimum number of features
(columns). The default value of 1 rejects empty datasets.
This check is only enforced when the input data has effectively 2
dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0
disables this check.
warn_on_dtype : boolean (default=False)
Raise DataConversionWarning if the dtype of the input data structure
does not match the requested dtype, causing a memory copy.
estimator : str or estimator instance (default=None)
If passed, include the name of the estimator in warning messages.
Returns
-------
X_converted : object
The converted and validated X.
"""
# accept_sparse 'None' deprecation check
if accept_sparse is None:
warnings.warn(
"Passing 'None' to parameter 'accept_sparse' in methods "
"check_array and check_X_y is deprecated in version 0.19 "
"and will be removed in 0.21. Use 'accept_sparse=False' "
" instead.", DeprecationWarning)
accept_sparse = False
# store whether originally we wanted numeric dtype
dtype_numeric = isinstance(dtype, six.string_types) and dtype == "numeric"
dtype_orig = getattr(array, "dtype", None)
if not hasattr(dtype_orig, 'kind'):
# not a data type (e.g. a column named dtype in a pandas DataFrame)
dtype_orig = None
if dtype_numeric:
if dtype_orig is not None and dtype_orig.kind == "O":
# if input is object, convert to float.
dtype = np.float64
else:
dtype = None
if isinstance(dtype, (list, tuple)):
if dtype_orig is not None and dtype_orig in dtype:
# no dtype conversion required
dtype = None
else:
# dtype conversion required. Let's select the first element of the
# list of accepted types.
dtype = dtype[0]
if estimator is not None:
if isinstance(estimator, six.string_types):
estimator_name = estimator
else:
estimator_name = estimator.__class__.__name__
else:
estimator_name = "Estimator"
context = " by %s" % estimator_name if estimator is not None else ""
if sp.issparse(array):
array = _ensure_sparse_format(array, accept_sparse, dtype, copy,
force_all_finite)
else:
array = np.array(array, dtype=dtype, order=order, copy=copy)
if ensure_2d:
if array.ndim == 1:
raise ValueError(
"Expected 2D array, got 1D array instead:\narray={}.\n"
"Reshape your data either using array.reshape(-1, 1) if "
"your data has a single feature or array.reshape(1, -1) "
"if it contains a single sample.".format(array))
array = np.atleast_2d(array)
# To ensure that array flags are maintained
array = np.array(array, dtype=dtype, order=order, copy=copy)
# make sure we actually converted to numeric:
if dtype_numeric and array.dtype.kind == "O":
array = array.astype(np.float64)
if not allow_nd and array.ndim >= 3:
raise ValueError("Found array with dim %d. %s expected <= 2."
% (array.ndim, estimator_name))
if force_all_finite:
_assert_all_finite(array)
shape_repr = _shape_repr(array.shape)
if ensure_min_samples > 0:
n_samples = _num_samples(array)
if n_samples < ensure_min_samples:
raise ValueError("Found array with %d sample(s) (shape=%s) while a"
" minimum of %d is required%s."
% (n_samples, shape_repr, ensure_min_samples,
context))
if ensure_min_features > 0 and array.ndim == 2:
n_features = array.shape[1]
if n_features < ensure_min_features:
raise ValueError("Found array with %d feature(s) (shape=%s) while"
" a minimum of %d is required%s."
% (n_features, shape_repr, ensure_min_features,
context))
if warn_on_dtype and dtype_orig is not None and array.dtype != dtype_orig:
msg = ("Data with input dtype %s was converted to %s%s."
% (dtype_orig, array.dtype, context))
warnings.warn(msg, DataConversionWarning)
return array
def check_X_y(X, y, accept_sparse=False, dtype="numeric", order=None,
copy=False, force_all_finite=True, ensure_2d=True,
allow_nd=False, multi_output=False, ensure_min_samples=1,
ensure_min_features=1, y_numeric=False,
warn_on_dtype=False, estimator=None):
"""Input validation for standard estimators.
Checks X and y for consistent length, enforces X 2d and y 1d.
Standard input checks are only applied to y, such as checking that y
does not have np.nan or np.inf targets. For multi-label y, set
multi_output=True to allow 2d and sparse y. If the dtype of X is
object, attempt converting to float, raising on failure.
Parameters
----------
X : nd-array, list or sparse matrix
Input data.
y : nd-array, list or sparse matrix
Labels.
accept_sparse : string, boolean or list of string (default=False)
String[s] representing allowed sparse matrix formats, such as 'csc',
'csr', etc. If the input is sparse but not in the allowed format,
it will be converted to the first listed format. True allows the input
to be any format. False means that a sparse matrix input will
raise an error.
.. deprecated:: 0.19
Passing 'None' to parameter ``accept_sparse`` in methods is
deprecated in version 0.19 "and will be removed in 0.21. Use
``accept_sparse=False`` instead.
dtype : string, type, list of types or None (default="numeric")
Data type of result. If None, the dtype of the input is preserved.
If "numeric", dtype is preserved unless array.dtype is object.
If dtype is a list of types, conversion on the first type is only
performed if the dtype of the input is not in the list.
order : 'F', 'C' or None (default=None)
Whether an array will be forced to be fortran or c-style.
copy : boolean (default=False)
Whether a forced copy will be triggered. If copy=False, a copy might
be triggered by a conversion.
force_all_finite : boolean (default=True)
Whether to raise an error on np.inf and np.nan in X. This parameter
does not influence whether y can have np.inf or np.nan values.
ensure_2d : boolean (default=True)
Whether to make X at least 2d.
allow_nd : boolean (default=False)
Whether to allow X.ndim > 2.
multi_output : boolean (default=False)
Whether to allow 2-d y (array or sparse matrix). If false, y will be
validated as a vector. y cannot have np.nan or np.inf values if
multi_output=True.
ensure_min_samples : int (default=1)
Make sure that X has a minimum number of samples in its first
axis (rows for a 2D array).
ensure_min_features : int (default=1)
Make sure that the 2D array has some minimum number of features
(columns). The default value of 1 rejects empty datasets.
This check is only enforced when X has effectively 2 dimensions or
is originally 1D and ``ensure_2d`` is True. Setting to 0 disables
this check.
y_numeric : boolean (default=False)
Whether to ensure that y has a numeric type. If dtype of y is object,
it is converted to float64. Should only be used for regression
algorithms.
warn_on_dtype : boolean (default=False)
Raise DataConversionWarning if the dtype of the input data structure
does not match the requested dtype, causing a memory copy.
estimator : str or estimator instance (default=None)
If passed, include the name of the estimator in warning messages.
Returns
-------
X_converted : object
The converted and validated X.
y_converted : object
The converted and validated y.
"""
X = check_array(X, accept_sparse, dtype, order, copy, force_all_finite,
ensure_2d, allow_nd, ensure_min_samples,
ensure_min_features, warn_on_dtype, estimator)
if multi_output:
y = check_array(y, 'csr', force_all_finite=True, ensure_2d=False,
dtype=None)
else:
y = column_or_1d(y, warn=True)
_assert_all_finite(y)
if y_numeric and y.dtype.kind == 'O':
y = y.astype(np.float64)
check_consistent_length(X, y)
return X, y
def column_or_1d(y, warn=False):
""" Ravel column or 1d numpy array, else raises an error
Parameters
----------
y : array-like
warn : boolean, default False
To control display of warnings.
Returns
-------
y : array
"""
shape = np.shape(y)
if len(shape) == 1:
return np.ravel(y)
if len(shape) == 2 and shape[1] == 1:
if warn:
warnings.warn("A column-vector y was passed when a 1d array was"
" expected. Please change the shape of y to "
"(n_samples, ), for example using ravel().",
DataConversionWarning, stacklevel=2)
return np.ravel(y)
raise ValueError("bad input shape {0}".format(shape))
def check_random_state(seed):
"""Turn seed into a np.random.RandomState instance
Parameters
----------
seed : None | int | instance of RandomState
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance seeded with seed.
If seed is already a RandomState instance, return it.
Otherwise raise ValueError.
"""
if seed is None or seed is np.random:
return np.random.mtrand._rand
if isinstance(seed, (numbers.Integral, np.integer)):
return np.random.RandomState(seed)
if isinstance(seed, np.random.RandomState):
return seed
raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
' instance' % seed)
def has_fit_parameter(estimator, parameter):
"""Checks whether the estimator's fit method supports the given parameter.
Parameters
----------
estimator : object
An estimator to inspect.
parameter: str
The searched parameter.
Returns
-------
is_parameter: bool
Whether the parameter was found to be a named parameter of the
estimator's fit method.
Examples
--------
>>> from sklearn.svm import SVC
>>> has_fit_parameter(SVC(), "sample_weight")
True
"""
return parameter in signature(estimator.fit).parameters
def check_symmetric(array, tol=1E-10, raise_warning=True,
raise_exception=False):
"""Make sure that array is 2D, square and symmetric.
If the array is not symmetric, then a symmetrized version is returned.
Optionally, a warning or exception is raised if the matrix is not
symmetric.
Parameters
----------
array : nd-array or sparse matrix
Input object to check / convert. Must be two-dimensional and square,
otherwise a ValueError will be raised.
tol : float
Absolute tolerance for equivalence of arrays. Default = 1E-10.
raise_warning : boolean (default=True)
If True then raise a warning if conversion is required.
raise_exception : boolean (default=False)
If True then raise an exception if array is not symmetric.
Returns
-------
array_sym : ndarray or sparse matrix
Symmetrized version of the input array, i.e. the average of array
and array.transpose(). If sparse, then duplicate entries are first
summed and zeros are eliminated.
"""
if (array.ndim != 2) or (array.shape[0] != array.shape[1]):
raise ValueError("array must be 2-dimensional and square. "
"shape = {0}".format(array.shape))
if sp.issparse(array):
diff = array - array.T
# only csr, csc, and coo have `data` attribute
if diff.format not in ['csr', 'csc', 'coo']:
diff = diff.tocsr()
symmetric = np.all(abs(diff.data) < tol)
else:
symmetric = np.allclose(array, array.T, atol=tol)
if not symmetric:
if raise_exception:
raise ValueError("Array must be symmetric")
if raise_warning:
warnings.warn("Array is not symmetric, and will be converted "
"to symmetric by average with its transpose.")
if sp.issparse(array):
conversion = 'to' + array.format
array = getattr(0.5 * (array + array.T), conversion)()
else:
array = 0.5 * (array + array.T)
return array
def check_is_fitted(estimator, attributes, msg=None, all_or_any=all):
"""Perform is_fitted validation for estimator.
Checks if the estimator is fitted by verifying the presence of
"all_or_any" of the passed attributes and raises a NotFittedError with the
given message.
Parameters
----------
estimator : estimator instance.
estimator instance for which the check is performed.
attributes : attribute name(s) given as string or a list/tuple of strings
Eg.:
``["coef_", "estimator_", ...], "coef_"``
msg : string
The default error message is, "This %(name)s instance is not fitted
yet. Call 'fit' with appropriate arguments before using this method."
For custom messages if "%(name)s" is present in the message string,
it is substituted for the estimator name.
Eg. : "Estimator, %(name)s, must be fitted before sparsifying".
all_or_any : callable, {all, any}, default all
Specify whether all or any of the given attributes must exist.
Returns
-------
None
Raises
------
NotFittedError
If the attributes are not found.
"""
if msg is None:
msg = ("This %(name)s instance is not fitted yet. Call 'fit' with "
"appropriate arguments before using this method.")
if not hasattr(estimator, 'fit'):
raise TypeError("%s is not an estimator instance." % (estimator))
if not isinstance(attributes, (list, tuple)):
attributes = [attributes]
if not all_or_any([hasattr(estimator, attr) for attr in attributes]):
raise NotFittedError(msg % {'name': type(estimator).__name__})
def check_non_negative(X, whom):
"""
Check if there is any negative value in an array.
Parameters
----------
X : array-like or sparse matrix
Input data.
whom : string
Who passed X to this function.
"""
X = X.data if sp.issparse(X) else X
if (X < 0).any():
raise ValueError("Negative values in data passed to %s" % whom)
| mit | 4,532,605,231,950,397,000 | 39.050222 | 79 | 0.615328 | false | 4.181678 | false | false | false |
gregelin/python-ideascaleapi | setup.py | 1 | 1086 | from distutils.core import setup
from ideascaleapi import __version__,__license__,__doc__
license_text = open('LICENSE').read()
long_description = open('README.rst').read()
setup(name="python-ideascaleapi",
version=__version__,
py_modules=["ideascaleapi"],
description="Libraries for interacting with the Ideascale API",
author="Greg Elin (forking James Turk)",
author_email = "[email protected]",
license=license_text,
url="http://github.com/gregelin/python-ideascaleapi/tree/master",
long_description=long_description,
platforms=["any"],
classifiers=["Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
install_requires=["simplejson >= 1.8"]
)
| bsd-3-clause | 1,815,907,163,226,902,500 | 39.222222 | 82 | 0.593923 | false | 4.414634 | false | false | false |
marekjm/diaspy | diaspy/models.py | 1 | 23071 | #!/usr/bin/env python3
"""This module is only imported in other diaspy modules and
MUST NOT import anything.
"""
import json
import copy
import re
BS4_SUPPORT=False
try:
from bs4 import BeautifulSoup
except ImportError:
print("[diaspy] BeautifulSoup not found, falling back on regex.")
else: BS4_SUPPORT=True
from diaspy import errors
class Aspect():
"""This class represents an aspect.
Class can be initialized by passing either an id and/or name as
parameters.
If both are missing, an exception will be raised.
"""
def __init__(self, connection, id, name=None):
self._connection = connection
self.id, self.name = id, name
self._cached = []
def getUsers(self, fetch = True):
"""Returns list of GUIDs of users who are listed in this aspect.
"""
if fetch:
request = self._connection.get('contacts.json?a_id={}'.format(self.id))
self._cached = request.json()
return self._cached
def removeAspect(self):
"""
--> POST /aspects/{id} HTTP/1.1
--> _method=delete&authenticity_token={token}
<-- HTTP/1.1 302 Found
Removes whole aspect.
:returns: None
"""
request = self._connection.tokenFrom('contacts').delete('aspects/{}'.format(self.id))
if request.status_code != 302:
raise errors.AspectError('wrong status code: {0}'.format(request.status_code))
def addUser(self, user_id):
"""Add user to current aspect.
:param user_id: user to add to aspect
:type user_id: int
:returns: JSON from request
--> POST /aspect_memberships HTTP/1.1
--> Accept: application/json, text/javascript, */*; q=0.01
--> Content-Type: application/json; charset=UTF-8
--> {"aspect_id":123,"person_id":123}
<-- HTTP/1.1 200 OK
"""
data = {'aspect_id': self.id,
'person_id': user_id}
headers = {'content-type': 'application/json',
'accept': 'application/json'}
request = self._connection.tokenFrom('contacts').post('aspect_memberships', data=json.dumps(data), headers=headers)
if request.status_code == 400:
raise errors.AspectError('duplicate record, user already exists in aspect: {0}'.format(request.status_code))
elif request.status_code == 404:
raise errors.AspectError('user not found from this pod: {0}'.format(request.status_code))
elif request.status_code != 200:
raise errors.AspectError('wrong status code: {0}'.format(request.status_code))
response = None
try:
response = request.json()
except json.decoder.JSONDecodeError:
""" Should be OK now, but I'll leave this commentary here
at first to see if anything comes up """
# FIXME For some (?) reason removing users from aspects works, but
# adding them is a no-go and Diaspora* kicks us out with CSRF errors.
# Weird.
pass
if response is None:
raise errors.CSRFProtectionKickedIn()
# Now you should fetchguid(fetch_stream=False) on User to update aspect membership_id's
# Or update it locally with the response
return response
def removeUser(self, user):
"""Remove user from current aspect.
:param user: user to remove from aspect
:type user: diaspy.people.User object
"""
membership_id = None
to_remove = None
for each in user.aspectMemberships():
if each.get('aspect', {}).get('id') == self.id:
membership_id = each.get('id')
to_remove = each
break # no need to continue
if membership_id is None:
raise errors.UserIsNotMemberOfAspect(user, self)
request = self._connection.delete('aspect_memberships/{0}'.format(membership_id))
if request.status_code == 404:
raise errors.AspectError('cannot remove user from aspect, probably tried too fast after adding: {0}'.format(request.status_code))
elif request.status_code != 200:
raise errors.AspectError('cannot remove user from aspect: {0}'.format(request.status_code))
if 'contact' in user.data: # User object
if to_remove: user.data['contact']['aspect_memberships'].remove( to_remove ) # remove local aspect membership_id
else: # User object from Contacts()
if to_remove: user.data['aspect_memberships'].remove( to_remove ) # remove local aspect membership_id
return request.json()
class Notification():
"""This class represents single notification.
"""
_who_regexp = re.compile(r'/people/([0-9a-f]+)["\']{1} class=["\']{1}hovercardable')
_aboutid_regexp = re.compile(r'/posts/[0-9a-f]+')
_htmltag_regexp = re.compile('</?[a-z]+( *[a-z_-]+=["\'].*?["\'])* */?>')
def __init__(self, connection, data):
self._connection = connection
self.type = data['type']
self._data = data[self.type]
self.id = self._data['id']
self.unread = self._data['unread']
def __getitem__(self, key):
"""Returns a key from notification data.
"""
return self._data[key]
def __str__(self):
"""Returns notification note.
"""
if BS4_SUPPORT:
soup = BeautifulSoup(self._data['note_html'], 'lxml')
media_body = soup.find('div', {"class": "media-body"})
div = media_body.find('div')
if div: div.decompose()
return media_body.getText().strip()
else:
string = re.sub(self._htmltag_regexp, '', self._data['note_html'])
string = string.strip().split('\n')[0]
while ' ' in string: string = string.replace(' ', ' ')
return string
def __repr__(self):
"""Returns notification note with more details.
"""
return '{0}: {1}'.format(self.when(), str(self))
def about(self):
"""Returns id of post about which the notification is informing OR:
If the id is None it means that it's about user so .who() is called.
"""
if BS4_SUPPORT:
soup = BeautifulSoup(self._data['note_html'], 'lxml')
id = soup.find('a', {"data-ref": True})
if id: return id['data-ref']
about = self._aboutid_regexp.search(self._data['note_html'])
if about is None: about = self.who()[0]
else: about = int(about.group(0)[7:])
return about
def who(self):
"""Returns list of guids of the users who caused you to get the notification.
"""
if BS4_SUPPORT: # Parse the HTML with BS4
soup = BeautifulSoup(self._data['note_html'], 'lxml')
hovercardable_soup = soup.findAll('a', {"class": "hovercardable"})
return list(set([soup['href'][8:] for soup in hovercardable_soup]))
else:
return list(set([who for who in self._who_regexp.findall(self._data['note_html'])]))
def when(self):
"""Returns UTC time as found in note_html.
"""
return self._data['created_at']
def mark(self, unread=False):
"""Marks notification to read/unread.
Marks notification to read if `unread` is False.
Marks notification to unread if `unread` is True.
:param unread: which state set for notification
:type unread: bool
"""
headers = {'x-csrf-token': repr(self._connection)}
params = {'set_unread': json.dumps(unread)}
self._connection.put('notifications/{0}'.format(self['id']), params=params, headers=headers)
self._data['unread'] = unread
class Conversation():
"""This class represents a conversation.
.. note::
Remember that you need to have access to the conversation.
"""
if not BS4_SUPPORT:
_message_stream_regexp = re.compile(r'<div class=["\']{1}stream["\']{1}>(.*?)<div class=["\']{1}stream-element new-message["\']{1}>', re.DOTALL)
_message_guid_regexp = re.compile(r'data-guid=["\']{1}([0-9]+)["\']{1}')
_message_created_at_regexp = re.compile(r'<time datetime=["\']{1}([0-9]{4}-[0-9]{2}-[0-9]{1,2}T[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}Z)["\']{1}')
_message_body_regexp = re.compile(r'<div class=["\']{1}message-content["\']{1}>\s+<p>(.*?)</p>\s+</div>', re.DOTALL)
_message_author_guid_regexp = re.compile(r'<a href=["\']{1}/people/([a-f0-9]+)["\']{1} class=["\']{1}img')
_message_author_name_regexp = re.compile(r'<img alt=["\']{1}(.*?)["\']{1}.*')
_message_author_avatar_regexp = re.compile(r'src=["\']{1}(.*?)["\']{1}')
def __init__(self, connection, id, fetch=True):
"""
:param conv_id: id of the post and not the guid!
:type conv_id: str
:param connection: connection object used to authenticate
:type connection: connection.Connection
"""
self._connection = connection
self.id = id
self._data = {}
self._messages = []
if fetch: self._fetch()
def __len__(self): return len(self._messages)
def __iter__(self): return iter(self._messages)
def __getitem__(self, n): return self._messages[n]
def _fetch(self):
"""Fetches JSON data representing conversation.
"""
request = self._connection.get('conversations/{}.json'.format(self.id))
if request.status_code == 200:
self._data = request.json()['conversation']
else:
raise errors.ConversationError('cannot download conversation data: {0}'.format(request.status_code))
def _fetch_messages(self):
"""Fetches HTML data we will use to parse message data.
This is a workaround until Diaspora* has it's API plans implemented.
"""
request = self._connection.get('conversations/{}'.format(self.id))
if request.status_code == 200:
# Clear potential old messages
self._messages = []
message_template = {
'guid' : None,
'created_at' : None,
'body' : None,
'author' : {
'guid' : None,
'diaspora_id' : None, # TODO? Not able to get from this page.
'name' : None,
'avatar' : None
}
}
if BS4_SUPPORT: # Parse the HTML with BS4
soup = BeautifulSoup(request.content, 'lxml')
messages_soup = soup.findAll('div', {"class": "stream-element message"})
for message_soup in messages_soup:
message = copy.deepcopy(message_template)
# guid
if message_soup and message_soup.has_attr('data-guid'):
message['guid'] = message_soup['data-guid']
# created_at
time_soup = message_soup.find('time', {"class": "timeago"})
if time_soup and time_soup.has_attr('datetime'):
message['created_at'] = time_soup['datetime']
# body
body_soup = message_soup.find('div', {"class": "message-content"})
if body_soup: message['body'] = body_soup.get_text().strip()
# author
author_a_soup = message_soup.find('a', {"class": "img"})
if author_a_soup:
# author guid
message['author']['guid'] = author_a_soup['href'][8:]
# name and avatar
author_img_soup = author_a_soup.find('img', {"class": "avatar"})
if author_img_soup:
message['author']['name'] = author_img_soup['title']
message['author']['avatar'] = author_img_soup['src']
self._messages.append(message.copy())
else: # Regex fallback
messages_stream_html = self._message_stream_regexp.search(request.content.decode('utf-8'))
if messages_stream_html:
messages_html = messages_stream_html.group(1).split("<div class='stream-element message'")
for message_html in messages_html:
message = copy.deepcopy(message_template)
# Guid
guid = self._message_guid_regexp.search(message_html)
if guid: message['guid'] = guid.group(1)
else: continue
# Created at
created_at = self._message_created_at_regexp.search(message_html)
if created_at: message['created_at'] = created_at.group(1)
# Body
body = self._message_body_regexp.search(message_html)
if body: message['body'] = body.group(1)
# Author
author_guid = self._message_author_guid_regexp.search(message_html)
if author_guid: message['author']['guid'] = author_guid.group(1)
author_name = self._message_author_name_regexp.search(message_html)
if author_name:
message['author']['name'] = author_name.group(1)
author_avatar = self._message_author_avatar_regexp.search(author_name.group(0))
if author_avatar: message['author']['avatar'] = author_avatar.group(1)
self._messages.append(message.copy())
else:
raise errors.ConversationError('cannot download message data from conversation: {0}'.format(request.status_code))
def messages(self): return self._messages
def update_messages(self):
"""(Re-)fetches messages in this conversation.
"""
self._fetch_messages()
def answer(self, text):
"""Answer that conversation
:param text: text to answer.
:type text: str
"""
data = {'message[text]': text,
'utf8': '✓',
'authenticity_token': repr(self._connection)}
request = self._connection.post('conversations/{}/messages'.format(self.id),
data=data,
headers={'accept': 'application/json'})
if request.status_code != 200:
raise errors.ConversationError('{0}: Answer could not be posted.'
.format(request.status_code))
return request.json()
def delete(self):
"""Delete this conversation.
Has to be implemented.
"""
data = {'authenticity_token': repr(self._connection)}
request = self._connection.delete('conversations/{0}/visibility/'
.format(self.id),
data=data,
headers={'accept': 'application/json'})
if request.status_code != 404:
raise errors.ConversationError('{0}: Conversation could not be deleted.'
.format(request.status_code))
def get_subject(self):
"""Returns the subject of this conversation
"""
return self._data['subject']
class Comment():
"""Represents comment on post.
Does not require Connection() object. Note that you should not manually
create `Comment()` objects -- they are designed to be created automatically
by `Comments()` objects wich automatically will be created by `Post()`
objects.
"""
def __init__(self, data):
self._data = data
self.id = data['id']
self.guid = data['guid']
def __str__(self):
"""Returns comment's text.
"""
return self._data['text']
def __repr__(self):
"""Returns comments text and author.
Format: AUTHOR (AUTHOR'S GUID): COMMENT
"""
return '{0} ({1}): {2}'.format(self.author(), self.author('guid'), str(self))
def when(self):
"""Returns time when the comment had been created.
"""
return self._data['created_at']
def author(self, key='name'):
"""Returns author of the comment.
"""
return self._data['author'][key]
class Comments():
def __init__(self, comments=[]):
self._comments = comments
def __iter__(self):
for comment in self._comments: yield comment
def __len__(self):
return len(self._comments)
def __getitem__(self, index):
if self._comments: return self._comments[index]
def __bool__(self):
if self._comments: return True
return False
def ids(self):
return [c.id for c in self._comments]
def add(self, comment):
""" Expects Comment() object
:param comment: Comment() object to add.
:type comment: Comment() object."""
if comment and type(comment) == Comment: self._comments.append(comment)
def set(self, comments):
"""Sets comments wich already have a Comment() obj
:param comments: list with Comment() objects to set.
:type comments: list.
"""
if comments: self._comments = comments
def set_json(self, json_comments):
"""Sets comments for this post from post data."""
if json_comments:
self._comments = [Comment(c) for c in json_comments]
class Post():
"""This class represents a post.
.. note::
Remember that you need to have access to the post.
"""
def __init__(self, connection, id=0, guid='', fetch=True, comments=True, post_data=None):
"""
:param id: id of the post (GUID is recommended)
:type id: int
:param guid: GUID of the post
:type guid: str
:param connection: connection object used to authenticate
:type connection: connection.Connection
:param fetch: defines whether to fetch post's data or not
:type fetch: bool
:param comments: defines whether to fetch post's comments or not (if True also data will be fetched)
:type comments: bool
:param post_data: contains post data so no need to fetch the post if this is set, until you want to update post data
:type: json
"""
if not (guid or id): raise TypeError('neither guid nor id was provided')
self._connection = connection
self.id = id
self.guid = guid
self._data = {}
self.comments = Comments()
if post_data:
self._data = post_data
if fetch: self._fetchdata()
if comments:
if not self._data: self._fetchdata()
self._fetchcomments()
else:
if not self._data: self._fetchdata()
self.comments.set_json( self.data()['interactions']['comments'] )
def __repr__(self):
"""Returns string containing more information then str().
"""
return '{0} ({1}): {2}'.format(self._data['author']['name'], self._data['author']['guid'], self._data['text'])
def __str__(self):
"""Returns text of a post.
"""
return self._data['text']
def _fetchdata(self):
"""This function retrieves data of the post.
:returns: guid of post whose data was fetched
"""
if self.id: id = self.id
if self.guid: id = self.guid
request = self._connection.get('posts/{0}.json'.format(id))
if request.status_code != 200:
raise errors.PostError('{0}: could not fetch data for post: {1}'.format(request.status_code, id))
elif request:
self._data = request.json()
return self.data()['guid']
def _fetchcomments(self):
"""Retreives comments for this post.
Retrieving comments via GUID will result in 404 error.
DIASPORA* does not supply comments through /posts/:guid/ endpoint.
"""
id = self.data()['id']
if self.data()['interactions']['comments_count']:
request = self._connection.get('posts/{0}/comments.json'.format(id))
if request.status_code != 200:
raise errors.PostError('{0}: could not fetch comments for post: {1}'.format(request.status_code, id))
else:
self.comments.set([Comment(c) for c in request.json()])
def fetch(self, comments = False):
"""Fetches post data.
"""
self._fetchdata()
if comments:
self._fetchcomments()
return self
def data(self, data = None):
if data is not None:
self._data = data
return self._data
def like(self):
"""This function likes a post.
It abstracts the 'Like' functionality.
:returns: dict -- json formatted like object.
"""
data = {'authenticity_token': repr(self._connection)}
request = self._connection.post('posts/{0}/likes'.format(self.id),
data=data,
headers={'accept': 'application/json'})
if request.status_code != 201:
raise errors.PostError('{0}: Post could not be liked.'
.format(request.status_code))
likes_json = request.json()
if likes_json:
self._data['interactions']['likes'] = [likes_json]
return likes_json
def reshare(self):
"""This function reshares a post
"""
data = {'root_guid': self._data['guid'],
'authenticity_token': repr(self._connection)}
request = self._connection.post('reshares',
data=data,
headers={'accept': 'application/json'})
if request.status_code != 201:
raise Exception('{0}: Post could not be reshared'.format(request.status_code))
return request.json()
def comment(self, text):
"""This function comments on a post
:param text: text to comment.
:type text: str
"""
data = {'text': text,
'authenticity_token': repr(self._connection)}
request = self._connection.post('posts/{0}/comments'.format(self.id),
data=data,
headers={'accept': 'application/json'})
if request.status_code != 201:
raise Exception('{0}: Comment could not be posted.'
.format(request.status_code))
return Comment(request.json())
def vote_poll(self, poll_answer_id):
"""This function votes on a post's poll
:param poll_answer_id: id to poll vote.
:type poll_answer_id: int
"""
poll_id = self._data['poll']['poll_id']
data = {'poll_answer_id': poll_answer_id,
'poll_id': poll_id,
'post_id': self.id,
'authenticity_token': repr(self._connection)}
request = self._connection.post('posts/{0}/poll_participations'.format(self.id),
data=data,
headers={'accept': 'application/json'})
if request.status_code != 201:
raise Exception('{0}: Vote on poll failed.'
.format(request.status_code))
return request.json()
def hide(self):
"""
-> PUT /share_visibilities/42 HTTP/1.1
post_id=123
<- HTTP/1.1 200 OK
"""
headers = {'x-csrf-token': repr(self._connection)}
params = {'post_id': json.dumps(self.id)}
request = self._connection.put('share_visibilities/42', params=params, headers=headers)
if request.status_code != 200:
raise Exception('{0}: Failed to hide post.'
.format(request.status_code))
def mute(self):
"""
-> POST /blocks HTTP/1.1
{"block":{"person_id":123}}
<- HTTP/1.1 204 No Content
"""
headers = {'content-type':'application/json', 'x-csrf-token': repr(self._connection)}
data = json.dumps({ 'block': { 'person_id' : self._data['author']['id'] } })
request = self._connection.post('blocks', data=data, headers=headers)
if request.status_code != 204:
raise Exception('{0}: Failed to block person'
.format(request.status_code))
def subscribe(self):
"""
-> POST /posts/123/participation HTTP/1.1
<- HTTP/1.1 201 Created
"""
headers = {'x-csrf-token': repr(self._connection)}
data = {}
request = self._connection.post('posts/{}/participation'
.format( self.id ), data=data, headers=headers)
if request.status_code != 201:
raise Exception('{0}: Failed to subscribe to post'
.format(request.status_code))
def unsubscribe(self):
"""
-> POST /posts/123/participation HTTP/1.1
_method=delete
<- HTTP/1.1 200 OK
"""
headers = {'x-csrf-token': repr(self._connection)}
data = { "_method": "delete" }
request = self._connection.post('posts/{}/participation'
.format( self.id ), headers=headers, data=data)
if request.status_code != 200:
raise Exception('{0}: Failed to unsubscribe to post'
.format(request.status_code))
def report(self):
"""
TODO
"""
pass
def delete(self):
""" This function deletes this post
"""
data = {'authenticity_token': repr(self._connection)}
request = self._connection.delete('posts/{0}'.format(self.id),
data=data,
headers={'accept': 'application/json'})
if request.status_code != 204:
raise errors.PostError('{0}: Post could not be deleted'.format(request.status_code))
def delete_comment(self, comment_id):
"""This function removes a comment from a post
:param comment_id: id of the comment to remove.
:type comment_id: str
"""
data = {'authenticity_token': repr(self._connection)}
request = self._connection.delete('posts/{0}/comments/{1}'
.format(self.id, comment_id),
data=data,
headers={'accept': 'application/json'})
if request.status_code != 204:
raise errors.PostError('{0}: Comment could not be deleted'
.format(request.status_code))
def delete_like(self):
"""This function removes a like from a post
"""
data = {'authenticity_token': repr(self._connection)}
url = 'posts/{0}/likes/{1}'.format(self.id, self._data['interactions']['likes'][0]['id'])
request = self._connection.delete(url, data=data)
if request.status_code != 204:
raise errors.PostError('{0}: Like could not be removed.'
.format(request.status_code))
def author(self, key='name'):
"""Returns author of the post.
:param key: all keys available in data['author']
"""
return self._data['author'][key]
| mit | 5,489,278,063,691,003,000 | 30.954294 | 146 | 0.653158 | false | 3.203416 | false | false | false |
matousc89/padasip | padasip/filters/nlmf.py | 1 | 5444 | """
.. versionadded:: 1.1.0
The least-mean-fourth (LMF) adaptive filter implemented according to the
paper :cite:`zerguine2000convergence`. The NLMF is an extension of the LMF
adaptive filter (:ref:`filter-lmf`).
The NLMF filter can be created as follows
>>> import padasip as pa
>>> pa.filters.FilterNLMF(n)
where `n` is the size (number of taps) of the filter.
Content of this page:
.. contents::
:local:
:depth: 1
.. seealso:: :ref:`filters`
Algorithm Explanation
======================================
The NLMF is extension of LMF filter. See :ref:`filter-lmf`
for explanation of the algorithm behind.
The extension is based on normalization of learning rate.
The learning rage :math:`\mu` is replaced by learning rate :math:`\eta(k)`
normalized with every new sample according to input power as follows
:math:`\eta (k) = \\frac{\mu}{\epsilon + || \\textbf{x}(k) ||^2}`,
where :math:`|| \\textbf{x}(k) ||^2` is norm of input vector and
:math:`\epsilon` is a small positive constant (regularization term).
This constant is introduced to preserve the stability in cases where
the input is close to zero.
Minimal Working Examples
======================================
If you have measured data you may filter it as follows
.. code-block:: python
import numpy as np
import matplotlib.pylab as plt
import padasip as pa
# creation of data
N = 500
x = np.random.normal(0, 1, (N, 4)) # input matrix
v = np.random.normal(0, 0.1, N) # noise
d = 2*x[:,0] + 0.1*x[:,1] - 0.3*x[:,2] + 0.5*x[:,3] + v # target
# identification
f = pa.filters.FilterNLMF(n=4, mu=0.005, w="random")
y, e, w = f.run(d, x)
# show results
plt.figure(figsize=(15,9))
plt.subplot(211);plt.title("Adaptation");plt.xlabel("samples - k")
plt.plot(d,"b", label="d - target")
plt.plot(y,"g", label="y - output");plt.legend()
plt.subplot(212);plt.title("Filter error");plt.xlabel("samples - k")
plt.plot(10*np.log10(e**2),"r", label="e - error [dB]");plt.legend()
plt.tight_layout()
plt.show()
References
======================================
.. bibliography:: lmf.bib
:style: plain
Code Explanation
======================================
"""
import numpy as np
from padasip.filters.base_filter import AdaptiveFilter
class FilterNLMF(AdaptiveFilter):
"""
Adaptive NLMF filter.
**Args:**
* `n` : length of filter (integer) - how many input is input array
(row of input matrix)
**Kwargs:**
* `mu` : learning rate (float). Also known as step size.
If it is too slow,
the filter may have bad performance. If it is too high,
the filter will be unstable. The default value can be unstable
for ill-conditioned input data.
* `eps` : regularization term (float). It is introduced to preserve
stability for close-to-zero input vectors
* `w` : initial weights of filter. Possible values are:
* array with initial weights (1 dimensional array) of filter size
* "random" : create random weights
* "zeros" : create zero value weights
"""
def __init__(self, n, mu=0.1, eps=1., w="random"):
self.kind = "NLMF filter"
if type(n) == int:
self.n = n
else:
raise ValueError('The size of filter must be an integer')
self.mu = self.check_float_param(mu, 0, 1000, "mu")
self.eps = self.check_float_param(eps, 0, 1000, "eps")
self.init_weights(w, self.n)
self.w_history = False
def adapt(self, d, x):
"""
Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array)
"""
y = np.dot(self.w, x)
e = d - y
nu = self.mu / (self.eps + np.dot(x, x))
self.w += nu * x * e**3
def run(self, d, x):
"""
This function filters multiple samples in a row.
**Args:**
* `d` : desired value (1 dimensional array)
* `x` : input matrix (2-dimensional array). Rows are samples,
columns are input arrays.
**Returns:**
* `y` : output value (1 dimensional array).
The size corresponds with the desired value.
* `e` : filter error for every sample (1 dimensional array).
The size corresponds with the desired value.
* `w` : history of all weights (2 dimensional array).
Every row is set of the weights for given sample.
"""
# measure the data and check if the dimmension agree
N = len(x)
if not len(d) == N:
raise ValueError('The length of vector d and matrix x must agree.')
self.n = len(x[0])
# prepare data
try:
x = np.array(x)
d = np.array(d)
except:
raise ValueError('Impossible to convert x or d to a numpy array')
# create empty arrays
y = np.zeros(N)
e = np.zeros(N)
self.w_history = np.zeros((N,self.n))
# adaptation loop
for k in range(N):
self.w_history[k,:] = self.w
y[k] = np.dot(self.w, x[k])
e[k] = d[k] - y[k]
nu = self.mu / (self.eps + np.dot(x[k], x[k]))
dw = nu * x[k] * e[k]**3
self.w += dw
return y, e, self.w_history
| mit | -1,379,382,755,198,736,400 | 28.586957 | 81 | 0.568883 | false | 3.55817 | false | false | false |
tachijuan/python | myscripts/imap.py | 1 | 1470 | import os, sys, imaplib, rfc822, re, StringIO
import RPi.GPIO as GPIO
import time
server ='mail.xxx.us'
username='[email protected]'
password='xxx'
GPIO.setmode(GPIO.BOARD)
GREEN_LED = 22
RED_LED = 7
GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.setup(RED_LED, GPIO.OUT)
M = imaplib.IMAP4_SSL(server)
M.login(username, password)
M.select()
try:
while 1:
print "checking email"
typ, data = M.search(None, '(UNSEEN SUBJECT "PIFI MESSAGE")')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
#print 'Message %s\n%s\n' % (num, data[0][1])
redon = re.search( "RED ON",
data[0][1],
re.MULTILINE|re.DOTALL )
greenon = re.search( "GREEN ON",
data[0][1],
re.MULTILINE|re.DOTALL )
redoff = re.search( "RED OFF",
data[0][1],
re.MULTILINE|re.DOTALL )
greenoff = re.search( "GREEN OFF",
data[0][1],
re.MULTILINE|re.DOTALL )
if redon:
GPIO.output(RED_LED, True)
print "red on"
if greenon:
GPIO.output(GREEN_LED, True)
print "green on"
if redoff:
GPIO.output(RED_LED, False)
print "red off"
if greenoff:
GPIO.output(GREEN_LED, False)
print "green off"
time.sleep(120)
except KeyboardInterrupt:
GPIO.cleanup()
pass
M.close()
M.logout()
| mit | -6,482,561,999,222,598,000 | 21.96875 | 65 | 0.535374 | false | 3.230769 | false | false | false |
LevinJ/Supply-demand-forecasting | implement/xgboostmodel.py | 1 | 4070 | import sys
import os
sys.path.insert(0, os.path.abspath('..'))
from preprocess.preparedata import PrepareData
import numpy as np
from utility.runtype import RunType
from utility.datafilepath import g_singletonDataFilePath
from preprocess.splittrainvalidation import HoldoutSplitMethod
import xgboost as xgb
from evaluation.sklearnmape import mean_absolute_percentage_error_xgboost
from evaluation.sklearnmape import mean_absolute_percentage_error
from utility.modelframework import ModelFramework
from utility.xgbbasemodel import XGBoostGridSearch
from evaluation.sklearnmape import mean_absolute_percentage_error_xgboost_cv
from utility.xgbbasemodel import XGBoostBase
import logging
import sys
class DidiXGBoostModel(XGBoostBase, PrepareData, XGBoostGridSearch):
def __init__(self):
PrepareData.__init__(self)
XGBoostGridSearch.__init__(self)
XGBoostBase.__init__(self)
self.best_score_colname_in_cv = 'test-mape-mean'
self.do_cross_val = False
self.train_validation_foldid = -2
if self.do_cross_val is None:
root = logging.getLogger()
root.setLevel(logging.DEBUG)
root.addHandler(logging.StreamHandler(sys.stdout))
root.addHandler(logging.FileHandler('logs/finetune_parameters.log', mode='w'))
return
def set_xgb_parameters(self):
early_stopping_rounds = 3
self.xgb_params = {'silent':1, 'colsample_bytree': 0.8, 'silent': 1, 'lambda ': 1, 'min_child_weight': 1, 'subsample': 0.8, 'eta': 0.01, 'objective': 'reg:linear', 'max_depth': 7}
# self.xgb_params = {'silent':1 }
self.xgb_learning_params = {
'num_boost_round': 200,
'callbacks':[xgb.callback.print_evaluation(show_stdv=True),xgb.callback.early_stop(early_stopping_rounds)],
'feval':mean_absolute_percentage_error_xgboost_cv}
if self.do_cross_val == False:
self.xgb_learning_params['feval'] = mean_absolute_percentage_error_xgboost
return
def get_paramgrid_1(self):
"""
This method must be overriden by derived class when its objective is not reg:linear
"""
param_grid = {'max_depth':[6], 'eta':[0.1], 'min_child_weight':[1],'silent':[1],
'objective':['reg:linear'],'colsample_bytree':[0.8],'subsample':[0.8], 'lambda ':[1]}
return param_grid
def get_paramgrid_2(self, param_grid):
"""
This method must be overriden by derived class if it intends to fine tune parameters
"""
self.ramdonized_search_enable = False
self.randomized_search_n_iter = 150
self.grid_search_display_result = True
param_grid['eta'] = [0.01] #train-mape:-0.448062+0.00334926 test-mape:-0.448402+0.00601761
# param_grid['max_depth'] = [7] #train-mape:-0.363007+0.00454276 test-mape:-0.452832+0.00321641
# param_grid['colsample_bytree'] = [0.8]
param_grid['max_depth'] = range(5,8) #train-mape:-0.363007+0.00454276 test-mape:-0.452832+0.00321641
param_grid['colsample_bytree'] = [0.6,0.8,1.0]
# param_grid['lambda'] = range(1,15)
# param_grid['max_depth'] = [3,4]
# param_grid['eta'] = [0.01,0.1] # 0.459426+0.00518875
# param_grid['subsample'] = [0.5] #0.458935+0.00522205
# param_grid['eta'] = [0.005] #0.457677+0.00526401
return param_grid
def get_learning_params(self):
"""e
This method must be overriden by derived class if it intends to fine tune parameters
"""
num_boost_round = 100
early_stopping_rounds = 5
kwargs = {'num_boost_round':num_boost_round, 'feval':mean_absolute_percentage_error_xgboost_cv,
'callbacks':[xgb.callback.print_evaluation(show_stdv=True),xgb.callback.early_stop(early_stopping_rounds)]}
return kwargs
if __name__ == "__main__":
obj= DidiXGBoostModel()
obj.run() | mit | 3,712,276,902,335,813,600 | 43.736264 | 187 | 0.629975 | false | 3.327882 | false | false | false |
Censio/filterpy | filterpy/common/tests/test_discretization.py | 1 | 2566 | # -*- coding: utf-8 -*-
"""Copyright 2015 Roger R Labbe Jr.
FilterPy library.
http://github.com/rlabbe/filterpy
Documentation at:
https://filterpy.readthedocs.org
Supporting book at:
https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python
This is licensed under an MIT license. See the readme.MD file
for more information.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from filterpy.common import linear_ode_discretation, Q_discrete_white_noise
from numpy import array
def near_eq(x,y):
return abs(x-y) < 1.e-17
def test_Q_discrete_white_noise():
Q = Q_discrete_white_noise (2)
assert Q[0,0] == .25
assert Q[1,0] == .5
assert Q[0,1] == .5
assert Q[1,1] == 1
assert Q.shape == (2,2)
def test_linear_ode():
F = array([[0,0,1,0,0,0],
[0,0,0,1,0,0],
[0,0,0,0,1,0],
[0,0,0,0,0,1],
[0,0,0,0,0,0],
[0,0,0,0,0,0]], dtype=float)
L = array ([[0,0],
[0,0],
[0,0],
[0,0],
[1,0],
[0,1]], dtype=float)
q = .2
Q = array([[q, 0],[0, q]])
dt = 0.5
A,Q = linear_ode_discretation(F, L, Q, dt)
val = [1, 0, dt, 0, 0.5*dt**2, 0]
for i in range(6):
assert val[i] == A[0,i]
for i in range(6):
assert val[i-1] == A[1,i] if i > 0 else A[1,i] == 0
for i in range(6):
assert val[i-2] == A[2,i] if i > 1 else A[2,i] == 0
for i in range(6):
assert val[i-3] == A[3,i] if i > 2 else A[3,i] == 0
for i in range(6):
assert val[i-4] == A[4,i] if i > 3 else A[4,i] == 0
for i in range(6):
assert val[i-5] == A[5,i] if i > 4 else A[5,i] == 0
assert near_eq(Q[0,0], (1./20)*(dt**5)*q)
assert near_eq(Q[0,1], 0)
assert near_eq(Q[0,2], (1/8)*(dt**4)*q)
assert near_eq(Q[0,3], 0)
assert near_eq(Q[0,4], (1./6)*(dt**3)*q)
assert near_eq(Q[0,5], 0)
if __name__ == "__main__":
test_linear_ode()
test_Q_discrete_white_noise()
F = array([[0,0,1,0,0,0],
[0,0,0,1,0,0],
[0,0,0,0,1,0],
[0,0,0,0,0,1],
[0,0,0,0,0,0],
[0,0,0,0,0,0]], dtype=float)
L = array ([[0,0],
[0,0],
[0,0],
[0,0],
[1,0],
[0,1]], dtype=float)
q = .2
Q = array([[q, 0],[0, q]])
dt = 1/30
A,Q = linear_ode_discretation(F, L, Q, dt)
print(Q) | mit | -1,838,436,546,280,924,000 | 21.716814 | 75 | 0.464147 | false | 2.560878 | false | false | false |
boada/planckClusters | MOSAICpipe/bpz-1.99.3/prior_full.py | 1 | 3446 | from __future__ import print_function
from __future__ import division
from past.utils import old_div
from useful import match_resol
import numpy
import sys
# Hacked to use numpy and avoid import * commands
# FM
Float = numpy.float
less = numpy.less
def function(z, m, nt):
"""HDFN prior for the main six types of Benitez 2000
Returns an array pi[z[:],:6]
The input magnitude is F814W AB
"""
if nt != 6:
print("Wrong number of template spectra!")
sys.exit()
global zt_at_a
global zt_at_1p5
global zt_at_2
nz = len(z)
momin_hdf = 20.
if m <= 20.:
xm = numpy.arange(12., 18.0)
ft = numpy.array((0.55, 0.21, 0.21, .01, .01, .01))
zm0 = numpy.array([0.021, 0.034, 0.056, 0.0845, 0.1155, 0.127]) * (
old_div(2., 3.))
if len(ft) != nt:
print("Wrong number of templates!")
sys.exit()
nz = len(z)
m = numpy.array([m]) # match_resol works with arrays
m = numpy.clip(m, xm[0], xm[-1])
zm = match_resol(xm, zm0, m)
try:
zt_2.shape
except NameError:
t2 = [2.] * nt
zt_2 = numpy.power.outer(z, t2)
try:
zt_1p5.shape
except NameError:
t1p5 = [1.5] * nt
zt_1p5 = numpy.power.outer(z, t1p5)
zm_3 = numpy.power.outer(zm, 3)
zm_1p5 = numpy.power.outer(zm, 1.5)
p_i = 3. / 2. / zm_3 * zt_2[:, :] * numpy.exp(-numpy.clip(
old_div(zt_1p5[:, :], zm_1p5), 0., 700.))
norm = numpy.add.reduce(p_i[:nz, :], 0)
#Get rid of very low probability levels
p_i[:nz, :] = numpy.where(
numpy.less(
old_div(p_i[:nz, :], norm[:]), old_div(1e-5, float(nz))), 0.,
old_div(p_i[:nz, :], norm[:]))
norm = numpy.add.reduce(p_i[:nz, :], 0)
return p_i[:nz, :] / norm[:] * ft[:]
else:
m = numpy.minimum(numpy.maximum(20., m), 32)
a = numpy.array((2.465, 1.806, 1.806, 0.906, 0.906, 0.906))
zo = numpy.array((0.431, 0.390, 0.390, 0.0626, 0.0626, 0.0626))
km = numpy.array((0.0913, 0.0636, 0.0636, 0.123, 0.123, 0.123))
fo_t = numpy.array((0.35, 0.25, 0.25))
k_t = numpy.array((0.450, 0.147, 0.147))
dm = m - momin_hdf
zmt = numpy.clip(zo + km * dm, 0.01, 15.)
zmt_at_a = zmt**(a)
#We define z**a as global to keep it
#between function calls. That way it is
# estimated only once
try:
zt_at_a.shape
except NameError:
zt_at_a = numpy.power.outer(z, a)
#Morphological fractions
f_t = numpy.zeros((len(a), ), Float)
f_t[:3] = fo_t * numpy.exp(-k_t * dm)
f_t[3:] = old_div((1. - numpy.add.reduce(f_t[:3])), 3.)
#Formula:
#zm=zo+km*(m_m_min)
#p(z|T,m)=(z**a)*numpy.exp(-(z/zm)**a)
p_i = zt_at_a[:nz, :6] * numpy.exp(-numpy.clip(
old_div(zt_at_a[:nz, :6], zmt_at_a[:6]), 0., 700.))
#This eliminates the very low level tails of the priors
norm = numpy.add.reduce(p_i[:nz, :6], 0)
p_i[:nz, :6] = numpy.where(
less(
old_div(p_i[:nz, :6], norm[:6]), old_div(1e-2, float(nz))), 0.,
old_div(p_i[:nz, :6], norm[:6]))
norm = numpy.add.reduce(p_i[:nz, :6], 0)
p_i[:nz, :6] = p_i[:nz, :6] / norm[:6] * f_t[:6]
return p_i
| mit | -3,085,104,049,551,145,000 | 31.819048 | 79 | 0.492455 | false | 2.732752 | false | false | false |
selboo/starl-mangle | webvirtmgr/dashboard/views.py | 1 | 5187 | from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.utils.datastructures import SortedDict
from instance.models import Host
from webvirtmgr.server import ConnServer
from dashboard.forms import HostAddTcpForm, HostAddSshForm
def sort_host(hosts):
"""
Sorts dictionary of hosts by key
"""
if hosts:
sorted_hosts = []
for host in sorted(hosts.iterkeys()):
sorted_hosts.append((host, hosts[host]))
return SortedDict(sorted_hosts)
def index(request):
"""
Index page.
"""
if not request.user.is_authenticated():
return HttpResponseRedirect('/login')
else:
return HttpResponseRedirect('/dashboard')
def dashboard(request):
"""
Dashboard page.
"""
if not request.user.is_authenticated():
return HttpResponseRedirect('/login')
def get_hosts_status(hosts):
"""
Function return all hosts all vds on host
"""
all_hosts = {}
for host in hosts:
try:
import socket
socket_host = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_host.settimeout(1)
if host.type == 'ssh':
socket_host.connect((host.hostname, host.port))
else:
socket_host.connect((host.hostname, 16509))
socket_host.close()
status = 1
except Exception as err:
status = err
all_hosts[host.id] = (host.name, host.hostname, status)
return all_hosts
hosts = Host.objects.filter()
hosts_info = get_hosts_status(hosts)
form = None
if request.method == 'POST':
if 'host_del' in request.POST:
del_host = Host.objects.get(id=request.POST.get('host_id', ''))
del_host.delete()
return HttpResponseRedirect(request.get_full_path())
if 'host_tcp_add' in request.POST:
form = HostAddTcpForm(request.POST)
if form.is_valid():
data = form.cleaned_data
new_host = Host(name=data['name'],
hostname=data['hostname'],
type='tcp',
login=data['login'],
password=data['password1']
)
new_host.save()
return HttpResponseRedirect(request.get_full_path())
if 'host_ssh_add' in request.POST:
form = HostAddSshForm(request.POST)
if form.is_valid():
data = form.cleaned_data
new_host = Host(name=data['name'],
hostname=data['hostname'],
type='ssh',
port=data['port'],
login=data['login']
)
new_host.save()
return HttpResponseRedirect(request.get_full_path())
hosts_info = sort_host(hosts_info)
return render_to_response('dashboard.html', {'hosts_info': hosts_info,
'form': form,
},
context_instance=RequestContext(request))
def infrastructure(request):
"""
Infrastructure page.
"""
if not request.user.is_authenticated():
return HttpResponseRedirect('/login')
hosts = Host.objects.filter().order_by('id')
hosts_vms = {}
host_info = None
host_mem = None
for host in hosts:
try:
import socket
socket_host = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_host.settimeout(1)
if host.type == 'ssh':
socket_host.connect((host.hostname, host.port))
else:
socket_host.connect((host.hostname, 16509))
socket_host.close()
status = 1
except:
status = 2
if status == 1:
conn = ConnServer(host)
host_info = conn.node_get_info()
host_mem = conn.memory_get_usage()
hosts_vms[host.id, host.name, status, host_info[2], host_mem[0], host_mem[2]] = conn.vds_on_cluster()
else:
hosts_vms[host.id, host.name, status, None, None, None] = None
for host in hosts_vms:
hosts_vms[host] = sort_host(hosts_vms[host])
hosts_vms = sort_host(hosts_vms)
return render_to_response('infrastructure.html', {'hosts_info': host_info,
'host_mem': host_mem,
'hosts_vms': hosts_vms,
'hosts': hosts
},
context_instance=RequestContext(request))
def page_setup(request):
return render_to_response('setup.html', {}, context_instance=RequestContext(request))
| apache-2.0 | 1,696,039,395,362,939,000 | 31.829114 | 113 | 0.508965 | false | 4.639535 | false | false | false |
anntzer/scikit-learn | sklearn/linear_model/_passive_aggressive.py | 2 | 17363 | # Authors: Rob Zinkov, Mathieu Blondel
# License: BSD 3 clause
from ..utils.validation import _deprecate_positional_args
from ._stochastic_gradient import BaseSGDClassifier
from ._stochastic_gradient import BaseSGDRegressor
from ._stochastic_gradient import DEFAULT_EPSILON
class PassiveAggressiveClassifier(BaseSGDClassifier):
"""Passive Aggressive Classifier
Read more in the :ref:`User Guide <passive_aggressive>`.
Parameters
----------
C : float, default=1.0
Maximum step size (regularization). Defaults to 1.0.
fit_intercept : bool, default=True
Whether the intercept should be estimated or not. If False, the
data is assumed to be already centered.
max_iter : int, default=1000
The maximum number of passes over the training data (aka epochs).
It only impacts the behavior in the ``fit`` method, and not the
:meth:`partial_fit` method.
.. versionadded:: 0.19
tol : float or None, default=1e-3
The stopping criterion. If it is not None, the iterations will stop
when (loss > previous_loss - tol).
.. versionadded:: 0.19
early_stopping : bool, default=False
Whether to use early stopping to terminate training when validation.
score is not improving. If set to True, it will automatically set aside
a stratified fraction of training data as validation and terminate
training when validation score is not improving by at least tol for
n_iter_no_change consecutive epochs.
.. versionadded:: 0.20
validation_fraction : float, default=0.1
The proportion of training data to set aside as validation set for
early stopping. Must be between 0 and 1.
Only used if early_stopping is True.
.. versionadded:: 0.20
n_iter_no_change : int, default=5
Number of iterations with no improvement to wait before early stopping.
.. versionadded:: 0.20
shuffle : bool, default=True
Whether or not the training data should be shuffled after each epoch.
verbose : integer, default=0
The verbosity level
loss : string, default="hinge"
The loss function to be used:
hinge: equivalent to PA-I in the reference paper.
squared_hinge: equivalent to PA-II in the reference paper.
n_jobs : int or None, default=None
The number of CPUs to use to do the OVA (One Versus All, for
multi-class problems) computation.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
random_state : int, RandomState instance, default=None
Used to shuffle the training data, when ``shuffle`` is set to
``True``. Pass an int for reproducible output across multiple
function calls.
See :term:`Glossary <random_state>`.
warm_start : bool, default=False
When set to True, reuse the solution of the previous call to fit as
initialization, otherwise, just erase the previous solution.
See :term:`the Glossary <warm_start>`.
Repeatedly calling fit or partial_fit when warm_start is True can
result in a different solution than when calling fit a single time
because of the way the data is shuffled.
class_weight : dict, {class_label: weight} or "balanced" or None, \
default=None
Preset for the class_weight fit parameter.
Weights associated with classes. If not given, all classes
are supposed to have weight one.
The "balanced" mode uses the values of y to automatically adjust
weights inversely proportional to class frequencies in the input data
as ``n_samples / (n_classes * np.bincount(y))``
.. versionadded:: 0.17
parameter *class_weight* to automatically weight samples.
average : bool or int, default=False
When set to True, computes the averaged SGD weights and stores the
result in the ``coef_`` attribute. If set to an int greater than 1,
averaging will begin once the total number of samples seen reaches
average. So average=10 will begin averaging after seeing 10 samples.
.. versionadded:: 0.19
parameter *average* to use weights averaging in SGD
Attributes
----------
coef_ : array, shape = [1, n_features] if n_classes == 2 else [n_classes,\
n_features]
Weights assigned to the features.
intercept_ : array, shape = [1] if n_classes == 2 else [n_classes]
Constants in decision function.
n_iter_ : int
The actual number of iterations to reach the stopping criterion.
For multiclass fits, it is the maximum over every binary fit.
classes_ : array of shape (n_classes,)
The unique classes labels.
t_ : int
Number of weight updates performed during training.
Same as ``(n_iter_ * n_samples)``.
loss_function_ : callable
Loss function used by the algorithm.
Examples
--------
>>> from sklearn.linear_model import PassiveAggressiveClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_features=4, random_state=0)
>>> clf = PassiveAggressiveClassifier(max_iter=1000, random_state=0,
... tol=1e-3)
>>> clf.fit(X, y)
PassiveAggressiveClassifier(random_state=0)
>>> print(clf.coef_)
[[0.26642044 0.45070924 0.67251877 0.64185414]]
>>> print(clf.intercept_)
[1.84127814]
>>> print(clf.predict([[0, 0, 0, 0]]))
[1]
See Also
--------
SGDClassifier
Perceptron
References
----------
Online Passive-Aggressive Algorithms
<http://jmlr.csail.mit.edu/papers/volume7/crammer06a/crammer06a.pdf>
K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006)
"""
@_deprecate_positional_args
def __init__(self, *, C=1.0, fit_intercept=True, max_iter=1000, tol=1e-3,
early_stopping=False, validation_fraction=0.1,
n_iter_no_change=5, shuffle=True, verbose=0, loss="hinge",
n_jobs=None, random_state=None, warm_start=False,
class_weight=None, average=False):
super().__init__(
penalty=None,
fit_intercept=fit_intercept,
max_iter=max_iter,
tol=tol,
early_stopping=early_stopping,
validation_fraction=validation_fraction,
n_iter_no_change=n_iter_no_change,
shuffle=shuffle,
verbose=verbose,
random_state=random_state,
eta0=1.0,
warm_start=warm_start,
class_weight=class_weight,
average=average,
n_jobs=n_jobs)
self.C = C
self.loss = loss
def partial_fit(self, X, y, classes=None):
"""Fit linear model with Passive Aggressive algorithm.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Subset of the training data
y : numpy array of shape [n_samples]
Subset of the target values
classes : array, shape = [n_classes]
Classes across all calls to partial_fit.
Can be obtained by via `np.unique(y_all)`, where y_all is the
target vector of the entire dataset.
This argument is required for the first call to partial_fit
and can be omitted in the subsequent calls.
Note that y doesn't need to contain all labels in `classes`.
Returns
-------
self : returns an instance of self.
"""
self._validate_params(for_partial_fit=True)
if self.class_weight == 'balanced':
raise ValueError("class_weight 'balanced' is not supported for "
"partial_fit. For 'balanced' weights, use "
"`sklearn.utils.compute_class_weight` with "
"`class_weight='balanced'`. In place of y you "
"can use a large enough subset of the full "
"training set target to properly estimate the "
"class frequency distributions. Pass the "
"resulting weights as the class_weight "
"parameter.")
lr = "pa1" if self.loss == "hinge" else "pa2"
return self._partial_fit(X, y, alpha=1.0, C=self.C,
loss="hinge", learning_rate=lr, max_iter=1,
classes=classes, sample_weight=None,
coef_init=None, intercept_init=None)
def fit(self, X, y, coef_init=None, intercept_init=None):
"""Fit linear model with Passive Aggressive algorithm.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data
y : numpy array of shape [n_samples]
Target values
coef_init : array, shape = [n_classes,n_features]
The initial coefficients to warm-start the optimization.
intercept_init : array, shape = [n_classes]
The initial intercept to warm-start the optimization.
Returns
-------
self : returns an instance of self.
"""
self._validate_params()
lr = "pa1" if self.loss == "hinge" else "pa2"
return self._fit(X, y, alpha=1.0, C=self.C,
loss="hinge", learning_rate=lr,
coef_init=coef_init, intercept_init=intercept_init)
class PassiveAggressiveRegressor(BaseSGDRegressor):
"""Passive Aggressive Regressor
Read more in the :ref:`User Guide <passive_aggressive>`.
Parameters
----------
C : float, default=1.0
Maximum step size (regularization). Defaults to 1.0.
fit_intercept : bool, default=True
Whether the intercept should be estimated or not. If False, the
data is assumed to be already centered. Defaults to True.
max_iter : int, default=1000
The maximum number of passes over the training data (aka epochs).
It only impacts the behavior in the ``fit`` method, and not the
:meth:`partial_fit` method.
.. versionadded:: 0.19
tol : float or None, default=1e-3
The stopping criterion. If it is not None, the iterations will stop
when (loss > previous_loss - tol).
.. versionadded:: 0.19
early_stopping : bool, default=False
Whether to use early stopping to terminate training when validation.
score is not improving. If set to True, it will automatically set aside
a fraction of training data as validation and terminate
training when validation score is not improving by at least tol for
n_iter_no_change consecutive epochs.
.. versionadded:: 0.20
validation_fraction : float, default=0.1
The proportion of training data to set aside as validation set for
early stopping. Must be between 0 and 1.
Only used if early_stopping is True.
.. versionadded:: 0.20
n_iter_no_change : int, default=5
Number of iterations with no improvement to wait before early stopping.
.. versionadded:: 0.20
shuffle : bool, default=True
Whether or not the training data should be shuffled after each epoch.
verbose : integer, default=0
The verbosity level
loss : string, default="epsilon_insensitive"
The loss function to be used:
epsilon_insensitive: equivalent to PA-I in the reference paper.
squared_epsilon_insensitive: equivalent to PA-II in the reference
paper.
epsilon : float, default=0.1
If the difference between the current prediction and the correct label
is below this threshold, the model is not updated.
random_state : int, RandomState instance, default=None
Used to shuffle the training data, when ``shuffle`` is set to
``True``. Pass an int for reproducible output across multiple
function calls.
See :term:`Glossary <random_state>`.
warm_start : bool, default=False
When set to True, reuse the solution of the previous call to fit as
initialization, otherwise, just erase the previous solution.
See :term:`the Glossary <warm_start>`.
Repeatedly calling fit or partial_fit when warm_start is True can
result in a different solution than when calling fit a single time
because of the way the data is shuffled.
average : bool or int, default=False
When set to True, computes the averaged SGD weights and stores the
result in the ``coef_`` attribute. If set to an int greater than 1,
averaging will begin once the total number of samples seen reaches
average. So average=10 will begin averaging after seeing 10 samples.
.. versionadded:: 0.19
parameter *average* to use weights averaging in SGD
Attributes
----------
coef_ : array, shape = [1, n_features] if n_classes == 2 else [n_classes,\
n_features]
Weights assigned to the features.
intercept_ : array, shape = [1] if n_classes == 2 else [n_classes]
Constants in decision function.
n_iter_ : int
The actual number of iterations to reach the stopping criterion.
t_ : int
Number of weight updates performed during training.
Same as ``(n_iter_ * n_samples)``.
Examples
--------
>>> from sklearn.linear_model import PassiveAggressiveRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_features=4, random_state=0)
>>> regr = PassiveAggressiveRegressor(max_iter=100, random_state=0,
... tol=1e-3)
>>> regr.fit(X, y)
PassiveAggressiveRegressor(max_iter=100, random_state=0)
>>> print(regr.coef_)
[20.48736655 34.18818427 67.59122734 87.94731329]
>>> print(regr.intercept_)
[-0.02306214]
>>> print(regr.predict([[0, 0, 0, 0]]))
[-0.02306214]
See Also
--------
SGDRegressor
References
----------
Online Passive-Aggressive Algorithms
<http://jmlr.csail.mit.edu/papers/volume7/crammer06a/crammer06a.pdf>
K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006)
"""
@_deprecate_positional_args
def __init__(self, *, C=1.0, fit_intercept=True, max_iter=1000, tol=1e-3,
early_stopping=False, validation_fraction=0.1,
n_iter_no_change=5, shuffle=True, verbose=0,
loss="epsilon_insensitive", epsilon=DEFAULT_EPSILON,
random_state=None, warm_start=False,
average=False):
super().__init__(
penalty=None,
l1_ratio=0,
epsilon=epsilon,
eta0=1.0,
fit_intercept=fit_intercept,
max_iter=max_iter,
tol=tol,
early_stopping=early_stopping,
validation_fraction=validation_fraction,
n_iter_no_change=n_iter_no_change,
shuffle=shuffle,
verbose=verbose,
random_state=random_state,
warm_start=warm_start,
average=average)
self.C = C
self.loss = loss
def partial_fit(self, X, y):
"""Fit linear model with Passive Aggressive algorithm.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Subset of training data
y : numpy array of shape [n_samples]
Subset of target values
Returns
-------
self : returns an instance of self.
"""
self._validate_params(for_partial_fit=True)
lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2"
return self._partial_fit(X, y, alpha=1.0, C=self.C,
loss="epsilon_insensitive",
learning_rate=lr, max_iter=1,
sample_weight=None,
coef_init=None, intercept_init=None)
def fit(self, X, y, coef_init=None, intercept_init=None):
"""Fit linear model with Passive Aggressive algorithm.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data
y : numpy array of shape [n_samples]
Target values
coef_init : array, shape = [n_features]
The initial coefficients to warm-start the optimization.
intercept_init : array, shape = [1]
The initial intercept to warm-start the optimization.
Returns
-------
self : returns an instance of self.
"""
self._validate_params()
lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2"
return self._fit(X, y, alpha=1.0, C=self.C,
loss="epsilon_insensitive",
learning_rate=lr,
coef_init=coef_init,
intercept_init=intercept_init)
| bsd-3-clause | -4,979,293,226,387,037,000 | 35.942553 | 79 | 0.607153 | false | 4.177815 | false | false | false |
vit-/telegram-uz-bot | uz/tests/interface/telegram/test_bot.py | 1 | 5489 | import time
from datetime import datetime
import mock
import pytest
from uz.tests import Awaitable
from uz.interface.telegram import bot
from uz.scanner import UknkownScanID
CHAT_ID = 'chat_id'
def tg_message(text):
return {
'chat': {
'id': CHAT_ID,
'type': 'private',
},
'from': {'first_name': 'n/a', 'id': 'user_id'},
'message_id': int(time.time()),
'text': text
}
def get_reply(send_message_mock):
args, kwargs = send_message_mock.call_args_list[0]
return args[1]
@pytest.mark.asyncio
async def test_list_trains(source_station, destination_station, train):
bot.send_message = send_message = mock.MagicMock(return_value=Awaitable())
date = datetime(2016, 7, 21)
command = '/trains {} {} {}'.format(
date.strftime('%Y-%m-%d'), source_station.title, destination_station.title)
with mock.patch('uz.interface.serializer.Deserializer.load',
return_value=Awaitable((date, source_station, destination_station))) as load, \
mock.patch('uz.client.client.UZClient.list_trains',
return_value=Awaitable([train])) as list_trains:
await bot._process_message(tg_message(command))
load.assert_called_once_with({
'date': date.strftime('%Y-%m-%d'),
'source': source_station.title,
'destination': destination_station.title})
list_trains.assert_called_once_with(date, source_station, destination_station)
msg = get_reply(send_message)
title = 'Trains from %s to %s on %s:' % (
source_station, destination_station, date.date())
assert msg.startswith(title)
assert train.info() in msg
@pytest.mark.asyncio
@pytest.mark.parametrize('is_ok', [True, False])
async def test_status(is_ok):
scan_id = 'id1234'
scanner = mock.MagicMock()
if is_ok:
scanner.status.return_value = (attempts, error) = (10, 'i am error')
else:
scanner.status.side_effect = UknkownScanID()
bot.send_message = send_message = mock.MagicMock(return_value=Awaitable())
bot.set_scanner(scanner)
await bot._process_message(tg_message('/status_{}'.format(scan_id)))
scanner.status.assert_called_once_with(scan_id)
if is_ok:
send_message.assert_called_once_with(
CHAT_ID, 'No attempts: {}\nLast error message: {}'.format(attempts, error))
else:
send_message.assert_called_once_with(
CHAT_ID, 'Unknown scan id: {}'.format(scan_id))
@pytest.mark.asyncio
@pytest.mark.parametrize('is_ok', [True, False])
async def test_abort_scan(is_ok):
scan_id = 'id4321'
scanner = mock.MagicMock()
if is_ok:
scanner.abort.return_value = True
else:
scanner.abort.side_effect = UknkownScanID()
bot.send_message = send_message = mock.MagicMock(return_value=Awaitable())
bot.set_scanner(scanner)
await bot._process_message(tg_message('/abort_{}'.format(scan_id)))
scanner.abort.assert_called_once_with(scan_id)
if is_ok:
send_message.assert_called_once_with(
CHAT_ID, 'OK')
else:
send_message.assert_called_once_with(
CHAT_ID, 'Unknown scan id: {}'.format(scan_id))
@pytest.mark.asyncio
@pytest.mark.parametrize('ct_letter', [None, 'C2'])
async def test_scan(source_station, destination_station, ct_letter):
scan_id = 'id1234'
date = datetime(2016, 10, 7)
train_num = '744K'
firstname = 'username'
lastname = 'surname'
parts = [
'/scan',
firstname,
lastname,
date.strftime('%Y-%m-%d'),
source_station,
destination_station,
train_num]
if ct_letter:
parts.append(ct_letter)
command = ' '.join(str(i) for i in parts)
scanner = mock.MagicMock()
scanner.add_item.return_value = scan_id
bot.send_message = send_message = mock.MagicMock(return_value=Awaitable())
bot.set_scanner(scanner)
with mock.patch('uz.interface.serializer.Deserializer.load',
return_value=Awaitable((date, source_station, destination_station))) as load:
await bot._process_message(tg_message(command))
load.assert_called_once_with({
'firstname': firstname,
'lastname': lastname,
'date': date.strftime('%Y-%m-%d'),
'source': source_station.title,
'destination': destination_station.title,
'train_num': train_num,
'ct_letter': ct_letter})
scanner.add_item.assert_called_once_with(
mock.ANY, firstname, lastname, date, source_station, destination_station,
train_num, ct_letter)
expected = ('Scanning tickets for train {train} from {src} to {dst} on {date}.\n'
'To monitor scan status: /status_{sid}\n'
'To abort scan: /abort_{sid}').format(
train=train_num,
src=source_station,
dst=destination_station,
date=date.date(),
sid=scan_id)
send_message.assert_called_once_with(CHAT_ID, expected)
@pytest.mark.asyncio
async def test_hello():
bot.send_message = send_message = mock.MagicMock(return_value=Awaitable())
await bot._process_message(tg_message('hi'))
send_message.assert_called_once_with(CHAT_ID, mock.ANY)
@pytest.mark.asyncio
async def test_help_msg():
bot.send_message = send_message = mock.MagicMock(return_value=Awaitable())
await bot._process_message(tg_message('/help'))
send_message.assert_called_once_with(CHAT_ID, mock.ANY)
| mit | 5,860,053,250,814,065,000 | 33.522013 | 99 | 0.635817 | false | 3.4072 | true | false | false |
CityofPittsburgh/pittsburgh-purchasing-suite | migrations/versions/31d29fbffe44_add_passwords_for_users.py | 1 | 1988 | """add passwords for users
Revision ID: 31d29fbffe44
Revises: 48c578b852fa
Create Date: 2016-01-20 23:33:36.893832
"""
# revision identifiers, used by Alembic.
revision = '31d29fbffe44'
down_revision = '48c578b852fa'
import random
from flask_security.utils import encrypt_password
from alembic import op
import sqlalchemy as sa
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def rand_alphabet():
return encrypt_password(''.join(random.choice(ALPHABET) for i in range(16)))
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column(u'roles', sa.Column('description', sa.String(length=255), nullable=True))
op.add_column(u'users', sa.Column('confirmed_at', sa.DateTime(), nullable=True))
op.add_column(u'users', sa.Column('current_login_at', sa.DateTime(), nullable=True))
op.add_column(u'users', sa.Column('current_login_ip', sa.String(length=255), nullable=True))
op.add_column(u'users', sa.Column('last_login_at', sa.DateTime(), nullable=True))
op.add_column(u'users', sa.Column('last_login_ip', sa.String(length=255), nullable=True))
op.add_column(u'users', sa.Column('login_count', sa.Integer(), nullable=True))
op.add_column(u'users', sa.Column(
'password', sa.String(length=255), nullable=False,
default=rand_alphabet(), server_default=rand_alphabet()
))
### end Alembic commands ###
op.execute(sa.sql.text('''
UPDATE users SET confirmed_at = now()
'''))
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column(u'users', 'password')
op.drop_column(u'users', 'login_count')
op.drop_column(u'users', 'last_login_ip')
op.drop_column(u'users', 'last_login_at')
op.drop_column(u'users', 'current_login_ip')
op.drop_column(u'users', 'current_login_at')
op.drop_column(u'users', 'confirmed_at')
op.drop_column(u'roles', 'description')
### end Alembic commands ###
| bsd-3-clause | -1,728,439,714,103,357,000 | 36.509434 | 96 | 0.686117 | false | 3.23252 | false | false | false |
miracle2k/stgit | stgit/commands/delete.py | 1 | 3073 |
__copyright__ = """
Copyright (C) 2005, Catalin Marinas <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
from stgit.argparse import opt
from stgit.commands import common
from stgit.lib import transaction
from stgit import argparse
help = 'Delete patches'
kind = 'patch'
usage = ['[options] <patch1> [<patch2>] [<patch3>..<patch4>]']
description = """
Delete the patches passed as arguments."""
args = [argparse.patch_range(argparse.applied_patches,
argparse.unapplied_patches)]
options = [
opt('--spill', action = 'store_true',
short = 'Spill patch contents to worktree and index', long = """
Delete the patches, but do not touch the index and worktree.
This only works with applied patches at the top of the stack.
The effect is to "spill" the patch contents into the index and
worktree. This can be useful e.g. if you want to split a patch
into several smaller pieces."""),
opt('-b', '--branch', args = [argparse.stg_branches],
short = 'Use BRANCH instead of the default branch')]
directory = common.DirectoryHasRepositoryLib()
def func(parser, options, args):
"""Delete one or more patches."""
stack = directory.repository.get_stack(options.branch)
if options.branch:
iw = None # can't use index/workdir to manipulate another branch
else:
iw = stack.repository.default_iw
if args:
patches = set(common.parse_patches(args, list(stack.patchorder.all),
len(stack.patchorder.applied)))
else:
parser.error('No patches specified')
if options.spill:
if set(stack.patchorder.applied[-len(patches):]) != patches:
parser.error('Can only spill topmost applied patches')
iw = None # don't touch index+worktree
def allow_conflicts(trans):
# Allow conflicts if the topmost patch stays the same.
if stack.patchorder.applied:
return (trans.applied
and trans.applied[-1] == stack.patchorder.applied[-1])
else:
return not trans.applied
trans = transaction.StackTransaction(stack, 'delete',
allow_conflicts = allow_conflicts)
try:
to_push = trans.delete_patches(lambda pn: pn in patches)
for pn in to_push:
trans.push_patch(pn, iw)
except transaction.TransactionHalted:
pass
return trans.run(iw)
| gpl-2.0 | -8,761,710,056,651,811,000 | 38.397436 | 76 | 0.664497 | false | 4.147099 | false | false | false |
FedoraScientific/salome-smesh | src/Tools/blocFissure/CasTests/fissure_Coude_4.py | 1 | 3081 | # -*- coding: utf-8 -*-
from fissure_Coude import fissure_Coude
class fissure_Coude_4(fissure_Coude):
"""
probleme de fissure du Coude : ASCOU09A
adaptation maillage
"""
# ---------------------------------------------------------------------------
def setParamGeometrieSaine(self):
"""
Paramètres géométriques du tuyau coudé sain:
angleCoude
r_cintr
l_tube_p1
l_tube_p2
epais
de
"""
self.geomParams = dict(angleCoude = 40,
r_cintr = 654,
l_tube_p1 = 1700,
l_tube_p2 = 1700,
epais = 62.5,
de = 912.4)
# ---------------------------------------------------------------------------
def setParamMaillageSain(self):
self.meshParams = dict(n_long_p1 = 16,
n_ep = 5,
n_long_coude = 30,
n_circ_g = 50,
n_circ_d = 20,
n_long_p2 = 12)
# ---------------------------------------------------------------------------
def setParamShapeFissure(self):
"""
paramètres de la fissure
profondeur : 0 < profondeur <= épaisseur
azimut : entre 0 et 360°
alpha : 0 < alpha < angleCoude
longueur : <=2*profondeur ==> ellipse, >2*profondeur = fissure longue
orientation : 0° : longitudinale, 90° : circonférentielle, autre : uniquement fissures elliptiques
externe : True : fissure face externe, False : fissure face interne
"""
print "setParamShapeFissure", self.nomCas
self.shapeFissureParams = dict(nomRep = '.',
nomFicSain = self.nomCas,
nomFicFissure = 'fissure_' + self.nomCas,
profondeur = 10,
azimut = 90,
alpha = 20,
longueur = 240,
orientation = 90,
lgInfluence = 30,
elliptique = False,
convexe = True,
externe = True)
# ---------------------------------------------------------------------------
def setReferencesMaillageFissure(self):
self.referencesMaillageFissure = dict(Entity_Quad_Pyramid = 948,
Entity_Quad_Triangle = 1562,
Entity_Quad_Edge = 1192,
Entity_Quad_Penta = 732,
Entity_Quad_Hexa = 22208,
Entity_Node = 133418,
Entity_Quad_Tetra = 18759,
Entity_Quad_Quadrangle = 11852)
| lgpl-2.1 | -4,575,732,381,039,616,000 | 41.068493 | 102 | 0.370563 | false | 4.230028 | false | false | false |
davidwilson-85/easymap | graphic_output/Pillow-4.2.1/Tests/test_file_wmf.py | 1 | 1215 | from helper import unittest, PillowTestCase, hopper
from PIL import Image
class TestFileWmf(PillowTestCase):
def test_load_raw(self):
# Test basic EMF open and rendering
im = Image.open('Tests/images/drawing.emf')
if hasattr(Image.core, "drawwmf"):
# Currently, support for WMF/EMF is Windows-only
im.load()
# Compare to reference rendering
imref = Image.open('Tests/images/drawing_emf_ref.png')
imref.load()
self.assert_image_similar(im, imref, 0)
# Test basic WMF open and rendering
im = Image.open('Tests/images/drawing.wmf')
if hasattr(Image.core, "drawwmf"):
# Currently, support for WMF/EMF is Windows-only
im.load()
# Compare to reference rendering
imref = Image.open('Tests/images/drawing_wmf_ref.png')
imref.load()
self.assert_image_similar(im, imref, 2.0)
def test_save(self):
im = hopper()
for ext in [".wmf", ".emf"]:
tmpfile = self.tempfile("temp"+ext)
self.assertRaises(IOError, lambda: im.save(tmpfile))
if __name__ == '__main__':
unittest.main()
| gpl-3.0 | -6,634,027,561,541,816,000 | 30.973684 | 66 | 0.584362 | false | 3.75 | true | false | false |
abrt/faf | src/pyfaf/storage/migrations/versions/a2b6d12819f9_drop_yum_type.py | 1 | 2158 | # Copyright (C) 2019 ABRT Team
# Copyright (C) 2019 Red Hat, Inc.
#
# This file is part of faf.
#
# faf is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# faf is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with faf. If not, see <http://www.gnu.org/licenses/>.
"""
drop_yum_type
Revision ID: a2b6d12819f9
Revises: e5d5cefb8ca4
Create Date: 2019-02-08 11:41:56.967881
"""
from alembic.op import execute, get_bind
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a2b6d12819f9'
down_revision = 'e5d5cefb8ca4'
new_values = ['dnf', 'koji', 'rpmmetadata']
old_values = new_values + ['yum']
old_type = sa.Enum(*old_values, name='repo_type')
new_type = sa.Enum(*new_values, name='repo_type')
tmp_type = sa.Enum(*new_values, name='_repo_type')
def upgrade() -> None:
bind = get_bind()
execute('UPDATE repo SET type=\'dnf\' WHERE type=\'yum\'')
tmp_type.create(bind, checkfirst=False)
execute('ALTER TABLE repo ALTER COLUMN type TYPE _repo_type USING '
'type::text::_repo_type')
old_type.drop(bind, checkfirst=False)
new_type.create(bind, checkfirst=False)
execute('ALTER TABLE repo ALTER COLUMN type TYPE repo_type USING '
'type::text::repo_type')
tmp_type.drop(bind, checkfirst=False)
def downgrade() -> None:
bind = get_bind()
tmp_type.create(bind, checkfirst=False)
execute('ALTER TABLE repo ALTER COLUMN type TYPE _repo_type USING '
'type::text::_repo_type')
new_type.drop(bind, checkfirst=False)
old_type.create(bind, checkfirst=False)
execute('ALTER TABLE repo ALTER COLUMN type TYPE repo_type USING '
'type::text::repo_type')
tmp_type.drop(bind, checkfirst=False)
| gpl-3.0 | 894,444,310,800,265,600 | 30.735294 | 71 | 0.696015 | false | 3.284627 | false | false | false |
lucius-feng/tg2 | tests/test_middlewares.py | 2 | 3091 | from webtest import TestApp
from tg.support.middlewares import StatusCodeRedirect
from tg.support.middlewares import DBSessionRemoverMiddleware
from tg.support.middlewares import MingSessionRemoverMiddleware
def FakeApp(environ, start_response):
if environ['PATH_INFO'].startswith('/error'):
start_response('403 Forbidden', [])
else:
start_response('200 Success', [])
if environ['PATH_INFO'] == '/error/document':
yield b'ERROR!!!'
else:
yield b'HI'
yield b'MORE'
class TestStatusCodeRedirectMiddleware(object):
def setup(self):
self.app = TestApp(StatusCodeRedirect(FakeApp, [403]))
def test_error_redirection(self):
r = self.app.get('/error_test', status=403)
assert 'ERROR!!!' in r, r
def test_success_passthrough(self):
r = self.app.get('/success_test')
assert 'HI' in r, r
class FakeDBSession(object):
removed = False
def remove(self):
self.removed = True
def close_all(self):
self.remove()
class FakeAppWithClose(object):
closed = False
step = 0
def __call__(self, environ, start_response):
start_response('200 Success', [])
if environ['PATH_INFO'] == '/crash':
raise Exception('crashed')
return self
def __iter__(self):
return self
def next(self):
self.step += 1
if self.step > 3:
raise StopIteration()
return str(self.step)
def close(self):
self.closed = True
def __repr__(self):
return '%s - %s' % (self.step, self.closed)
class TestDBSessionRemoverMiddleware(object):
def setup(self):
self.app_with_close = FakeAppWithClose()
self.session = FakeDBSession()
self.app = TestApp(DBSessionRemoverMiddleware(self.session, self.app_with_close))
def test_close_is_called(self):
r = self.app.get('/nonerror')
assert self.app_with_close.closed == True, self.app_with_close
def test_session_is_removed(self):
r = self.app.get('/nonerror')
assert self.session.removed == True, self.app_with_close
def test_session_is_removed_on_crash(self):
try:
r = self.app.get('/crash')
except:
pass
assert self.session.removed == True, self.app_with_close
class TestMingSessionRemoverMiddlewaree(object):
def setup(self):
self.app_with_close = FakeAppWithClose()
self.session = FakeDBSession()
self.app = TestApp(MingSessionRemoverMiddleware(self.session, self.app_with_close))
def test_close_is_called(self):
r = self.app.get('/nonerror')
assert self.app_with_close.closed == True, self.app_with_close
def test_session_is_removed(self):
r = self.app.get('/nonerror')
assert self.session.removed == True, self.app_with_close
def test_session_is_removed_on_crash(self):
try:
r = self.app.get('/crash')
except:
pass
assert self.session.removed == True, self.app_with_close
| mit | -5,575,966,756,473,490,000 | 25.646552 | 91 | 0.619864 | false | 3.697368 | true | false | false |
cloud-fan/spark | python/pyspark/pandas/data_type_ops/base.py | 1 | 12265 | #
# 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.
#
import numbers
from abc import ABCMeta
from itertools import chain
from typing import Any, Optional, TYPE_CHECKING, Union
import numpy as np
import pandas as pd
from pandas.api.types import CategoricalDtype
from pyspark.sql import functions as F
from pyspark.sql.types import (
ArrayType,
BinaryType,
BooleanType,
DataType,
DateType,
FractionalType,
IntegralType,
MapType,
NullType,
NumericType,
StringType,
StructType,
TimestampType,
UserDefinedType,
)
from pyspark.pandas.typedef import Dtype, extension_dtypes
from pyspark.pandas.typedef.typehints import extension_object_dtypes_available
if extension_object_dtypes_available:
from pandas import BooleanDtype
if TYPE_CHECKING:
from pyspark.pandas.indexes import Index # noqa: F401 (SPARK-34943)
from pyspark.pandas.series import Series # noqa: F401 (SPARK-34943)
def is_valid_operand_for_numeric_arithmetic(operand: Any, *, allow_bool: bool = True) -> bool:
"""Check whether the `operand` is valid for arithmetic operations against numerics."""
from pyspark.pandas.base import IndexOpsMixin
if isinstance(operand, numbers.Number):
return not isinstance(operand, bool) or allow_bool
elif isinstance(operand, IndexOpsMixin):
if isinstance(operand.dtype, CategoricalDtype):
return False
else:
return isinstance(operand.spark.data_type, NumericType) or (
allow_bool and isinstance(operand.spark.data_type, BooleanType)
)
else:
return False
def transform_boolean_operand_to_numeric(
operand: Any, spark_type: Optional[DataType] = None
) -> Any:
"""Transform boolean operand to numeric.
If the `operand` is:
- a boolean IndexOpsMixin, transform the `operand` to the `spark_type`.
- a boolean literal, transform to the int value.
Otherwise, return the operand as it is.
"""
from pyspark.pandas.base import IndexOpsMixin
if isinstance(operand, IndexOpsMixin) and isinstance(operand.spark.data_type, BooleanType):
assert spark_type, "spark_type must be provided if the operand is a boolean IndexOpsMixin"
return operand.spark.transform(lambda scol: scol.cast(spark_type))
elif isinstance(operand, bool):
return int(operand)
else:
return operand
def _as_categorical_type(
index_ops: Union["Series", "Index"], dtype: CategoricalDtype, spark_type: DataType
) -> Union["Index", "Series"]:
"""Cast `index_ops` to categorical dtype, given `dtype` and `spark_type`."""
assert isinstance(dtype, CategoricalDtype)
if dtype.categories is None:
codes, uniques = index_ops.factorize()
return codes._with_new_scol(
codes.spark.column,
field=codes._internal.data_fields[0].copy(dtype=CategoricalDtype(categories=uniques)),
)
else:
categories = dtype.categories
if len(categories) == 0:
scol = F.lit(-1)
else:
kvs = chain(
*[(F.lit(category), F.lit(code)) for code, category in enumerate(categories)]
)
map_scol = F.create_map(*kvs)
scol = F.coalesce(map_scol.getItem(index_ops.spark.column), F.lit(-1))
return index_ops._with_new_scol(
scol.cast(spark_type).alias(index_ops._internal.data_fields[0].name),
field=index_ops._internal.data_fields[0].copy(
dtype=dtype, spark_type=spark_type, nullable=False
),
)
def _as_bool_type(
index_ops: Union["Series", "Index"], dtype: Union[str, type, Dtype]
) -> Union["Index", "Series"]:
"""Cast `index_ops` to BooleanType Spark type, given `dtype`."""
from pyspark.pandas.internal import InternalField
if isinstance(dtype, extension_dtypes):
scol = index_ops.spark.column.cast(BooleanType())
else:
scol = F.when(index_ops.spark.column.isNull(), F.lit(False)).otherwise(
index_ops.spark.column.cast(BooleanType())
)
return index_ops._with_new_scol(
scol.alias(index_ops._internal.data_spark_column_names[0]),
field=InternalField(dtype=dtype),
)
def _as_string_type(
index_ops: Union["Series", "Index"],
dtype: Union[str, type, Dtype],
*,
null_str: str = str(None)
) -> Union["Index", "Series"]:
"""Cast `index_ops` to StringType Spark type, given `dtype` and `null_str`,
representing null Spark column.
"""
from pyspark.pandas.internal import InternalField
if isinstance(dtype, extension_dtypes):
scol = index_ops.spark.column.cast(StringType())
else:
casted = index_ops.spark.column.cast(StringType())
scol = F.when(index_ops.spark.column.isNull(), null_str).otherwise(casted)
return index_ops._with_new_scol(
scol.alias(index_ops._internal.data_spark_column_names[0]),
field=InternalField(dtype=dtype),
)
def _as_other_type(
index_ops: Union["Series", "Index"], dtype: Union[str, type, Dtype], spark_type: DataType
) -> Union["Index", "Series"]:
"""Cast `index_ops` to a `dtype` (`spark_type`) that needs no pre-processing.
Destination types that need pre-processing: CategoricalDtype, BooleanType, and StringType.
"""
from pyspark.pandas.internal import InternalField
need_pre_process = (
isinstance(dtype, CategoricalDtype)
or isinstance(spark_type, BooleanType)
or isinstance(spark_type, StringType)
)
assert not need_pre_process, "Pre-processing is needed before the type casting."
scol = index_ops.spark.column.cast(spark_type)
return index_ops._with_new_scol(
scol.alias(index_ops._internal.data_spark_column_names[0]),
field=InternalField(dtype=dtype),
)
class DataTypeOps(object, metaclass=ABCMeta):
"""The base class for binary operations of pandas-on-Spark objects (of different data types)."""
def __new__(cls, dtype: Dtype, spark_type: DataType):
from pyspark.pandas.data_type_ops.binary_ops import BinaryOps
from pyspark.pandas.data_type_ops.boolean_ops import BooleanOps, BooleanExtensionOps
from pyspark.pandas.data_type_ops.categorical_ops import CategoricalOps
from pyspark.pandas.data_type_ops.complex_ops import ArrayOps, MapOps, StructOps
from pyspark.pandas.data_type_ops.date_ops import DateOps
from pyspark.pandas.data_type_ops.datetime_ops import DatetimeOps
from pyspark.pandas.data_type_ops.null_ops import NullOps
from pyspark.pandas.data_type_ops.num_ops import IntegralOps, FractionalOps
from pyspark.pandas.data_type_ops.string_ops import StringOps
from pyspark.pandas.data_type_ops.udt_ops import UDTOps
if isinstance(dtype, CategoricalDtype):
return object.__new__(CategoricalOps)
elif isinstance(spark_type, FractionalType):
return object.__new__(FractionalOps)
elif isinstance(spark_type, IntegralType):
return object.__new__(IntegralOps)
elif isinstance(spark_type, StringType):
return object.__new__(StringOps)
elif isinstance(spark_type, BooleanType):
if extension_object_dtypes_available and isinstance(dtype, BooleanDtype):
return object.__new__(BooleanExtensionOps)
else:
return object.__new__(BooleanOps)
elif isinstance(spark_type, TimestampType):
return object.__new__(DatetimeOps)
elif isinstance(spark_type, DateType):
return object.__new__(DateOps)
elif isinstance(spark_type, BinaryType):
return object.__new__(BinaryOps)
elif isinstance(spark_type, ArrayType):
return object.__new__(ArrayOps)
elif isinstance(spark_type, MapType):
return object.__new__(MapOps)
elif isinstance(spark_type, StructType):
return object.__new__(StructOps)
elif isinstance(spark_type, NullType):
return object.__new__(NullOps)
elif isinstance(spark_type, UserDefinedType):
return object.__new__(UDTOps)
else:
raise TypeError("Type %s was not understood." % dtype)
def __init__(self, dtype: Dtype, spark_type: DataType):
self.dtype = dtype
self.spark_type = spark_type
@property
def pretty_name(self) -> str:
raise NotImplementedError()
def add(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Addition can not be applied to %s." % self.pretty_name)
def sub(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Subtraction can not be applied to %s." % self.pretty_name)
def mul(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Multiplication can not be applied to %s." % self.pretty_name)
def truediv(self, left, right) -> Union["Series", "Index"]:
raise TypeError("True division can not be applied to %s." % self.pretty_name)
def floordiv(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Floor division can not be applied to %s." % self.pretty_name)
def mod(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Modulo can not be applied to %s." % self.pretty_name)
def pow(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Exponentiation can not be applied to %s." % self.pretty_name)
def radd(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Addition can not be applied to %s." % self.pretty_name)
def rsub(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Subtraction can not be applied to %s." % self.pretty_name)
def rmul(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Multiplication can not be applied to %s." % self.pretty_name)
def rtruediv(self, left, right) -> Union["Series", "Index"]:
raise TypeError("True division can not be applied to %s." % self.pretty_name)
def rfloordiv(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Floor division can not be applied to %s." % self.pretty_name)
def rmod(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Modulo can not be applied to %s." % self.pretty_name)
def rpow(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Exponentiation can not be applied to %s." % self.pretty_name)
def __and__(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Bitwise and can not be applied to %s." % self.pretty_name)
def __or__(self, left, right) -> Union["Series", "Index"]:
raise TypeError("Bitwise or can not be applied to %s." % self.pretty_name)
def rand(self, left, right) -> Union["Series", "Index"]:
return left.__and__(right)
def ror(self, left, right) -> Union["Series", "Index"]:
return left.__or__(right)
def restore(self, col: pd.Series) -> pd.Series:
"""Restore column when to_pandas."""
return col
def prepare(self, col: pd.Series) -> pd.Series:
"""Prepare column when from_pandas."""
return col.replace({np.nan: None})
def astype(
self, index_ops: Union["Index", "Series"], dtype: Union[str, type, Dtype]
) -> Union["Index", "Series"]:
raise TypeError("astype can not be applied to %s." % self.pretty_name)
| apache-2.0 | 8,822,871,887,076,614,000 | 39.081699 | 100 | 0.658296 | false | 3.882558 | false | false | false |
MTK6580/walkie-talkie | ALPS.L1.MP6.V2_HEXING6580_WE_L/alps/build/tools/releasetools/img_from_target_files.py | 1 | 4926 | #!/usr/bin/env python
#
# Copyright (C) 2008 The Android Open Source Project
#
# 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.
"""
Given a target-files zipfile, produces an image zipfile suitable for
use with 'fastboot update'.
Usage: img_from_target_files [flags] input_target_files output_image_zip
-z (--bootable_zip)
Include only the bootable images (eg 'boot' and 'recovery') in
the output.
"""
import sys
if sys.hexversion < 0x02070000:
print >> sys.stderr, "Python 2.7 or newer is required."
sys.exit(1)
import errno
import os
import re
import shutil
import subprocess
import tempfile
import zipfile
# missing in Python 2.4 and before
if not hasattr(os, "SEEK_SET"):
os.SEEK_SET = 0
import common
OPTIONS = common.OPTIONS
def CopyInfo(output_zip):
"""Copy the android-info.txt file from the input to the output."""
output_zip.write(os.path.join(OPTIONS.input_tmp, "OTA", "android-info.txt"),
"android-info.txt")
def main(argv):
bootable_only = [False]
def option_handler(o, a):
if o in ("-z", "--bootable_zip"):
bootable_only[0] = True
else:
return False
return True
args = common.ParseOptions(argv, __doc__,
extra_opts="z",
extra_long_opts=["bootable_zip"],
extra_option_handler=option_handler)
bootable_only = bootable_only[0]
if len(args) != 2:
common.Usage(__doc__)
sys.exit(1)
OPTIONS.input_tmp, input_zip = common.UnzipTemp(args[0])
output_zip = zipfile.ZipFile(args[1], "w", compression=zipfile.ZIP_DEFLATED)
CopyInfo(output_zip)
try:
done = False
images_path = os.path.join(OPTIONS.input_tmp, "IMAGES")
if os.path.exists(images_path):
# If this is a new target-files, it already contains the images,
# and all we have to do is copy them to the output zip.
images = os.listdir(images_path)
if images:
for i in images:
if bootable_only and i not in ("boot.img", "recovery.img"): continue
if not i.endswith(".img"): continue
with open(os.path.join(images_path, i), "r") as f:
common.ZipWriteStr(output_zip, i, f.read())
done = True
if not done:
# We have an old target-files that doesn't already contain the
# images, so build them.
import add_img_to_target_files
OPTIONS.info_dict = common.LoadInfoDict(input_zip)
# If this image was originally labelled with SELinux contexts,
# make sure we also apply the labels in our new image. During
# building, the "file_contexts" is in the out/ directory tree,
# but for repacking from target-files.zip it's in the root
# directory of the ramdisk.
if "selinux_fc" in OPTIONS.info_dict:
OPTIONS.info_dict["selinux_fc"] = os.path.join(
OPTIONS.input_tmp, "BOOT", "RAMDISK", "file_contexts")
boot_image = common.GetBootableImage(
"boot.img", "boot.img", OPTIONS.input_tmp, "BOOT")
if boot_image:
boot_image.AddToZip(output_zip)
recovery_image = common.GetBootableImage(
"recovery.img", "recovery.img", OPTIONS.input_tmp, "RECOVERY")
if recovery_image:
recovery_image.AddToZip(output_zip)
def banner(s):
print "\n\n++++ " + s + " ++++\n\n"
if not bootable_only:
banner("AddSystem")
add_img_to_target_files.AddSystem(output_zip, prefix="")
try:
input_zip.getinfo("VENDOR/")
banner("AddVendor")
add_img_to_target_files.AddVendor(output_zip, prefix="")
except KeyError:
pass # no vendor partition for this device
try:
input_zip.getinfo("CUSTOM/")
banner("AddCustom")
add_img_to_target_files.AddCustom(output_zip, prefix="")
except KeyError:
pass # no custom partition for this device
banner("AddUserdata")
add_img_to_target_files.AddUserdata(output_zip, prefix="")
banner("AddCache")
add_img_to_target_files.AddCache(output_zip, prefix="")
finally:
print "cleaning up..."
output_zip.close()
shutil.rmtree(OPTIONS.input_tmp)
print "done."
if __name__ == '__main__':
try:
common.CloseInheritedPipes()
main(sys.argv[1:])
except common.ExternalError, e:
print
print " ERROR: %s" % (e,)
print
sys.exit(1)
| gpl-3.0 | 3,824,091,379,033,798,000 | 29.407407 | 78 | 0.634592 | false | 3.603511 | false | false | false |
JKarathiya/Lean | Algorithm.Python/FutureOptionShortPutOTMExpiryRegressionAlgorithm.py | 1 | 5416 | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License
from datetime import datetime, timedelta
import clr
from System import *
from System.Reflection import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Data import *
from QuantConnect.Data.Market import *
from QuantConnect.Orders import *
from QuantConnect.Securities import *
from QuantConnect.Securities.Future import *
from QuantConnect import Market
### <summary>
### This regression algorithm tests Out of The Money (OTM) future option expiry for short puts.
### We expect 2 orders from the algorithm, which are:
###
### * Initial entry, sell ES Put Option (expiring OTM)
### - Profit the option premium, since the option was not assigned.
###
### * Liquidation of ES put OTM contract on the last trade date
###
### Additionally, we test delistings for future options and assert that our
### portfolio holdings reflect the orders the algorithm has submitted.
### </summary>
class FutureOptionShortPutOTMExpiryRegressionAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 1, 5)
self.SetEndDate(2020, 6, 30)
self.es19m20 = self.AddFutureContract(
Symbol.CreateFuture(
Futures.Indices.SP500EMini,
Market.CME,
datetime(2020, 6, 19)),
Resolution.Minute).Symbol
# Select a future option expiring ITM, and adds it to the algorithm.
self.esOption = self.AddFutureOptionContract(
list(
sorted(
[x for x in self.OptionChainProvider.GetOptionContractList(self.es19m20, self.Time) if x.ID.StrikePrice <= 3000.0 and x.ID.OptionRight == OptionRight.Put],
key=lambda x: x.ID.StrikePrice,
reverse=True
)
)[0], Resolution.Minute).Symbol
self.expectedContract = Symbol.CreateOption(self.es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3000.0, datetime(2020, 6, 19))
if self.esOption != self.expectedContract:
raise AssertionError(f"Contract {self.expectedContract} was not found in the chain");
self.Schedule.On(self.DateRules.Tomorrow, self.TimeRules.AfterMarketOpen(self.es19m20, 1), self.ScheduledMarketOrder)
def ScheduledMarketOrder(self):
self.MarketOrder(self.esOption, -1)
def OnData(self, data: Slice):
# Assert delistings, so that we can make sure that we receive the delisting warnings at
# the expected time. These assertions detect bug #4872
for delisting in data.Delistings.Values:
if delisting.Type == DelistingType.Warning:
if delisting.Time != datetime(2020, 6, 19):
raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.Time}");
if delisting.Type == DelistingType.Delisted:
if delisting.Time != datetime(2020, 6, 20):
raise AssertionError(f"Delisting happened at unexpected date: {delisting.Time}");
def OnOrderEvent(self, orderEvent: OrderEvent):
if orderEvent.Status != OrderStatus.Filled:
# There's lots of noise with OnOrderEvent, but we're only interested in fills.
return
if not self.Securities.ContainsKey(orderEvent.Symbol):
raise AssertionError(f"Order event Symbol not found in Securities collection: {orderEvent.Symbol}")
security = self.Securities[orderEvent.Symbol]
if security.Symbol == self.es19m20:
raise AssertionError(f"Expected no order events for underlying Symbol {security.Symbol}")
if security.Symbol == self.expectedContract:
self.AssertFutureOptionContractOrder(orderEvent, security)
else:
raise AssertionError(f"Received order event for unknown Symbol: {orderEvent.Symbol}")
self.Log(f"{orderEvent}");
def AssertFutureOptionContractOrder(self, orderEvent: OrderEvent, optionContract: Security):
if orderEvent.Direction == OrderDirection.Sell and optionContract.Holdings.Quantity != -1:
raise AssertionError(f"No holdings were created for option contract {optionContract.Symbol}")
if orderEvent.Direction == OrderDirection.Buy and optionContract.Holdings.Quantity != 0:
raise AssertionError("Expected no options holdings after closing position")
if orderEvent.IsAssignment:
raise AssertionError(f"Assignment was not expected for {orderEvent.Symbol}")
def OnEndOfAlgorithm(self):
if self.Portfolio.Invested:
raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.ID) for i in self.Portfolio.Keys])}") | apache-2.0 | 1,143,300,330,185,993,500 | 45.299145 | 175 | 0.694978 | false | 4.069121 | false | false | false |
Johnzero/erp | openerp/addons/clivia_analysis/report/analysis_report.py | 1 | 2399 | # -*- encoding: utf-8 -*-
import tools
from osv import fields, osv
class common_report(osv.osv):
_name = "clivia_analysis.production_report"
_description = "报表视图"
_auto = False
_rec_name = 'date'
_columns = {
'year': fields.char('年份', size=4, readonly=True),
'month': fields.selection([('01', '一月'), ('02', '二月'), ('03', '三月'), ('04', '四月'),
('05', '五月'), ('06', '六月'), ('07', '七月'), ('08', '八月'), ('09', '九月'), ('10', '十月'),
('11', '十一月'), ('12', '十二月')], '月份', readonly=True),
'date': fields.date('上报时间', required=True, readonly=True),
'product_id': fields.many2one('clivia_analysis.stocked_product', '产品', readonly=True),
'produced': fields.integer('生产', readonly=True),
'sent': fields.float('发出', readonly=True),
'sold': fields.integer('销售', readonly=True),
'hefei_today_inventory':fields.integer('君子兰结存', readonly=True),
'sanhe_last_inventory':fields.integer('三河实际库存', readonly=True),
}
_order = 'date desc'
def init(self, cr):
tools.drop_view_if_exists(cr, 'clivia_analysis_production_report')
cr.execute("""
CREATE OR REPLACE VIEW clivia_analysis_production_report AS
SELECT DISTINCT ON (product.id) product.id, product.id AS product_id,
mpl.production AS produced,
mpl.hefei_warning_level,
mpl.sanhe_warning_level,
drl.hefei_today_inventory AS hefei_today_inventory,
drl.sanhe_real_inventory AS sanhe_real_inventory,
dr.date_created date,
to_char(dr.date_created::timestamp with time zone, 'YYYY'::text) AS year,
to_char(dr.date_created::timestamp with time zone, 'MM'::text) AS month,
drl.sent,
drl.sold
FROM clivia_analysis_stocked_product product
JOIN clivia_analysis_daily_report_line drl ON product.id = drl.product_id
JOIN clivia_analysis_daily_report dr ON dr.id = drl.report_id
JOIN clivia_analysis_monthly_plan_line mpl ON mpl.product_id = product.id
WHERE dr.state::text = 'review'::text
ORDER BY product.id, dr.date_created DESC;
""")
| agpl-3.0 | -2,405,913,437,995,879,000 | 43.803922 | 96 | 0.570241 | false | 3.204769 | false | false | false |
CN-UPB/OpenBarista | components/decaf-masta/decaf_masta/components/database/datacenter.py | 1 | 1976 | ##
# Copyright 2016 DECaF Project Group, University of Paderborn
# This file is part of the decaf orchestration framework
# All Rights Reserved.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
##
__author__ = 'Kristian Hinnenthal'
__date__ = '$13-okt-2015 14:15:27$'
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from .mastadatabase import Base
from .keystone import Keystone
import json
class Datacenter(Base):
__tablename__ = 'datacenters'
datacenter_id = Column(Integer, primary_key=True,autoincrement=True)
datacenter_name = Column(String(250), nullable=False)
keystone_id = Column(Integer, ForeignKey('keystone_credentials.keystone_id'), nullable=False)
keystone_region = Column(String(250), nullable=False)
flavors = relationship('Flavor', backref='datacenters')
images = relationship('Image', backref='datacenters')
monitoring_alarms = relationship('MonitoringAlarm', backref='datacenters')
management_networks = relationship('ManagementNetwork', backref='datacenters')
public_networks = relationship('PublicNetwork', backref='datacenters')
vm_instances = relationship('VMInstance', backref='datacenters')
internal_edges = relationship('InternalEdge', backref='datacenters')
public_ports = relationship('PublicPort', backref='datacenters')
keypairs = relationship('KeyPair', backref='datacenter')
def to_json(self):
return json.dumps(self.to_dict())
def to_dict(self):
return_dict = {
"datacenter" : {
"datacenter_id": self.datacenter_id,
"datacenter_name": self.datacenter_name,
"keystone_id": self.keystone_id,
"keystone_region": self.keystone_region
}
}
return return_dict | mpl-2.0 | -113,731,610,094,640,820 | 41.06383 | 97 | 0.695344 | false | 4.074227 | false | false | false |
googleapis/python-essential-contacts | google/cloud/essential_contacts_v1/services/essential_contacts_service/client.py | 1 | 36542 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from collections import OrderedDict
from distutils import util
import os
import re
from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.essential_contacts_v1.services.essential_contacts_service import (
pagers,
)
from google.cloud.essential_contacts_v1.types import enums
from google.cloud.essential_contacts_v1.types import service
from google.protobuf import field_mask_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
from .transports.base import EssentialContactsServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import EssentialContactsServiceGrpcTransport
from .transports.grpc_asyncio import EssentialContactsServiceGrpcAsyncIOTransport
class EssentialContactsServiceClientMeta(type):
"""Metaclass for the EssentialContactsService client.
This provides class-level methods for building and retrieving
support objects (e.g. transport) without polluting the client instance
objects.
"""
_transport_registry = (
OrderedDict()
) # type: Dict[str, Type[EssentialContactsServiceTransport]]
_transport_registry["grpc"] = EssentialContactsServiceGrpcTransport
_transport_registry["grpc_asyncio"] = EssentialContactsServiceGrpcAsyncIOTransport
def get_transport_class(
cls, label: str = None,
) -> Type[EssentialContactsServiceTransport]:
"""Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use.
"""
# If a specific transport is requested, return that one.
if label:
return cls._transport_registry[label]
# No transport is requested; return the default (that is, the first one
# in the dictionary).
return next(iter(cls._transport_registry.values()))
class EssentialContactsServiceClient(metaclass=EssentialContactsServiceClientMeta):
"""Manages contacts for important Google Cloud notifications."""
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
"""Converts api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint.
"""
if not api_endpoint:
return api_endpoint
mtls_endpoint_re = re.compile(
r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
)
m = mtls_endpoint_re.match(api_endpoint)
name, mtls, sandbox, googledomain = m.groups()
if mtls or not googledomain:
return api_endpoint
if sandbox:
return api_endpoint.replace(
"sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
)
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
DEFAULT_ENDPOINT = "essentialcontacts.googleapis.com"
DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
DEFAULT_ENDPOINT
)
@classmethod
def from_service_account_info(cls, info: dict, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
info.
Args:
info (dict): The service account private key info.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
EssentialContactsServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_info(info)
kwargs["credentials"] = credentials
return cls(*args, **kwargs)
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
EssentialContactsServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
return cls(*args, **kwargs)
from_service_account_json = from_service_account_file
@property
def transport(self) -> EssentialContactsServiceTransport:
"""Returns the transport used by the client instance.
Returns:
EssentialContactsServiceTransport: The transport used by the client
instance.
"""
return self._transport
@staticmethod
def contact_path(project: str, contact: str,) -> str:
"""Returns a fully-qualified contact string."""
return "projects/{project}/contacts/{contact}".format(
project=project, contact=contact,
)
@staticmethod
def parse_contact_path(path: str) -> Dict[str, str]:
"""Parses a contact path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)/contacts/(?P<contact>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
"""Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@staticmethod
def parse_common_billing_account_path(path: str) -> Dict[str, str]:
"""Parse a billing_account path into its component segments."""
m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_folder_path(folder: str,) -> str:
"""Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
def parse_common_folder_path(path: str) -> Dict[str, str]:
"""Parse a folder path into its component segments."""
m = re.match(r"^folders/(?P<folder>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_organization_path(organization: str,) -> str:
"""Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
def parse_common_organization_path(path: str) -> Dict[str, str]:
"""Parse a organization path into its component segments."""
m = re.match(r"^organizations/(?P<organization>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_project_path(project: str,) -> str:
"""Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
def parse_common_project_path(path: str) -> Dict[str, str]:
"""Parse a project path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_location_path(project: str, location: str,) -> str:
"""Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@staticmethod
def parse_common_location_path(path: str) -> Dict[str, str]:
"""Parse a location path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
return m.groupdict() if m else {}
def __init__(
self,
*,
credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, EssentialContactsServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
"""Instantiates the essential contacts service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
transport (Union[str, EssentialContactsServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
environment variable can also be used to override the endpoint:
"always" (always use the default mTLS endpoint), "never" (always
use the default regular endpoint) and "auto" (auto switch to the
default mTLS endpoint if client certificate is present, this is
the default value). However, the ``api_endpoint`` property takes
precedence if provided.
(2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
is "true", then the ``client_cert_source`` property can be used
to provide client certificate for mutual TLS transport. If
not provided, the default SSL client certificate will be used if
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
set, no client certificate will be used.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = client_options_lib.from_dict(client_options)
if client_options is None:
client_options = client_options_lib.ClientOptions()
# Create SSL credentials for mutual TLS if needed.
use_client_cert = bool(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
is_mtls = True
client_cert_source_func = client_options.client_cert_source
else:
is_mtls = mtls.has_default_client_cert_source()
if is_mtls:
client_cert_source_func = mtls.default_client_cert_source()
else:
client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
api_endpoint = client_options.api_endpoint
else:
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
if use_mtls_env == "never":
api_endpoint = self.DEFAULT_ENDPOINT
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
if is_mtls:
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
else:
api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
"values: never, auto, always"
)
# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, EssentialContactsServiceTransport):
# transport is a EssentialContactsServiceTransport instance.
if credentials or client_options.credentials_file:
raise ValueError(
"When providing a transport instance, "
"provide its credentials directly."
)
if client_options.scopes:
raise ValueError(
"When providing a transport instance, provide its scopes "
"directly."
)
self._transport = transport
else:
Transport = type(self).get_transport_class(transport)
self._transport = Transport(
credentials=credentials,
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
def create_contact(
self,
request: service.CreateContactRequest = None,
*,
parent: str = None,
contact: service.Contact = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> service.Contact:
r"""Adds a new contact for a resource.
Args:
request (google.cloud.essential_contacts_v1.types.CreateContactRequest):
The request object. Request message for the
CreateContact method.
parent (str):
Required. The resource to save this contact for. Format:
organizations/{organization_id}, folders/{folder_id} or
projects/{project_id}
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
contact (google.cloud.essential_contacts_v1.types.Contact):
Required. The contact to create. Must
specify an email address and language
tag.
This corresponds to the ``contact`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.essential_contacts_v1.types.Contact:
A contact that will receive
notifications from Google Cloud.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([parent, contact])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a service.CreateContactRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, service.CreateContactRequest):
request = service.CreateContactRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if parent is not None:
request.parent = parent
if contact is not None:
request.contact = contact
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.create_contact]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def update_contact(
self,
request: service.UpdateContactRequest = None,
*,
contact: service.Contact = None,
update_mask: field_mask_pb2.FieldMask = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> service.Contact:
r"""Updates a contact.
Note: A contact's email address cannot be changed.
Args:
request (google.cloud.essential_contacts_v1.types.UpdateContactRequest):
The request object. Request message for the
UpdateContact method.
contact (google.cloud.essential_contacts_v1.types.Contact):
Required. The contact resource to
replace the existing saved contact.
Note: the email address of the contact
cannot be modified.
This corresponds to the ``contact`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Optional. The update mask applied to the resource. For
the ``FieldMask`` definition, see
https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
This corresponds to the ``update_mask`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.essential_contacts_v1.types.Contact:
A contact that will receive
notifications from Google Cloud.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([contact, update_mask])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a service.UpdateContactRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, service.UpdateContactRequest):
request = service.UpdateContactRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if contact is not None:
request.contact = contact
if update_mask is not None:
request.update_mask = update_mask
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.update_contact]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata(
(("contact.name", request.contact.name),)
),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def list_contacts(
self,
request: service.ListContactsRequest = None,
*,
parent: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListContactsPager:
r"""Lists the contacts that have been set on a resource.
Args:
request (google.cloud.essential_contacts_v1.types.ListContactsRequest):
The request object. Request message for the ListContacts
method.
parent (str):
Required. The parent resource name. Format:
organizations/{organization_id}, folders/{folder_id} or
projects/{project_id}
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.essential_contacts_v1.services.essential_contacts_service.pagers.ListContactsPager:
Response message for the ListContacts
method.
Iterating over this object will yield
results and resolve additional pages
automatically.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([parent])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a service.ListContactsRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, service.ListContactsRequest):
request = service.ListContactsRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if parent is not None:
request.parent = parent
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.list_contacts]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ListContactsPager(
method=rpc, request=request, response=response, metadata=metadata,
)
# Done; return the response.
return response
def get_contact(
self,
request: service.GetContactRequest = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> service.Contact:
r"""Gets a single contact.
Args:
request (google.cloud.essential_contacts_v1.types.GetContactRequest):
The request object. Request message for the GetContact
method.
name (str):
Required. The name of the contact to retrieve. Format:
organizations/{organization_id}/contacts/{contact_id},
folders/{folder_id}/contacts/{contact_id} or
projects/{project_id}/contacts/{contact_id}
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.essential_contacts_v1.types.Contact:
A contact that will receive
notifications from Google Cloud.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([name])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a service.GetContactRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, service.GetContactRequest):
request = service.GetContactRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if name is not None:
request.name = name
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.get_contact]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def delete_contact(
self,
request: service.DeleteContactRequest = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> None:
r"""Deletes a contact.
Args:
request (google.cloud.essential_contacts_v1.types.DeleteContactRequest):
The request object. Request message for the
DeleteContact method.
name (str):
Required. The name of the contact to delete. Format:
organizations/{organization_id}/contacts/{contact_id},
folders/{folder_id}/contacts/{contact_id} or
projects/{project_id}/contacts/{contact_id}
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([name])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a service.DeleteContactRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, service.DeleteContactRequest):
request = service.DeleteContactRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if name is not None:
request.name = name
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.delete_contact]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
rpc(
request, retry=retry, timeout=timeout, metadata=metadata,
)
def compute_contacts(
self,
request: service.ComputeContactsRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ComputeContactsPager:
r"""Lists all contacts for the resource that are
subscribed to the specified notification categories,
including contacts inherited from any parent resources.
Args:
request (google.cloud.essential_contacts_v1.types.ComputeContactsRequest):
The request object. Request message for the
ComputeContacts method.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.essential_contacts_v1.services.essential_contacts_service.pagers.ComputeContactsPager:
Response message for the
ComputeContacts method.
Iterating over this object will yield
results and resolve additional pages
automatically.
"""
# Create or coerce a protobuf request object.
# Minor optimization to avoid making a copy if the user passes
# in a service.ComputeContactsRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, service.ComputeContactsRequest):
request = service.ComputeContactsRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.compute_contacts]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ComputeContactsPager(
method=rpc, request=request, response=response, metadata=metadata,
)
# Done; return the response.
return response
def send_test_message(
self,
request: service.SendTestMessageRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> None:
r"""Allows a contact admin to send a test message to
contact to verify that it has been configured correctly.
Args:
request (google.cloud.essential_contacts_v1.types.SendTestMessageRequest):
The request object. Request message for the
SendTestMessage method.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
# Create or coerce a protobuf request object.
# Minor optimization to avoid making a copy if the user passes
# in a service.SendTestMessageRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, service.SendTestMessageRequest):
request = service.SendTestMessageRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.send_test_message]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
)
# Send the request.
rpc(
request, retry=retry, timeout=timeout, metadata=metadata,
)
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
"google-cloud-essential-contacts",
).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
__all__ = ("EssentialContactsServiceClient",)
| apache-2.0 | 6,529,256,094,567,324,000 | 41.540163 | 111 | 0.617946 | false | 4.636721 | false | false | false |
Dev-Cloud-Platform/Dev-Cloud | dev_cloud/cc1/src/wi/views/user/user.py | 1 | 7236 | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# 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.
#
# @COPYRIGHT_end
"""@package src.wi.views.user.user
@author Piotr Wójcik
@date 31.01.2014
"""
from django.contrib import messages
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from django.views.decorators.csrf import csrf_protect
from wi.commontags.templatetags.templatetags import filesizeformatmb
from wi.forms.user import CMAuthenticationForm, HelpForm, PasswordChangeForm, \
AccountDataEdit
from wi.utils import get_dict_from_list, messages_ajax
from wi.utils.decorators import django_view, user_permission
from wi.utils.exceptions import RestErrorException
from wi.utils.messages_ajax import ajax_request
from wi.utils.messages_codes import get_message
from wi.utils.states import message_levels_reversed
from wi.utils.views import prep_data
@django_view
@user_permission
def change_cm(request, cm_id, success_url='mai_main'):
"""
View changing used CM.
"""
request.session['user'].cm_id = int(cm_id)
request.session.modified = True
messages.success(request, _('Cluster Manager changed.'))
return redirect(request.META['HTTP_REFERER'] or success_url)
@django_view
@ajax_request
@user_permission
def get_messages(request):
"""
Ajax view fetching user messages.
"""
if request.method == 'POST':
response = prep_data('user/message/get_list/', request.session)
for item in response:
item['text'] = get_message(item['code'], item['params'])
item['level'] = message_levels_reversed[item['level']]
return messages_ajax.success(response)
@django_view
@ajax_request
@user_permission
def acc_ajax_get_user_data(request):
"""
Ajax view. Returns user account data.
"""
if request.method == 'GET':
rest_data = prep_data({'user': 'user/user/get_my_data/',
'cms': 'guest/cluster/list_names/'
}, request.session)
user_data = rest_data['user']
users_cm = get_dict_from_list(rest_data['cms'], user_data['default_cluster_id'], key='cluster_id')
if users_cm is None:
raise Exception('User\'s default_cluster_id=%d is not a valid CM id.' % user_data['default_cluster_id'])
user_data['default_cluster_id'] = users_cm['name']
return messages_ajax.success(user_data)
@django_view
@ajax_request
@user_permission
@csrf_protect
def acc_ajax_account_data_edit(request, template_name='generic/form.html', form_class=AccountDataEdit):
"""
Ajax view for user account data editing.
"""
rest_data = prep_data({'cms': 'guest/cluster/list_names/'}, request.session)
if request.method == 'POST':
form = form_class(data=request.POST, rest_data=rest_data)
if form.is_valid():
prep_data({'user': ('user/user/edit/', form.cleaned_data)}, request.session)
request.session['user'].email = form.cleaned_data['email']
request.session['user'].default_cluster_id = form.cleaned_data['default_cluster_id']
request.session.modified = True
return messages_ajax.success(_('Account data edited.'))
else:
form = form_class(data={'email': request.session['user'].email,
'default_cluster_id': request.session['user'].default_cluster_id}, rest_data=rest_data)
return messages_ajax.success(render_to_string(template_name, {'form': form,
'text': '',
'confirmation': _('Save')},
context_instance=RequestContext(request)),
status=1)
@django_view
@ajax_request
@user_permission
def acc_ajax_get_user_quotas(request):
"""
Ajax view for fetching users' quotas.
"""
if request.method == 'GET':
quota = prep_data('user/user/check_quota/', request.session)
quota['memory'] = filesizeformatmb(quota['memory'])
quota['used_memory'] = filesizeformatmb(quota['used_memory'])
quota['storage'] = filesizeformatmb(quota['storage'])
quota['used_storage'] = filesizeformatmb(quota['used_storage'])
return messages_ajax.success(quota)
@django_view
@csrf_protect
@user_permission
def acc_password_change(request, template_name='account/password_change_form.html',
password_change_form=PasswordChangeForm):
"""
View for password changing (for logged users).
"""
if request.method == "POST":
form = password_change_form(user=request.session['user'], data=request.POST)
if form.is_valid():
new_password = form.cleaned_data['new_password1']
try:
prep_data(('user/user/set_password/', {'new_password': new_password}), request.session)
except RestErrorException as ex:
messages.error(request, ex.value)
request.session['user'].set_password(new_password)
request.session.modified = True
return redirect('acc_password_change_done')
else:
form = password_change_form(user=request.session['user'])
return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request))
@django_view
@user_permission
def hlp_form(request, form_class=HelpForm, template_name='help/form.html'):
"""
View handling help form.
"""
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
topic, issue, email = form.cleaned_data['topic'], form.cleaned_data['issue'], form.cleaned_data['email']
name = str(request.session.get('user', form.cleaned_data['firstlast']))
topic += _(' from user:') + name + ', email: ' + email
dictionary = {'issue': issue,
'topic': topic}
try:
prep_data(('user/user/send_issue/', dictionary), request.session)
except Exception:
return redirect('hlp_issue_error')
return redirect('hlp_issue_sent')
else:
form = form_class()
rest_data = prep_data('guest/user/is_mailer_active/', request.session)
return render_to_response(template_name, dict({'form': form}.items() + rest_data.items()),
context_instance=RequestContext(request))
| apache-2.0 | 6,534,912,669,814,899,000 | 35.913265 | 119 | 0.634969 | false | 3.942779 | false | false | false |
mahim97/zulip | zerver/webhooks/github_webhook/tests.py | 5 | 21928 | from typing import Dict, Optional, Text
import ujson
from mock import MagicMock, patch
from zerver.lib.test_classes import WebhookTestCase
from zerver.lib.webhooks.git import COMMITS_LIMIT
from zerver.models import Message
class GithubWebhookTest(WebhookTestCase):
STREAM_NAME = 'github'
URL_TEMPLATE = "/api/v1/external/github?stream={stream}&api_key={api_key}"
FIXTURE_DIR_NAME = 'github_webhook'
EXPECTED_SUBJECT_REPO_EVENTS = u"public-repo"
EXPECTED_SUBJECT_ISSUE_EVENTS = u"public-repo / Issue #2 Spelling error in the README file"
EXPECTED_SUBJECT_PR_EVENTS = u"public-repo / PR #1 Update the README with new information"
EXPECTED_SUBJECT_DEPLOYMENT_EVENTS = u"public-repo / Deployment on production"
EXPECTED_SUBJECT_ORGANIZATION_EVENTS = u"baxterandthehackers organization"
EXPECTED_SUBJECT_BRANCH_EVENTS = u"public-repo / changes"
EXPECTED_SUBJECT_WIKI_EVENTS = u"public-repo / Wiki Pages"
def test_ping_event(self) -> None:
expected_message = u"GitHub webhook has been successfully configured by TomaszKolek"
self.send_and_test_stream_message('ping', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='ping')
def test_ping_organization_event(self) -> None:
expected_message = u"GitHub webhook has been successfully configured by eeshangarg"
self.send_and_test_stream_message('ping_organization', 'zulip-test-org', expected_message, HTTP_X_GITHUB_EVENT='ping')
def test_push_delete_branch(self) -> None:
expected_message = u"eeshangarg [deleted](https://github.com/eeshangarg/public-repo/compare/2e8cf535fb38...000000000000) the branch feature."
self.send_and_test_stream_message('push_delete_branch', u"public-repo / feature", expected_message, HTTP_X_GITHUB_EVENT='push')
def test_push_local_branch_without_commits(self) -> None:
expected_message = u"eeshangarg [pushed](https://github.com/eeshangarg/public-repo/compare/feature) the branch feature."
self.send_and_test_stream_message('push_local_branch_without_commits', u"public-repo / feature", expected_message, HTTP_X_GITHUB_EVENT='push')
def test_push_1_commit(self) -> None:
expected_message = u"baxterthehacker [pushed](https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f) 1 commit to branch changes.\n\n* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))"
self.send_and_test_stream_message('push_1_commit', self.EXPECTED_SUBJECT_BRANCH_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='push')
def test_push_1_commit_without_username(self) -> None:
expected_message = u"eeshangarg [pushed](https://github.com/eeshangarg/public-repo/compare/0383613da871...2e8cf535fb38) 1 commit to branch changes. Commits by John Snow (1).\n\n* Update the README ([2e8cf53](https://github.com/eeshangarg/public-repo/commit/2e8cf535fb38a3dab2476cdf856efda904ad4c94))"
self.send_and_test_stream_message('push_1_commit_without_username', self.EXPECTED_SUBJECT_BRANCH_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='push')
def test_push_1_commit_filtered_by_branches(self) -> None:
self.url = self.build_webhook_url('master,changes')
expected_message = u"baxterthehacker [pushed](https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f) 1 commit to branch changes.\n\n* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))"
self.send_and_test_stream_message('push_1_commit', self.EXPECTED_SUBJECT_BRANCH_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='push')
def test_push_multiple_comitters(self) -> None:
commits_info = u'* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))\n'
expected_message = u"""baxterthehacker [pushed](https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f) 6 commits to branch changes. Commits by Tomasz (3), Ben (2) and baxterthehacker (1).\n\n{}* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))""".format(commits_info * 5)
self.send_and_test_stream_message('push_multiple_committers', self.EXPECTED_SUBJECT_BRANCH_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='push')
def test_push_multiple_comitters_with_others(self) -> None:
commits_info = u'* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))\n'
expected_message = u"""baxterthehacker [pushed](https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f) 10 commits to branch changes. Commits by Tomasz (4), Ben (3), James (2) and others (1).\n\n{}* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))""".format(commits_info * 9)
self.send_and_test_stream_message('push_multiple_committers_with_others', self.EXPECTED_SUBJECT_BRANCH_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='push')
def test_push_multiple_comitters_filtered_by_branches(self) -> None:
self.url = self.build_webhook_url('master,changes')
commits_info = u'* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))\n'
expected_message = u"""baxterthehacker [pushed](https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f) 6 commits to branch changes. Commits by Tomasz (3), Ben (2) and baxterthehacker (1).\n\n{}* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))""".format(commits_info * 5)
self.send_and_test_stream_message('push_multiple_committers', self.EXPECTED_SUBJECT_BRANCH_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='push')
def test_push_multiple_comitters_with_others_filtered_by_branches(self) -> None:
self.url = self.build_webhook_url('master,changes')
commits_info = u'* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))\n'
expected_message = u"""baxterthehacker [pushed](https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f) 10 commits to branch changes. Commits by Tomasz (4), Ben (3), James (2) and others (1).\n\n{}* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))""".format(commits_info * 9)
self.send_and_test_stream_message('push_multiple_committers_with_others', self.EXPECTED_SUBJECT_BRANCH_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='push')
def test_push_50_commits(self) -> None:
commit_info = "* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))\n"
expected_message = u"baxterthehacker [pushed](https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f) 50 commits to branch changes.\n\n{}[and 30 more commit(s)]".format(
commit_info * COMMITS_LIMIT
)
self.send_and_test_stream_message('push_50_commits', self.EXPECTED_SUBJECT_BRANCH_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='push')
def test_push_50_commits_filtered_by_branches(self) -> None:
self.url = self.build_webhook_url(branches='master,changes')
commit_info = "* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))\n"
expected_message = u"baxterthehacker [pushed](https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f) 50 commits to branch changes.\n\n{}[and 30 more commit(s)]".format(
commit_info * COMMITS_LIMIT
)
self.send_and_test_stream_message('push_50_commits', self.EXPECTED_SUBJECT_BRANCH_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='push')
def test_commit_comment_msg(self) -> None:
expected_message = u"baxterthehacker [commented](https://github.com/baxterthehacker/public-repo/commit/9049f1265b7d61be4a8904a9a27120d2064dab3b#commitcomment-11056394) on [9049f12](https://github.com/baxterthehacker/public-repo/commit/9049f1265b7d61be4a8904a9a27120d2064dab3b)\n~~~ quote\nThis is a really good change! :+1:\n~~~"
self.send_and_test_stream_message('commit_comment', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='commit_comment')
def test_create_msg(self) -> None:
expected_message = u"baxterthehacker created tag 0.0.1"
self.send_and_test_stream_message('create', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='create')
def test_delete_msg(self) -> None:
expected_message = u"baxterthehacker deleted tag simple-tag"
self.send_and_test_stream_message('delete', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='delete')
def test_deployment_msg(self) -> None:
expected_message = u"baxterthehacker created new deployment"
self.send_and_test_stream_message('deployment', self.EXPECTED_SUBJECT_DEPLOYMENT_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='deployment')
def test_deployment_status_msg(self) -> None:
expected_message = u"Deployment changed status to success"
self.send_and_test_stream_message('deployment_status', self.EXPECTED_SUBJECT_DEPLOYMENT_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='deployment_status')
def test_fork_msg(self) -> None:
expected_message = u"baxterandthehackers forked [public-repo](https://github.com/baxterandthehackers/public-repo)"
self.send_and_test_stream_message('fork', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='fork')
def test_issue_comment_msg(self) -> None:
expected_message = u"baxterthehacker [commented](https://github.com/baxterthehacker/public-repo/issues/2#issuecomment-99262140) on [Issue #2](https://github.com/baxterthehacker/public-repo/issues/2)\n\n~~~ quote\nYou are totally right! I'll get this fixed right away.\n~~~"
self.send_and_test_stream_message('issue_comment', self.EXPECTED_SUBJECT_ISSUE_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='issue_comment')
def test_issue_msg(self) -> None:
expected_message = u"baxterthehacker opened [Issue #2](https://github.com/baxterthehacker/public-repo/issues/2)\n\n~~~ quote\nIt looks like you accidently spelled 'commit' with two 't's.\n~~~"
self.send_and_test_stream_message('issue', self.EXPECTED_SUBJECT_ISSUE_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='issues')
def test_membership_msg(self) -> None:
expected_message = u"baxterthehacker added [kdaigle](https://github.com/kdaigle) to Contractors team"
self.send_and_test_stream_message('membership', self.EXPECTED_SUBJECT_ORGANIZATION_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='membership')
def test_member_msg(self) -> None:
expected_message = u"baxterthehacker added [octocat](https://github.com/octocat) to [public-repo](https://github.com/baxterthehacker/public-repo)"
self.send_and_test_stream_message('member', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='member')
def test_pull_request_opened_msg(self) -> None:
expected_message = u"baxterthehacker opened [PR](https://github.com/baxterthehacker/public-repo/pull/1)\nfrom `changes` to `master`\n\n~~~ quote\nThis is a pretty simple change that we need to pull into master.\n~~~"
self.send_and_test_stream_message('opened_pull_request', self.EXPECTED_SUBJECT_PR_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='pull_request')
def test_pull_request_synchronized_msg(self) -> None:
expected_message = u"baxterthehacker updated [PR](https://github.com/baxterthehacker/public-repo/pull/1)\nfrom `changes` to `master`"
self.send_and_test_stream_message('synchronized_pull_request', self.EXPECTED_SUBJECT_PR_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='pull_request')
def test_pull_request_closed_msg(self) -> None:
expected_message = u"baxterthehacker closed without merge [PR](https://github.com/baxterthehacker/public-repo/pull/1)"
self.send_and_test_stream_message('closed_pull_request', self.EXPECTED_SUBJECT_PR_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='pull_request')
def test_pull_request_merged_msg(self) -> None:
expected_message = u"baxterthehacker merged [PR](https://github.com/baxterthehacker/public-repo/pull/1)"
self.send_and_test_stream_message('merged_pull_request', self.EXPECTED_SUBJECT_PR_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='pull_request')
def test_public_msg(self) -> None:
expected_message = u"baxterthehacker made [the repository](https://github.com/baxterthehacker/public-repo) public"
self.send_and_test_stream_message('public', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='public')
def test_wiki_pages_msg(self) -> None:
expected_message = u"jasonrudolph:\n* created [Home](https://github.com/baxterthehacker/public-repo/wiki/Home)\n* created [Home](https://github.com/baxterthehacker/public-repo/wiki/Home)"
self.send_and_test_stream_message('wiki_pages', self.EXPECTED_SUBJECT_WIKI_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='gollum')
def test_watch_msg(self) -> None:
expected_message = u"baxterthehacker starred [the repository](https://github.com/baxterthehacker/public-repo)"
self.send_and_test_stream_message('watch_repository', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='watch')
def test_repository_msg(self) -> None:
expected_message = u"baxterthehacker created [the repository](https://github.com/baxterandthehackers/public-repo)"
self.send_and_test_stream_message('repository', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='repository')
def test_team_add_msg(self) -> None:
expected_message = u"[The repository](https://github.com/baxterandthehackers/public-repo) was added to team github"
self.send_and_test_stream_message('team_add', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='team_add')
def test_release_msg(self) -> None:
expected_message = u"baxterthehacker published [the release](https://github.com/baxterthehacker/public-repo/releases/tag/0.0.1)"
self.send_and_test_stream_message('release', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='release')
def test_page_build_msg(self) -> None:
expected_message = u"Github Pages build, trigerred by baxterthehacker, is built"
self.send_and_test_stream_message('page_build', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='page_build')
def test_status_msg(self) -> None:
expected_message = u"[9049f12](https://github.com/baxterthehacker/public-repo/commit/9049f1265b7d61be4a8904a9a27120d2064dab3b) changed its status to success"
self.send_and_test_stream_message('status', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='status')
def test_pull_request_review_msg(self) -> None:
expected_message = u"baxterthehacker submitted [PR Review](https://github.com/baxterthehacker/public-repo/pull/1#pullrequestreview-2626884)"
self.send_and_test_stream_message('pull_request_review', self.EXPECTED_SUBJECT_PR_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='pull_request_review')
def test_pull_request_review_comment_msg(self) -> None:
expected_message = u"baxterthehacker created [PR Review Comment](https://github.com/baxterthehacker/public-repo/pull/1#discussion_r29724692)\n\n~~~ quote\nMaybe you should use more emojji on this line.\n~~~"
self.send_and_test_stream_message('pull_request_review_comment', self.EXPECTED_SUBJECT_PR_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='pull_request_review_comment')
def test_push_tag_msg(self) -> None:
expected_message = u"baxterthehacker pushed tag abc"
self.send_and_test_stream_message('push_tag', self.EXPECTED_SUBJECT_REPO_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='push')
def test_pull_request_edited_msg(self) -> None:
expected_message = u"baxterthehacker edited [PR](https://github.com/baxterthehacker/public-repo/pull/1)\nfrom `changes` to `master`"
self.send_and_test_stream_message('edited_pull_request', self.EXPECTED_SUBJECT_PR_EVENTS, expected_message,
HTTP_X_GITHUB_EVENT='pull_request')
def test_pull_request_assigned_msg(self) -> None:
expected_message = u"baxterthehacker assigned [PR](https://github.com/baxterthehacker/public-repo/pull/1) to baxterthehacker"
self.send_and_test_stream_message('assigned_pull_request', self.EXPECTED_SUBJECT_PR_EVENTS, expected_message,
HTTP_X_GITHUB_EVENT='pull_request')
def test_pull_request_unassigned_msg(self) -> None:
expected_message = u"eeshangarg unassigned [PR](https://github.com/zulip-test-org/helloworld/pull/1)"
self.send_and_test_stream_message(
'unassigned_pull_request',
'helloworld / PR #1 Mention that Zulip rocks!',
expected_message,
HTTP_X_GITHUB_EVENT='pull_request'
)
@patch('zerver.webhooks.github_webhook.view.check_send_stream_message')
def test_pull_request_labeled_ignore(
self, check_send_stream_message_mock: MagicMock) -> None:
payload = self.get_body('labeled_pull_request')
result = self.client_post(self.url, payload, HTTP_X_GITHUB_EVENT='pull_request', content_type="application/json")
self.assertFalse(check_send_stream_message_mock.called)
self.assert_json_success(result)
@patch('zerver.webhooks.github_webhook.view.check_send_stream_message')
def test_pull_request_unlabeled_ignore(
self, check_send_stream_message_mock: MagicMock) -> None:
payload = self.get_body('unlabeled_pull_request')
result = self.client_post(self.url, payload, HTTP_X_GITHUB_EVENT='pull_request', content_type="application/json")
self.assertFalse(check_send_stream_message_mock.called)
self.assert_json_success(result)
@patch('zerver.webhooks.github_webhook.view.check_send_stream_message')
def test_pull_request_request_review_ignore(
self, check_send_stream_message_mock: MagicMock) -> None:
payload = self.get_body('request_review_pull_request')
result = self.client_post(self.url, payload, HTTP_X_GITHUB_EVENT='pull_request', content_type="application/json")
self.assertFalse(check_send_stream_message_mock.called)
self.assert_json_success(result)
@patch('zerver.webhooks.github_webhook.view.check_send_stream_message')
def test_pull_request_request_review_remove_ignore(
self, check_send_stream_message_mock: MagicMock) -> None:
payload = self.get_body('request_review_removed_pull_request')
result = self.client_post(self.url, payload, HTTP_X_GITHUB_EVENT='pull_request', content_type="application/json")
self.assertFalse(check_send_stream_message_mock.called)
self.assert_json_success(result)
@patch('zerver.webhooks.github_webhook.view.check_send_stream_message')
def test_push_1_commit_filtered_by_branches_ignore(
self, check_send_stream_message_mock: MagicMock) -> None:
self.url = self.build_webhook_url(branches='master,development')
payload = self.get_body('push_1_commit')
result = self.client_post(self.url, payload, HTTP_X_GITHUB_EVENT='push', content_type="application/json")
self.assertFalse(check_send_stream_message_mock.called)
self.assert_json_success(result)
@patch('zerver.webhooks.github_webhook.view.check_send_stream_message')
def test_push_50_commits_filtered_by_branches_ignore(
self, check_send_stream_message_mock: MagicMock) -> None:
self.url = self.build_webhook_url(branches='master,development')
payload = self.get_body('push_50_commits')
result = self.client_post(self.url, payload, HTTP_X_GITHUB_EVENT='push', content_type="application/json")
self.assertFalse(check_send_stream_message_mock.called)
self.assert_json_success(result)
@patch('zerver.webhooks.github_webhook.view.check_send_stream_message')
def test_push_multiple_comitters_filtered_by_branches_ignore(
self, check_send_stream_message_mock: MagicMock) -> None:
self.url = self.build_webhook_url(branches='master,development')
payload = self.get_body('push_multiple_committers')
result = self.client_post(self.url, payload, HTTP_X_GITHUB_EVENT='push', content_type="application/json")
self.assertFalse(check_send_stream_message_mock.called)
self.assert_json_success(result)
@patch('zerver.webhooks.github_webhook.view.check_send_stream_message')
def test_push_multiple_comitters_with_others_filtered_by_branches_ignore(
self, check_send_stream_message_mock: MagicMock) -> None:
self.url = self.build_webhook_url(branches='master,development')
payload = self.get_body('push_multiple_committers_with_others')
result = self.client_post(self.url, payload, HTTP_X_GITHUB_EVENT='push', content_type="application/json")
self.assertFalse(check_send_stream_message_mock.called)
self.assert_json_success(result)
| apache-2.0 | 8,828,503,967,933,125,000 | 78.162455 | 387 | 0.727107 | false | 3.066853 | true | false | false |
atztogo/spglib | python/test/test_collinear_spin.py | 1 | 1335 | import unittest
import numpy as np
from spglib import get_symmetry
class TestGetSymmetry(unittest.TestCase):
def setUp(self):
lattice = [[4, 0, 0], [0, 4, 0], [0, 0, 4]]
positions = [[0, 0, 0], [0.5, 0.5, 0.5]]
numbers = [1, 1]
magmoms = [0, 0]
self._cell = (lattice, positions, numbers, magmoms)
def tearDown(self):
pass
def test_get_symmetry_ferro(self):
self._cell[3][0] = 1
self._cell[3][1] = 1
sym = get_symmetry(self._cell)
self.assertEqual(96, len(sym['rotations']))
np.testing.assert_equal(sym['equivalent_atoms'], [0, 0])
def test_get_symmetry_anti_ferro(self):
self._cell[3][0] = 1
self._cell[3][1] = -1
sym = get_symmetry(self._cell)
self.assertEqual(96, len(sym['rotations']))
np.testing.assert_equal(sym['equivalent_atoms'], [0, 0])
def test_get_symmetry_broken_magmoms(self):
self._cell[3][0] = 1
self._cell[3][1] = 2
sym = get_symmetry(self._cell)
self.assertEqual(48, len(sym['rotations']))
np.testing.assert_equal(sym['equivalent_atoms'], [0, 1])
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestGetSymmetry)
unittest.TextTestRunner(verbosity=2).run(suite)
# unittest.main()
| bsd-3-clause | 1,407,334,135,078,816,500 | 30.046512 | 72 | 0.580524 | false | 3.186158 | true | false | false |
aalien/subtitle2spu | parsesrt.py | 1 | 1661 | # Copyright (C) 2008 Antti Laine <[email protected]>
#
# This file is part of subtitle2spu.
#
# subtitle2spu is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# subtitle2spu is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with subtitle2spu. If not, see <http://www.gnu.org/licenses/>.
import sys
# States
READNUMBER = 1
READTIME = 2
READTEXT = 3
def parse( file, writer ):
state = READNUMBER
linecount = 0
lines = ""
for buf in file:
if not buf:
continue
if state == READNUMBER:
number = buf.split()[0]
state = READTIME
continue
if state == READTIME:
starttime = buf.split()[0]
endtime = buf.split()[2]
state = READTEXT
continue
if state == READTEXT:
if buf[0] not in ("\n", "\r"):
linecount += 1
lines += buf
else:
print "Writing subtitle %s" %(number)
if not writer.write( number, starttime, endtime, lines ):
return False
state = READNUMBER
linecount = 0
lines = ""
return True
| mit | 7,590,266,957,127,908,000 | 29.759259 | 73 | 0.584588 | false | 4.081081 | false | false | false |
soscpd/bee | root/tests/zguide/examples/Python/mdcliapi.py | 1 | 3030 | """Majordomo Protocol Client API, Python version.
Implements the MDP/Worker spec at http:#rfc.zeromq.org/spec:7.
Author: Min RK <[email protected]>
Based on Java example by Arkadiusz Orzechowski
"""
import logging
import zmq
import MDP
from zhelpers import dump
class MajorDomoClient(object):
"""Majordomo Protocol Client API, Python version.
Implements the MDP/Worker spec at http:#rfc.zeromq.org/spec:7.
"""
broker = None
ctx = None
client = None
poller = None
timeout = 2500
retries = 3
verbose = False
def __init__(self, broker, verbose=False):
self.broker = broker
self.verbose = verbose
self.ctx = zmq.Context()
self.poller = zmq.Poller()
logging.basicConfig(format="%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S",
level=logging.INFO)
self.reconnect_to_broker()
def reconnect_to_broker(self):
"""Connect or reconnect to broker"""
if self.client:
self.poller.unregister(self.client)
self.client.close()
self.client = self.ctx.socket(zmq.REQ)
self.client.linger = 0
self.client.connect(self.broker)
self.poller.register(self.client, zmq.POLLIN)
if self.verbose:
logging.info("I: connecting to broker at %s...", self.broker)
def send(self, service, request):
"""Send request to broker and get reply by hook or crook.
Takes ownership of request message and destroys it when sent.
Returns the reply message or None if there was no reply.
"""
if not isinstance(request, list):
request = [request]
request = [MDP.C_CLIENT, service] + request
if self.verbose:
logging.warn("I: send request to '%s' service: ", service)
dump(request)
reply = None
retries = self.retries
while retries > 0:
self.client.send_multipart(request)
try:
items = self.poller.poll(self.timeout)
except KeyboardInterrupt:
break # interrupted
if items:
msg = self.client.recv_multipart()
if self.verbose:
logging.info("I: received reply:")
dump(msg)
# Don't try to handle errors, just assert noisily
assert len(msg) >= 3
header = msg.pop(0)
assert MDP.C_CLIENT == header
reply_service = msg.pop(0)
assert service == reply_service
reply = msg
break
else:
if retries:
logging.warn("W: no reply, reconnecting...")
self.reconnect_to_broker()
else:
logging.warn("W: permanent error, abandoning")
break
retries -= 1
return reply
def destroy(self):
self.context.destroy()
| mit | 8,947,509,223,582,141,000 | 28.705882 | 90 | 0.553465 | false | 4.297872 | false | false | false |
scholer/cadnano2.5 | cadnano/strand/modscmd.py | 2 | 1922 | from cadnano.proxies.cnproxy import UndoCommand
from cadnano.cntypes import (
DocT,
StrandT
)
class AddModsCommand(UndoCommand):
def __init__(self, document: DocT, strand: StrandT, idx: int, mod_id: str):
super(AddModsCommand, self).__init__()
self._strand = strand
self._id_num = strand.idNum()
self._idx = idx
self._mod_id = mod_id
self.document = document
# end def
def redo(self):
strand = self._strand
mid = self._mod_id
part = strand.part()
idx = self._idx
part.addModStrandInstance(strand, idx, mid)
strand.strandModsAddedSignal.emit(strand, self.document, mid, idx)
# end def
def undo(self):
strand = self._strand
mid = self._mod_id
part = strand.part()
idx = self._idx
part.removeModStrandInstance(strand, idx, mid)
strand.strandModsRemovedSignal.emit(strand, self.document, mid, idx)
# end def
# end class
class RemoveModsCommand(UndoCommand):
def __init__(self, document, strand, idx, mod_id):
super(RemoveModsCommand, self).__init__()
self._strand = strand
self._id_num = strand.idNum()
self._idx = idx
self._mod_id = mod_id
self.document = document
# end def
def redo(self):
strand = self._strand
strand.isStaple()
mid = self._mod_id
part = strand.part()
idx = self._idx
part.removeModStrandInstance(strand, idx, mid)
strand.strandModsRemovedSignal.emit(strand, self.document, mid, idx)
# end def
def undo(self):
strand = self._strand
strand.isStaple()
mid = self._mod_id
part = strand.part()
idx = self._idx
part.addModStrandInstance(strand, idx, mid)
strand.strandModsAddedSignal.emit(strand, self.document, mid, idx)
# end def
# end class
| mit | 6,883,323,475,434,581,000 | 28.121212 | 79 | 0.596254 | false | 3.469314 | false | false | false |
jorgenkg/python-neural-network | nimblenet/cost_functions.py | 1 | 1632 | import numpy as np
import math
def sum_squared_error( outputs, targets, derivative=False ):
if derivative:
return outputs - targets
else:
return 0.5 * np.mean(np.sum( np.power(outputs - targets,2), axis = 1 ))
#end cost function
def hellinger_distance( outputs, targets, derivative=False ):
"""
The output signals should be in the range [0, 1]
"""
root_difference = np.sqrt( outputs ) - np.sqrt( targets )
if derivative:
return root_difference/( np.sqrt(2) * np.sqrt( outputs ))
else:
return np.mean(np.sum( np.power(root_difference, 2 ), axis=1) / math.sqrt( 2 ))
#end cost function
def binary_cross_entropy_cost( outputs, targets, derivative=False, epsilon=1e-11 ):
"""
The output signals should be in the range [0, 1]
"""
# Prevent overflow
outputs = np.clip(outputs, epsilon, 1 - epsilon)
divisor = np.maximum(outputs * (1 - outputs), epsilon)
if derivative:
return (outputs - targets) / divisor
else:
return np.mean(-np.sum(targets * np.log( outputs ) + (1 - targets) * np.log(1 - outputs), axis=1))
#end cost function
cross_entropy_cost = binary_cross_entropy_cost
def softmax_categorical_cross_entropy_cost( outputs, targets, derivative=False, epsilon=1e-11 ):
"""
The output signals should be in the range [0, 1]
"""
outputs = np.clip(outputs, epsilon, 1 - epsilon)
if derivative:
return outputs - targets
else:
return np.mean(-np.sum(targets * np.log( outputs ), axis=1))
#end cost function
softmax_neg_loss = softmax_categorical_cross_entropy_cost | bsd-2-clause | -7,239,579,203,085,241,000 | 30.403846 | 106 | 0.645221 | false | 3.602649 | false | false | false |
googleapis/googleapis-gen | google/ads/googleads/v7/googleads-py/google/ads/googleads/v7/enums/types/negative_geo_target_type.py | 1 | 1192 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package='google.ads.googleads.v7.enums',
marshal='google.ads.googleads.v7',
manifest={
'NegativeGeoTargetTypeEnum',
},
)
class NegativeGeoTargetTypeEnum(proto.Message):
r"""Container for enum describing possible negative geo target
types.
"""
class NegativeGeoTargetType(proto.Enum):
r"""The possible negative geo target types."""
UNSPECIFIED = 0
UNKNOWN = 1
PRESENCE_OR_INTEREST = 4
PRESENCE = 5
__all__ = tuple(sorted(__protobuf__.manifest))
| apache-2.0 | -6,885,534,629,699,815,000 | 28.8 | 74 | 0.692953 | false | 4 | false | false | false |
mvaled/sentry | src/sentry/south_migrations/0326_auto__add_field_groupsnooze_count__add_field_groupsnooze_window__add_f.py | 1 | 116733 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'GroupSnooze.count'
db.add_column(
'sentry_groupsnooze',
'count',
self.gf('sentry.db.models.fields.bounded.BoundedPositiveIntegerField')(null=True),
keep_default=False
)
# Adding field 'GroupSnooze.window'
db.add_column(
'sentry_groupsnooze',
'window',
self.gf('sentry.db.models.fields.bounded.BoundedPositiveIntegerField')(null=True),
keep_default=False
)
# Adding field 'GroupSnooze.user_count'
db.add_column(
'sentry_groupsnooze',
'user_count',
self.gf('sentry.db.models.fields.bounded.BoundedPositiveIntegerField')(null=True),
keep_default=False
)
# Adding field 'GroupSnooze.user_window'
db.add_column(
'sentry_groupsnooze',
'user_window',
self.gf('sentry.db.models.fields.bounded.BoundedPositiveIntegerField')(null=True),
keep_default=False
)
# Adding field 'GroupSnooze.state'
db.add_column(
'sentry_groupsnooze',
'state',
self.gf('sentry.db.models.fields.jsonfield.JSONField')(null=True),
keep_default=False
)
# Changing field 'GroupSnooze.until'
db.alter_column(
'sentry_groupsnooze',
'until',
self.gf('django.db.models.fields.DateTimeField')(null=True)
)
def backwards(self, orm):
raise RuntimeError(
"Cannot reverse this migration. 'GroupSnooze.until' and its values cannot be restored."
)
models = {
'sentry.activity': {
'Meta': {
'object_name': 'Activity'
},
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {
'null': 'True'
}),
'datetime':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']",
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']",
'null': 'True'
}
)
},
'sentry.apiapplication': {
'Meta': {
'object_name': 'ApiApplication'
},
'allowed_origins':
('django.db.models.fields.TextField', [], {
'null': 'True',
'blank': 'True'
}),
'client_id': (
'django.db.models.fields.CharField', [], {
'default': "'1fe2246606cd41688e14b95ae1bdc14c6b7652dea035446fa2dc8bcacf21afd6'",
'unique': 'True',
'max_length': '64'
}
),
'client_secret': (
'sentry.db.models.fields.encrypted.EncryptedTextField', [], {
'default': "'7f918820281a421d991389c5fad78a41551739601ae745e8a24e9cb56ee8ffaa'"
}
),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'homepage_url':
('django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': (
'django.db.models.fields.CharField', [], {
'default': "'Trusting Weasel'",
'max_length': '64',
'blank': 'True'
}
),
'owner': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
),
'privacy_url':
('django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True'
}),
'redirect_uris': ('django.db.models.fields.TextField', [], {}),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
),
'terms_url':
('django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True'
})
},
'sentry.apiauthorization': {
'Meta': {
'unique_together': "(('user', 'application'),)",
'object_name': 'ApiAuthorization'
},
'application': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ApiApplication']",
'null': 'True'
}
),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'scope_list': (
'sentry.db.models.fields.array.ArrayField', [], {
'of': ('django.db.models.fields.TextField', [], {})
}
),
'scopes': ('django.db.models.fields.BigIntegerField', [], {
'default': 'None'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.apigrant': {
'Meta': {
'object_name': 'ApiGrant'
},
'application': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ApiApplication']"
}
),
'code': (
'django.db.models.fields.CharField', [], {
'default': "'d959d133f88c4292a581081e6190b949'",
'max_length': '64',
'db_index': 'True'
}
),
'expires_at': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime(2017, 6, 1, 0, 0)',
'db_index': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'redirect_uri': ('django.db.models.fields.CharField', [], {
'max_length': '255'
}),
'scope_list': (
'sentry.db.models.fields.array.ArrayField', [], {
'of': ('django.db.models.fields.TextField', [], {})
}
),
'scopes': ('django.db.models.fields.BigIntegerField', [], {
'default': 'None'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.apikey': {
'Meta': {
'object_name': 'ApiKey'
},
'allowed_origins':
('django.db.models.fields.TextField', [], {
'null': 'True',
'blank': 'True'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '32'
}),
'label': (
'django.db.models.fields.CharField', [], {
'default': "'Default'",
'max_length': '64',
'blank': 'True'
}
),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'key_set'",
'to': "orm['sentry.Organization']"
}
),
'scope_list': (
'sentry.db.models.fields.array.ArrayField', [], {
'of': ('django.db.models.fields.TextField', [], {})
}
),
'scopes': ('django.db.models.fields.BigIntegerField', [], {
'default': 'None'
}),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
)
},
'sentry.apitoken': {
'Meta': {
'object_name': 'ApiToken'
},
'application': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ApiApplication']",
'null': 'True'
}
),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'expires_at': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime(2017, 7, 1, 0, 0)',
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'refresh_token': (
'django.db.models.fields.CharField', [], {
'default': "'6c4fadd19de34e39ac0859f3f896065cd8c3cd19c56c453287ab9f199c539138'",
'max_length': '64',
'unique': 'True',
'null': 'True'
}
),
'scope_list': (
'sentry.db.models.fields.array.ArrayField', [], {
'of': ('django.db.models.fields.TextField', [], {})
}
),
'scopes': ('django.db.models.fields.BigIntegerField', [], {
'default': 'None'
}),
'token': (
'django.db.models.fields.CharField', [], {
'default': "'94b568466766407cad05e6e2a630f6561a04ecb269c047c381f78c857d84422a'",
'unique': 'True',
'max_length': '64'
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.auditlogentry': {
'Meta': {
'object_name': 'AuditLogEntry'
},
'actor': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'blank': 'True',
'related_name': "'audit_actors'",
'null': 'True',
'to': "orm['sentry.User']"
}
),
'actor_key': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ApiKey']",
'null': 'True',
'blank': 'True'
}
),
'actor_label': (
'django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True',
'blank': 'True'
}
),
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}),
'datetime':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'event': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ip_address': (
'django.db.models.fields.GenericIPAddressField', [], {
'max_length': '39',
'null': 'True'
}
),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'target_object':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'target_user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'blank': 'True',
'related_name': "'audit_targets'",
'null': 'True',
'to': "orm['sentry.User']"
}
)
},
'sentry.authenticator': {
'Meta': {
'unique_together': "(('user', 'type'),)",
'object_name': 'Authenticator',
'db_table': "'auth_authenticator'"
},
'config': ('sentry.db.models.fields.encrypted.EncryptedPickledObjectField', [], {}),
'created_at':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {
'primary_key': 'True'
}),
'last_used_at': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.authidentity': {
'Meta': {
'unique_together': "(('auth_provider', 'ident'), ('auth_provider', 'user'))",
'object_name': 'AuthIdentity'
},
'auth_provider': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.AuthProvider']"
}
),
'data': ('sentry.db.models.fields.encrypted.EncryptedJsonField', [], {
'default': '{}'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'last_synced':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'last_verified':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.authprovider': {
'Meta': {
'object_name': 'AuthProvider'
},
'config':
('sentry.db.models.fields.encrypted.EncryptedJsonField', [], {
'default': '{}'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'default_global_access':
('django.db.models.fields.BooleanField', [], {
'default': 'True'
}),
'default_role':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '50'
}),
'default_teams': (
'django.db.models.fields.related.ManyToManyField', [], {
'to': "orm['sentry.Team']",
'symmetrical': 'False',
'blank': 'True'
}
),
'flags': ('django.db.models.fields.BigIntegerField', [], {
'default': '0'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_sync': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']",
'unique': 'True'
}
),
'provider': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'sync_time':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
})
},
'sentry.broadcast': {
'Meta': {
'object_name': 'Broadcast'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'date_expires': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime(2017, 6, 8, 0, 0)',
'null': 'True',
'blank': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'is_active':
('django.db.models.fields.BooleanField', [], {
'default': 'True',
'db_index': 'True'
}),
'link': (
'django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True',
'blank': 'True'
}
),
'message': ('django.db.models.fields.CharField', [], {
'max_length': '256'
}),
'title': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'upstream_id': (
'django.db.models.fields.CharField', [], {
'max_length': '32',
'null': 'True',
'blank': 'True'
}
)
},
'sentry.broadcastseen': {
'Meta': {
'unique_together': "(('broadcast', 'user'),)",
'object_name': 'BroadcastSeen'
},
'broadcast': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Broadcast']"
}
),
'date_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.commit': {
'Meta': {
'unique_together': "(('repository_id', 'key'),)",
'object_name': 'Commit',
'index_together': "(('repository_id', 'date_added'),)"
},
'author': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.CommitAuthor']",
'null': 'True'
}
),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'message': ('django.db.models.fields.TextField', [], {
'null': 'True'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'repository_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {})
},
'sentry.commitauthor': {
'Meta': {
'unique_together':
"(('organization_id', 'email'), ('organization_id', 'external_id'))",
'object_name':
'CommitAuthor'
},
'email': ('django.db.models.fields.EmailField', [], {
'max_length': '75'
}),
'external_id':
('django.db.models.fields.CharField', [], {
'max_length': '164',
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name':
('django.db.models.fields.CharField', [], {
'max_length': '128',
'null': 'True'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
)
},
'sentry.commitfilechange': {
'Meta': {
'unique_together': "(('commit', 'filename'),)",
'object_name': 'CommitFileChange'
},
'commit': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Commit']"
}
),
'filename': ('django.db.models.fields.CharField', [], {
'max_length': '255'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'type': ('django.db.models.fields.CharField', [], {
'max_length': '1'
})
},
'sentry.counter': {
'Meta': {
'object_name': 'Counter',
'db_table': "'sentry_projectcounter'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'unique': 'True'
}
),
'value': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.deploy': {
'Meta': {
'object_name': 'Deploy'
},
'date_finished':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'date_started':
('django.db.models.fields.DateTimeField', [], {
'null': 'True',
'blank': 'True'
}),
'environment_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': (
'django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True',
'blank': 'True'
}
),
'notified': (
'django.db.models.fields.NullBooleanField', [], {
'default': 'False',
'null': 'True',
'db_index': 'True',
'blank': 'True'
}
),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
),
'url': (
'django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True',
'blank': 'True'
}
)
},
'sentry.distribution': {
'Meta': {
'unique_together': "(('release', 'name'),)",
'object_name': 'Distribution'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
)
},
'sentry.dsymapp': {
'Meta': {
'unique_together': "(('project', 'platform', 'app_id'),)",
'object_name': 'DSymApp'
},
'app_id': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'data': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_synced':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'platform':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'sync_id':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
})
},
'sentry.dsymbundle': {
'Meta': {
'object_name': 'DSymBundle'
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.DSymObject']"
}
),
'sdk': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.DSymSDK']"
}
)
},
'sentry.dsymobject': {
'Meta': {
'object_name': 'DSymObject'
},
'cpu_name': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object_path': ('django.db.models.fields.TextField', [], {
'db_index': 'True'
}),
'uuid':
('django.db.models.fields.CharField', [], {
'max_length': '36',
'db_index': 'True'
}),
'vmaddr':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
}),
'vmsize':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
})
},
'sentry.dsymsdk': {
'Meta': {
'object_name':
'DSymSDK',
'index_together':
"[('version_major', 'version_minor', 'version_patchlevel', 'version_build')]"
},
'dsym_type':
('django.db.models.fields.CharField', [], {
'max_length': '20',
'db_index': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'sdk_name': ('django.db.models.fields.CharField', [], {
'max_length': '20'
}),
'version_build': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'version_major': ('django.db.models.fields.IntegerField', [], {}),
'version_minor': ('django.db.models.fields.IntegerField', [], {}),
'version_patchlevel': ('django.db.models.fields.IntegerField', [], {})
},
'sentry.dsymsymbol': {
'Meta': {
'unique_together': "[('object', 'address')]",
'object_name': 'DSymSymbol'
},
'address':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'db_index': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.DSymObject']"
}
),
'symbol': ('django.db.models.fields.TextField', [], {})
},
'sentry.environment': {
'Meta': {
'unique_together': "(('project_id', 'name'), ('organization_id', 'name'))",
'object_name': 'Environment'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'organization_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'project_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'projects': (
'django.db.models.fields.related.ManyToManyField', [], {
'to': "orm['sentry.Project']",
'through': "orm['sentry.EnvironmentProject']",
'symmetrical': 'False'
}
)
},
'sentry.environmentproject': {
'Meta': {
'unique_together': "(('project', 'environment'),)",
'object_name': 'EnvironmentProject'
},
'environment': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Environment']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
)
},
'sentry.event': {
'Meta': {
'unique_together': "(('project_id', 'event_id'),)",
'object_name': 'Event',
'db_table': "'sentry_message'",
'index_together': "(('group_id', 'datetime'),)"
},
'data':
('sentry.db.models.fields.node.NodeField', [], {
'null': 'True',
'blank': 'True'
}),
'datetime': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'event_id': (
'django.db.models.fields.CharField', [], {
'max_length': '32',
'null': 'True',
'db_column': "'message_id'"
}
),
'group_id': (
'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True',
'blank': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'message': ('django.db.models.fields.TextField', [], {}),
'platform':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'project_id': (
'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True',
'blank': 'True'
}
),
'time_spent':
('sentry.db.models.fields.bounded.BoundedIntegerField', [], {
'null': 'True'
})
},
'sentry.eventmapping': {
'Meta': {
'unique_together': "(('project_id', 'event_id'),)",
'object_name': 'EventMapping'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'event_id': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'group_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.eventprocessingissue': {
'Meta': {
'unique_together': "(('raw_event', 'processing_issue'),)",
'object_name': 'EventProcessingIssue'
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'processing_issue': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ProcessingIssue']"
}
),
'raw_event': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.RawEvent']"
}
)
},
'sentry.eventtag': {
'Meta': {
'unique_together':
"(('event_id', 'key_id', 'value_id'),)",
'object_name':
'EventTag',
'index_together':
"(('project_id', 'key_id', 'value_id'), ('group_id', 'key_id', 'value_id'))"
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'event_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'group_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {}),
'value_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.eventuser': {
'Meta': {
'unique_together':
"(('project', 'ident'), ('project', 'hash'))",
'object_name':
'EventUser',
'index_together':
"(('project', 'email'), ('project', 'username'), ('project', 'ip_address'))"
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'email':
('django.db.models.fields.EmailField', [], {
'max_length': '75',
'null': 'True'
}),
'hash': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident':
('django.db.models.fields.CharField', [], {
'max_length': '128',
'null': 'True'
}),
'ip_address': (
'django.db.models.fields.GenericIPAddressField', [], {
'max_length': '39',
'null': 'True'
}
),
'name':
('django.db.models.fields.CharField', [], {
'max_length': '128',
'null': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'username':
('django.db.models.fields.CharField', [], {
'max_length': '128',
'null': 'True'
})
},
'sentry.file': {
'Meta': {
'object_name': 'File'
},
'blob': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'legacy_blob'",
'null': 'True',
'to': "orm['sentry.FileBlob']"
}
),
'blobs': (
'django.db.models.fields.related.ManyToManyField', [], {
'to': "orm['sentry.FileBlob']",
'through': "orm['sentry.FileBlobIndex']",
'symmetrical': 'False'
}
),
'checksum':
('django.db.models.fields.CharField', [], {
'max_length': '40',
'null': 'True'
}),
'headers': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'path': ('django.db.models.fields.TextField', [], {
'null': 'True'
}),
'size':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'timestamp': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'type': ('django.db.models.fields.CharField', [], {
'max_length': '64'
})
},
'sentry.fileblob': {
'Meta': {
'object_name': 'FileBlob'
},
'checksum':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '40'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'path': ('django.db.models.fields.TextField', [], {
'null': 'True'
}),
'size':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'timestamp': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
)
},
'sentry.fileblobindex': {
'Meta': {
'unique_together': "(('file', 'blob', 'offset'),)",
'object_name': 'FileBlobIndex'
},
'blob': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.FileBlob']"
}
),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'offset': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {})
},
'sentry.globaldsymfile': {
'Meta': {
'object_name': 'GlobalDSymFile'
},
'cpu_name': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object_name': ('django.db.models.fields.TextField', [], {}),
'uuid':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '36'
})
},
'sentry.group': {
'Meta': {
'unique_together': "(('project', 'short_id'),)",
'object_name': 'Group',
'db_table': "'sentry_groupedmessage'",
'index_together': "(('project', 'first_release'),)"
},
'active_at':
('django.db.models.fields.DateTimeField', [], {
'null': 'True',
'db_index': 'True'
}),
'culprit': (
'django.db.models.fields.CharField', [], {
'max_length': '200',
'null': 'True',
'db_column': "'view'",
'blank': 'True'
}
),
'data': (
'sentry.db.models.fields.gzippeddict.GzippedDictField', [], {
'null': 'True',
'blank': 'True'
}
),
'first_release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']",
'null': 'True',
'on_delete': 'models.PROTECT'
}
),
'first_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'is_public': (
'django.db.models.fields.NullBooleanField', [], {
'default': 'False',
'null': 'True',
'blank': 'True'
}
),
'last_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'level': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '40',
'db_index': 'True',
'blank': 'True'
}
),
'logger': (
'django.db.models.fields.CharField', [], {
'default': "''",
'max_length': '64',
'db_index': 'True',
'blank': 'True'
}
),
'message': ('django.db.models.fields.TextField', [], {}),
'num_comments': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'null': 'True'
}
),
'platform':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
),
'resolved_at':
('django.db.models.fields.DateTimeField', [], {
'null': 'True',
'db_index': 'True'
}),
'score': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], {
'default': '0'
}),
'short_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
}),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
),
'time_spent_count':
('sentry.db.models.fields.bounded.BoundedIntegerField', [], {
'default': '0'
}),
'time_spent_total':
('sentry.db.models.fields.bounded.BoundedIntegerField', [], {
'default': '0'
}),
'times_seen': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '1',
'db_index': 'True'
}
)
},
'sentry.groupassignee': {
'Meta': {
'object_name': 'GroupAssignee',
'db_table': "'sentry_groupasignee'"
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'assignee_set'",
'unique': 'True',
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'assignee_set'",
'to': "orm['sentry.Project']"
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'sentry_assignee_set'",
'to': "orm['sentry.User']"
}
)
},
'sentry.groupbookmark': {
'Meta': {
'unique_together': "(('project', 'user', 'group'),)",
'object_name': 'GroupBookmark'
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True'
}
),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'bookmark_set'",
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'bookmark_set'",
'to': "orm['sentry.Project']"
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'sentry_bookmark_set'",
'to': "orm['sentry.User']"
}
)
},
'sentry.groupcommitresolution': {
'Meta': {
'unique_together': "(('group_id', 'commit_id'),)",
'object_name': 'GroupCommitResolution'
},
'commit_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'datetime': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'group_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
})
},
'sentry.groupemailthread': {
'Meta': {
'unique_together': "(('email', 'group'), ('email', 'msgid'))",
'object_name': 'GroupEmailThread'
},
'date': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'email': ('django.db.models.fields.EmailField', [], {
'max_length': '75'
}),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'groupemail_set'",
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'msgid': ('django.db.models.fields.CharField', [], {
'max_length': '100'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'groupemail_set'",
'to': "orm['sentry.Project']"
}
)
},
'sentry.grouphash': {
'Meta': {
'unique_together': "(('project', 'hash'),)",
'object_name': 'GroupHash'
},
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']",
'null': 'True'
}
),
'hash': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
)
},
'sentry.groupmeta': {
'Meta': {
'unique_together': "(('group', 'key'),)",
'object_name': 'GroupMeta'
},
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'value': ('django.db.models.fields.TextField', [], {})
},
'sentry.groupredirect': {
'Meta': {
'object_name': 'GroupRedirect'
},
'group_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'db_index': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'previous_group_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'unique': 'True'
})
},
'sentry.grouprelease': {
'Meta': {
'unique_together': "(('group_id', 'release_id', 'environment'),)",
'object_name': 'GroupRelease'
},
'environment':
('django.db.models.fields.CharField', [], {
'default': "''",
'max_length': '64'
}),
'first_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'group_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'project_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'release_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
)
},
'sentry.groupresolution': {
'Meta': {
'object_name': 'GroupResolution'
},
'datetime': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']",
'unique': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
),
'status':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
})
},
'sentry.grouprulestatus': {
'Meta': {
'unique_together': "(('rule', 'group'),)",
'object_name': 'GroupRuleStatus'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_active': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'rule': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Rule']"
}
),
'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {
'default': '0'
})
},
'sentry.groupseen': {
'Meta': {
'unique_together': "(('user', 'group'),)",
'object_name': 'GroupSeen'
},
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']",
'db_index': 'False'
}
)
},
'sentry.groupsnooze': {
'Meta': {
'object_name': 'GroupSnooze'
},
'count':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']",
'unique': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'state': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'null': 'True'
}),
'until': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'user_count':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'user_window':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'window':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
})
},
'sentry.groupsubscription': {
'Meta': {
'unique_together': "(('group', 'user'),)",
'object_name': 'GroupSubscription'
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True'
}
),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'subscription_set'",
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'is_active': ('django.db.models.fields.BooleanField', [], {
'default': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'subscription_set'",
'to': "orm['sentry.Project']"
}
),
'reason':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.grouptagkey': {
'Meta': {
'unique_together': "(('project', 'group', 'key'),)",
'object_name': 'GroupTagKey'
},
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
),
'values_seen':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
})
},
'sentry.grouptagvalue': {
'Meta': {
'unique_together': "(('group_id', 'key', 'value'),)",
'object_name': 'GroupTagValue',
'db_table': "'sentry_messagefiltervalue'",
'index_together': "(('project_id', 'key', 'value', 'last_seen'),)"
},
'first_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True',
'db_index': 'True'
}
),
'group_id': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'last_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True',
'db_index': 'True'
}
),
'project_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'times_seen':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'value': ('django.db.models.fields.CharField', [], {
'max_length': '200'
})
},
'sentry.lostpasswordhash': {
'Meta': {
'object_name': 'LostPasswordHash'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'hash': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']",
'unique': 'True'
}
)
},
'sentry.option': {
'Meta': {
'object_name': 'Option'
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '64'
}),
'last_updated':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'value': ('sentry.db.models.fields.encrypted.EncryptedPickledObjectField', [], {})
},
'sentry.organization': {
'Meta': {
'object_name': 'Organization'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'default_role':
('django.db.models.fields.CharField', [], {
'default': "'member'",
'max_length': '32'
}),
'flags': ('django.db.models.fields.BigIntegerField', [], {
'default': '1'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'members': (
'django.db.models.fields.related.ManyToManyField', [], {
'related_name': "'org_memberships'",
'symmetrical': 'False',
'through': "orm['sentry.OrganizationMember']",
'to': "orm['sentry.User']"
}
),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'slug':
('django.db.models.fields.SlugField', [], {
'unique': 'True',
'max_length': '50'
}),
'status':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
})
},
'sentry.organizationaccessrequest': {
'Meta': {
'unique_together': "(('team', 'member'),)",
'object_name': 'OrganizationAccessRequest'
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'member': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.OrganizationMember']"
}
),
'team': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Team']"
}
)
},
'sentry.organizationavatar': {
'Meta': {
'object_name': 'OrganizationAvatar'
},
'avatar_type':
('django.db.models.fields.PositiveSmallIntegerField', [], {
'default': '0'
}),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']",
'unique': 'True',
'null': 'True',
'on_delete': 'models.SET_NULL'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident': (
'django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '32',
'db_index': 'True'
}
),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'avatar'",
'unique': 'True',
'to': "orm['sentry.Organization']"
}
)
},
'sentry.organizationmember': {
'Meta': {
'unique_together': "(('organization', 'user'), ('organization', 'email'))",
'object_name': 'OrganizationMember'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'email': (
'django.db.models.fields.EmailField', [], {
'max_length': '75',
'null': 'True',
'blank': 'True'
}
),
'flags': ('django.db.models.fields.BigIntegerField', [], {
'default': '0'
}),
'has_global_access': ('django.db.models.fields.BooleanField', [], {
'default': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'member_set'",
'to': "orm['sentry.Organization']"
}
),
'role':
('django.db.models.fields.CharField', [], {
'default': "'member'",
'max_length': '32'
}),
'teams': (
'django.db.models.fields.related.ManyToManyField', [], {
'to': "orm['sentry.Team']",
'symmetrical': 'False',
'through': "orm['sentry.OrganizationMemberTeam']",
'blank': 'True'
}
),
'token': (
'django.db.models.fields.CharField', [], {
'max_length': '64',
'unique': 'True',
'null': 'True',
'blank': 'True'
}
),
'type': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '50',
'blank': 'True'
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'blank': 'True',
'related_name': "'sentry_orgmember_set'",
'null': 'True',
'to': "orm['sentry.User']"
}
)
},
'sentry.organizationmemberteam': {
'Meta': {
'unique_together': "(('team', 'organizationmember'),)",
'object_name': 'OrganizationMemberTeam',
'db_table': "'sentry_organizationmember_teams'"
},
'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {
'primary_key': 'True'
}),
'is_active': ('django.db.models.fields.BooleanField', [], {
'default': 'True'
}),
'organizationmember': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.OrganizationMember']"
}
),
'team': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Team']"
}
)
},
'sentry.organizationonboardingtask': {
'Meta': {
'unique_together': "(('organization', 'task'),)",
'object_name': 'OrganizationOnboardingTask'
},
'data': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'date_completed':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'project_id': (
'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True',
'blank': 'True'
}
),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'task': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']",
'null': 'True'
}
)
},
'sentry.organizationoption': {
'Meta': {
'unique_together': "(('organization', 'key'),)",
'object_name': 'OrganizationOption',
'db_table': "'sentry_organizationoptions'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'value': ('sentry.db.models.fields.encrypted.EncryptedPickledObjectField', [], {})
},
'sentry.processingissue': {
'Meta': {
'unique_together': "(('project', 'checksum', 'type'),)",
'object_name': 'ProcessingIssue'
},
'checksum':
('django.db.models.fields.CharField', [], {
'max_length': '40',
'db_index': 'True'
}),
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}),
'datetime':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'type': ('django.db.models.fields.CharField', [], {
'max_length': '30'
})
},
'sentry.project': {
'Meta': {
'unique_together': "(('team', 'slug'), ('organization', 'slug'))",
'object_name': 'Project'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'first_event': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'flags':
('django.db.models.fields.BigIntegerField', [], {
'default': '0',
'null': 'True'
}),
'forced_color': (
'django.db.models.fields.CharField', [], {
'max_length': '6',
'null': 'True',
'blank': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '200'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'public': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'slug': ('django.db.models.fields.SlugField', [], {
'max_length': '50',
'null': 'True'
}),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
),
'team': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Team']"
}
)
},
'sentry.projectbookmark': {
'Meta': {
'unique_together': "(('project_id', 'user'),)",
'object_name': 'ProjectBookmark'
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project_id': (
'sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True',
'blank': 'True'
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.projectdsymfile': {
'Meta': {
'unique_together': "(('project', 'uuid'),)",
'object_name': 'ProjectDSymFile'
},
'cpu_name': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'object_name': ('django.db.models.fields.TextField', [], {}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
),
'uuid': ('django.db.models.fields.CharField', [], {
'max_length': '36'
})
},
'sentry.projectkey': {
'Meta': {
'object_name': 'ProjectKey'
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'label': (
'django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True',
'blank': 'True'
}
),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'key_set'",
'to': "orm['sentry.Project']"
}
),
'public_key': (
'django.db.models.fields.CharField', [], {
'max_length': '32',
'unique': 'True',
'null': 'True'
}
),
'rate_limit_count':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'rate_limit_window':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'roles': ('django.db.models.fields.BigIntegerField', [], {
'default': '1'
}),
'secret_key': (
'django.db.models.fields.CharField', [], {
'max_length': '32',
'unique': 'True',
'null': 'True'
}
),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
)
},
'sentry.projectoption': {
'Meta': {
'unique_together': "(('project', 'key'),)",
'object_name': 'ProjectOption',
'db_table': "'sentry_projectoptions'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'value': ('sentry.db.models.fields.encrypted.EncryptedPickledObjectField', [], {})
},
'sentry.projectplatform': {
'Meta': {
'unique_together': "(('project_id', 'platform'),)",
'object_name': 'ProjectPlatform'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'platform': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'project_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.rawevent': {
'Meta': {
'unique_together': "(('project', 'event_id'),)",
'object_name': 'RawEvent'
},
'data':
('sentry.db.models.fields.node.NodeField', [], {
'null': 'True',
'blank': 'True'
}),
'datetime':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'event_id':
('django.db.models.fields.CharField', [], {
'max_length': '32',
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
)
},
'sentry.release': {
'Meta': {
'unique_together': "(('organization', 'version'),)",
'object_name': 'Release'
},
'data': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'date_released':
('django.db.models.fields.DateTimeField', [], {
'null': 'True',
'blank': 'True'
}),
'date_started':
('django.db.models.fields.DateTimeField', [], {
'null': 'True',
'blank': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'new_groups':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'owner': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']",
'null': 'True',
'blank': 'True'
}
),
'project_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'projects': (
'django.db.models.fields.related.ManyToManyField', [], {
'related_name': "'releases'",
'symmetrical': 'False',
'through': "orm['sentry.ReleaseProject']",
'to': "orm['sentry.Project']"
}
),
'ref': (
'django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True',
'blank': 'True'
}
),
'url': (
'django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True',
'blank': 'True'
}
),
'version': ('django.db.models.fields.CharField', [], {
'max_length': '64'
})
},
'sentry.releasecommit': {
'Meta': {
'unique_together': "(('release', 'commit'), ('release', 'order'))",
'object_name': 'ReleaseCommit'
},
'commit': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Commit']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'order': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'project_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True',
'db_index': 'True'
}
),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
)
},
'sentry.releaseenvironment': {
'Meta': {
'unique_together':
"(('project_id', 'release_id', 'environment_id'), ('organization_id', 'release_id', 'environment_id'))",
'object_name':
'ReleaseEnvironment',
'db_table':
"'sentry_environmentrelease'"
},
'environment_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'first_seen':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'last_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'db_index': 'True'
}
),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'project_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True',
'db_index': 'True'
}
),
'release_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
)
},
'sentry.releasefile': {
'Meta': {
'unique_together': "(('release', 'ident'),)",
'object_name': 'ReleaseFile'
},
'dist': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Distribution']",
'null': 'True'
}
),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident': ('django.db.models.fields.CharField', [], {
'max_length': '40'
}),
'name': ('django.db.models.fields.TextField', [], {}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'project_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'null': 'True'
}),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
)
},
'sentry.releaseheadcommit': {
'Meta': {
'unique_together': "(('repository_id', 'release'),)",
'object_name': 'ReleaseHeadCommit'
},
'commit': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Commit']"
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
),
'repository_id':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {})
},
'sentry.releaseproject': {
'Meta': {
'unique_together': "(('project', 'release'),)",
'object_name': 'ReleaseProject',
'db_table': "'sentry_release_project'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'new_groups': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'null': 'True'
}
),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'release': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Release']"
}
)
},
'sentry.repository': {
'Meta': {
'unique_together':
"(('organization_id', 'name'), ('organization_id', 'provider', 'external_id'))",
'object_name':
'Repository'
},
'config': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'external_id':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '200'
}),
'organization_id': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'db_index': 'True'
}
),
'provider':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
),
'url': ('django.db.models.fields.URLField', [], {
'max_length': '200',
'null': 'True'
})
},
'sentry.reprocessingreport': {
'Meta': {
'unique_together': "(('project', 'event_id'),)",
'object_name': 'ReprocessingReport'
},
'datetime':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'event_id':
('django.db.models.fields.CharField', [], {
'max_length': '32',
'null': 'True'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
)
},
'sentry.rule': {
'Meta': {
'object_name': 'Rule'
},
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'label': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'status': (
'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0',
'db_index': 'True'
}
)
},
'sentry.savedsearch': {
'Meta': {
'unique_together': "(('project', 'name'),)",
'object_name': 'SavedSearch'
},
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'is_default': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'owner': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']",
'null': 'True'
}
),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'query': ('django.db.models.fields.TextField', [], {})
},
'sentry.savedsearchuserdefault': {
'Meta': {
'unique_together': "(('project', 'user'),)",
'object_name': 'SavedSearchUserDefault',
'db_table': "'sentry_savedsearch_userdefault'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'savedsearch': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.SavedSearch']"
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
)
},
'sentry.scheduleddeletion': {
'Meta': {
'unique_together': "(('app_label', 'model_name', 'object_id'),)",
'object_name': 'ScheduledDeletion'
},
'aborted': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'actor_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
}),
'app_label': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'data': ('sentry.db.models.fields.jsonfield.JSONField', [], {
'default': '{}'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'date_scheduled': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime(2017, 7, 1, 0, 0)'
}
),
'guid': (
'django.db.models.fields.CharField', [], {
'default': "'7dcd5c1ace824812b6cc232360d975f7'",
'unique': 'True',
'max_length': '32'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'in_progress': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'model_name': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'object_id': ('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {})
},
'sentry.tagkey': {
'Meta': {
'unique_together': "(('project', 'key'),)",
'object_name': 'TagKey',
'db_table': "'sentry_filterkey'"
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'label':
('django.db.models.fields.CharField', [], {
'max_length': '64',
'null': 'True'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
),
'status':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'values_seen':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
})
},
'sentry.tagvalue': {
'Meta': {
'unique_together': "(('project', 'key', 'value'),)",
'object_name': 'TagValue',
'db_table': "'sentry_filtervalue'"
},
'data': (
'sentry.db.models.fields.gzippeddict.GzippedDictField', [], {
'null': 'True',
'blank': 'True'
}
),
'first_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True',
'db_index': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'last_seen': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True',
'db_index': 'True'
}
),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
),
'times_seen':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
}),
'value': ('django.db.models.fields.CharField', [], {
'max_length': '200'
})
},
'sentry.team': {
'Meta': {
'unique_together': "(('organization', 'slug'),)",
'object_name': 'Team'
},
'date_added': (
'django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now',
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']"
}
),
'slug': ('django.db.models.fields.SlugField', [], {
'max_length': '50'
}),
'status':
('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {
'default': '0'
})
},
'sentry.user': {
'Meta': {
'object_name': 'User',
'db_table': "'auth_user'"
},
'date_joined':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'email':
('django.db.models.fields.EmailField', [], {
'max_length': '75',
'blank': 'True'
}),
'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], {
'primary_key': 'True'
}),
'is_active': ('django.db.models.fields.BooleanField', [], {
'default': 'True'
}),
'is_managed': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'is_password_expired':
('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'is_staff': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'last_login':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'last_password_change': ('django.db.models.fields.DateTimeField', [], {
'null': 'True'
}),
'name': (
'django.db.models.fields.CharField', [], {
'max_length': '200',
'db_column': "'first_name'",
'blank': 'True'
}
),
'password': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'session_nonce':
('django.db.models.fields.CharField', [], {
'max_length': '12',
'null': 'True'
}),
'username':
('django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '128'
})
},
'sentry.useravatar': {
'Meta': {
'object_name': 'UserAvatar'
},
'avatar_type':
('django.db.models.fields.PositiveSmallIntegerField', [], {
'default': '0'
}),
'file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.File']",
'unique': 'True',
'null': 'True',
'on_delete': 'models.SET_NULL'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'ident': (
'django.db.models.fields.CharField', [], {
'unique': 'True',
'max_length': '32',
'db_index': 'True'
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'avatar'",
'unique': 'True',
'to': "orm['sentry.User']"
}
)
},
'sentry.useremail': {
'Meta': {
'unique_together': "(('user', 'email'),)",
'object_name': 'UserEmail'
},
'date_hash_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'email': ('django.db.models.fields.EmailField', [], {
'max_length': '75'
}),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'is_verified': ('django.db.models.fields.BooleanField', [], {
'default': 'False'
}),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'related_name': "'emails'",
'to': "orm['sentry.User']"
}
),
'validation_hash': (
'django.db.models.fields.CharField', [], {
'default': "u'UgLIAnDusbhZ8E66pCx3Af5EoUtzEmSA'",
'max_length': '32'
}
)
},
'sentry.useroption': {
'Meta': {
'unique_together': "(('user', 'project', 'key'), ('user', 'organization', 'key'))",
'object_name': 'UserOption'
},
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'key': ('django.db.models.fields.CharField', [], {
'max_length': '64'
}),
'organization': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Organization']",
'null': 'True'
}
),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']",
'null': 'True'
}
),
'user': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.User']"
}
),
'value': ('sentry.db.models.fields.encrypted.EncryptedPickledObjectField', [], {})
},
'sentry.userreport': {
'Meta': {
'unique_together': "(('project', 'event_id'),)",
'object_name': 'UserReport',
'index_together': "(('project', 'event_id'), ('project', 'date_added'))"
},
'comments': ('django.db.models.fields.TextField', [], {}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'email': ('django.db.models.fields.EmailField', [], {
'max_length': '75'
}),
'event_id': ('django.db.models.fields.CharField', [], {
'max_length': '32'
}),
'event_user_id':
('sentry.db.models.fields.bounded.BoundedBigIntegerField', [], {
'null': 'True'
}),
'group': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Group']",
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'name': ('django.db.models.fields.CharField', [], {
'max_length': '128'
}),
'project': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.Project']"
}
)
},
'sentry.versiondsymfile': {
'Meta': {
'unique_together': "(('dsym_file', 'version', 'build'),)",
'object_name': 'VersionDSymFile'
},
'build':
('django.db.models.fields.CharField', [], {
'max_length': '32',
'null': 'True'
}),
'date_added':
('django.db.models.fields.DateTimeField', [], {
'default': 'datetime.datetime.now'
}),
'dsym_app': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.DSymApp']"
}
),
'dsym_file': (
'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {
'to': "orm['sentry.ProjectDSymFile']",
'null': 'True'
}
),
'id':
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {
'primary_key': 'True'
}),
'version': ('django.db.models.fields.CharField', [], {
'max_length': '32'
})
}
}
complete_apps = ['sentry']
| bsd-3-clause | -7,866,482,563,248,466,000 | 35.812677 | 120 | 0.398756 | false | 4.709444 | false | false | false |
tazo90/lux | setup.py | 1 | 1994 | import os
import json
from setuptools import setup, find_packages
package_name = 'lux'
def read(name):
root_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(root_dir, name), 'r') as f:
return f.read()
def run():
install_requires = []
dependency_links = []
pkg = json.loads(read('package.json'))
for line in read('requirements.txt').split('\n'):
if line.startswith('-e '):
link = line[3:].strip()
if link == '.':
continue
dependency_links.append(link)
line = link.split('=')[1]
line = line.strip()
if line:
install_requires.append(line)
packages = find_packages(exclude=['tests', 'tests.*'])
setup(name=package_name,
version=pkg['version'],
author=pkg['author']['name'],
author_email=pkg['author']['email'],
url=pkg['homepage'],
license=pkg['licenses'][0]['type'],
description=pkg['description'],
long_description=read('README.rst'),
packages=packages,
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
dependency_links=dependency_links,
scripts=['bin/luxmake.py'],
classifiers=['Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: JavaScript',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Utilities'])
if __name__ == '__main__':
run()
| bsd-3-clause | -8,769,033,512,469,859,000 | 31.16129 | 64 | 0.516048 | false | 4.573394 | false | false | false |
Robbie1977/TGscripts | plJHwarpToTemplate.py | 1 | 8574 | import os, re, shutil, subprocess, datetime, socket
ba = '/groups/sciserv/flyolympiad/vnc_align/toolkit/JBA/brainaligner'
cmtkdir = '/usr/local/cmtk/bin/'
fiji = '/usr/local/Fiji/ImageJ-linux64'
Rawconv = '~/script/raw2nrrdCrop.ijm'
Nrrdconv = '~/script/nrrd2rawUncrop.ijm'
Tfile = '~/template/flyVNCtemplate20xDaC.nrrd'
TfileR = '~/template/flyVNCtemplate20xDa.raw'
TfileM = '~/template/flyVNCtemplate20xDa.marker'
Qual = '~/script/Quality.py'
outdir = os.getcwd() + '/'
fo = open("PLwarp.txt",'r')
filelist = fo.readlines()
fo.close()
hostn = socket.gethostname()
runid = os.getpid()
procid = '[' + hostn + ';' + str(runid) + ']'
for fname in filelist:
fo = open("stop.txt",'r')
stoplist = fo.readlines()
if (hostn + '\n') in stoplist:
print 'Stop requested!'
else:
fname = fname.replace('\n','').replace('/disk/data/VFB/IMAGE_DATA/Janelia2012/TG/logs/',outdir)
try:
if os.path.exists(fname):
os.rename(fname,fname.replace('.lsm','~.lsm').replace('.raw','~.raw'))
basename = fname.replace(outdir,'').replace('.lsm','').replace('20130404_s/','').replace('.raw','').replace('Rigid/','').replace('/groups/sciserv/flyolympiad/vnc_align/20130404_lsms/','')
with open("PLwarp.log", "a") as myfile: # Log entry for process time and error checking
myfile.write(basename + ', Started JH warp, ' + procid + ', ' + str(datetime.datetime.now()) + '\n')
FloatFile = fname.replace('.lsm','~.lsm').replace('.raw','~.raw')
GxDF = outdir + basename + '-global.raw'
Goutput = basename + '-rigid.raw'
Axform = outdir + basename + '-rigid-affine.xform'
Foutput = Goutput.replace('-rigid.raw', '-rigid_C2.nrrd')
SigFile = Goutput.replace('-rigid.raw', '-rigid_C1.nrrd')
W5xform = outdir + basename + '-rigid-fastwarp.xform'
W5output = outdir + basename + '-rigid-BGwarp.nrrd'
Wsigout = outdir + basename + '-rigid-SGwarp.nrrd'
Routput = basename + '-rigid-warp.raw'
Loutput = basename + '-rigid-warp-local'
print 'Warping file %s...' % fname
#check for complete skip
if os.path.exists(W5xform):
print 'Warp5 output already exists - skipping.'
else:
#Generate the Initial Transform
if os.path.exists(Goutput):
print 'Global alignment already exists - skipping.'
else:
return_code = subprocess.call('nice ' + ba + ' -t %s -s %s -o %s -F %s -w 0 -C 0 -c 1 -B 1024 -Y' % (TfileR, FloatFile, Goutput, GxDF), shell=True)
print 'Brain Aligner Global alignment returned: %d' % return_code
#Convert raw to nrrd
return_code = subprocess.call('nice xvfb-run ' + fiji + ' -macro %s %s' % (Rawconv, Goutput), shell=True)
print 'Fiji/ImageJ conversion returned: %d' % return_code
#Generate the Affine Transform
if os.path.exists(Axform):
print 'Affine xform already exists - skipping.'
else:
FloatFile = Foutput
return_code = subprocess.call('nice ' + cmtkdir + 'registration --dofs 6,9 --auto-multi-levels 4 --match-histograms -o %s %s %s' % (Axform + '_part', Tfile, FloatFile), shell=True)
os.rename(Axform + '_part', Axform)
print 'registration returned: %d' % return_code
#Generate the Warped Transform
if os.path.exists(W5xform):
print 'Warp5 xform already exists - skipping.'
else:
return_code = subprocess.call('nice ' + cmtkdir + 'warp -o %s --grid-spacing 80 --exploration 30 --coarsest 4 --match-histograms --accuracy 0.2 --refine 4 --energy-weight 1e-1 --initial %s %s %s' % (W5xform + '_part', Axform, Tfile, FloatFile), shell=True) #coarsest adjusted from 8 to 4 as per greg sug.
os.rename(W5xform + '_part', W5xform)
print 'warp (5) returned: %d' % return_code
#Output a file to show the Warped Transform
if os.path.exists(W5output):
print 'Warp5 output already exists - skipping.'
else:
return_code = subprocess.call('nice ' + cmtkdir + 'reformatx -o %s --floating %s %s %s' % (W5output, FloatFile, Tfile, W5xform), shell=True)
print 'reformatx returned: %d' % return_code
print 'Completed background warpimg for %s.' % basename
if os.path.exists(Wsigout):
print 'Signal warp output already exists - skipping.'
else:
return_code = subprocess.call('nice ' + cmtkdir + 'reformatx -o %s --floating %s %s %s' % (Wsigout, SigFile, Tfile, W5xform), shell=True)
print 'reformatx returned: %d' % return_code
print 'Completed signal warpimg for %s.' % basename
if os.path.exists(Routput):
print 'RAW warp output already exists - skipping.'
else:
return_code = subprocess.call('nice xvfb-run ' + fiji + ' -macro %s %s' % (Nrrdconv, Routput), shell=True)
print 'Fiji returned: %d' % return_code
print 'Completed generating RAW warp for %s.' % basename
# if os.path.exists(Loutput + '.raw'):
# print 'Brianaligner local output already exists - skipping.'
# else:
# return_code = subprocess.call('nice ' + ba + ' -t %s -s %s -L %s -o %s -w 10 -C 0 -c 0 -H 2 -B 1024' % (TfileR, Routput, TfileM, Loutput + '.raw'), shell=True) #
# print 'Brainaligner returned: %d' % return_code
# print 'Completed generating RAW warp for %s.' % basename
if os.path.exists(Routput + '_qual.csv'):
print 'Quality measure already exists - skipping.'
else:
return_code = subprocess.call('nice python %s %s %s %s_qual.csv' % (Qual, W5output, Tfile, Routput), shell=True)
print 'Qual returned: %d' % return_code
print 'Completed generating Qual measure for %s.' % basename
if os.path.exists(W5output):
#os.remove(fname.replace('_blue',''))
#shutil.move(fname.replace('_blue',''),fname.replace('logs/','logs/nrrds/'))
#os.remove(Goutput)
#os.remove(Ioutput) Add if used
#shutil.rmtree(Axform, ignore_errors=True)
#os.remove(Aoutput)
#os.remove(W5xform) #Needed for Signal Channel Warp
with open("PLdone.txt", "a") as myfile:
myfile.write(Routput + '\n')
#os.remove(W5output) #Needed for checking only
print 'Clean-up for %s done.' % basename
with open("PLwarp.log", "a") as myfile: # Log entry for process time and error checking
myfile.write(basename + ', Finished JH warp, ' + procid + ', ' + str(datetime.datetime.now()) + '\n')
else:
print 'Failed warpimg for %s.' % basename
os.rename(fname.replace('_blue',''),fname.replace('_blue','_blue_error'))
with open("PLwarp.log", "a") as myfile: # Log entry for process time and error checking
myfile.write(basename + ', Failed JH warp, ' + procid + ', ' + str(datetime.datetime.now()) + '\n')
except OSError as e:
print 'Skiping file'
with open("PLwarp.log", "a") as myfile: # Log entry for process time and error checking
myfile.write(basename + ', Error during JH warp: ' + e.strerror + ', ' + procid + ', ' + str(datetime.datetime.now()) + '\n')
print 'All Done.'
| mit | -6,054,312,207,964,567,000 | 52.265823 | 328 | 0.515512 | false | 3.831099 | false | false | false |
tartopum/Lactum | setup.py | 1 | 1422 | import os
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import lactum
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
with open("README.md", "r") as f:
readme = f.read()
def reqs(*f):
def strip_comments(l):
return l.split("#", 1)[0].strip()
return list(filter(None, [strip_comments(l) for l in open(os.path.join(os.getcwd(), *f)).readlines()]))
requirements = reqs("requirements.txt")
test_requirements = reqs("requirements-dev.txt")
test_requirements = requirements + test_requirements[1:]
setup(
name="lactum",
description="",
long_description=readme,
author="Vayel",
author_email="[email protected]",
url="https://github.com/tartopum/Lactum",
packages=["lactum"],
package_dir={"lactum": "lactum"},
include_package_data=True,
install_requires=requirements,
license="MIT",
zip_safe=False,
classifiers=[
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Programming Language :: Python :: 3.5"
],
cmdclass={"test": PyTest},
tests_require=test_requirements
)
| mit | 268,804,563,701,314,200 | 24.392857 | 107 | 0.631505 | false | 3.618321 | true | false | false |
funkring/fdoo | addons-funkring/at_sale_layout_ext/sale.py | 1 | 1573 | # -*- coding: utf-8 -*-
#############################################################################
#
# Copyright (c) 2007 Martin Reisenhofer <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class SaleLayoutCategory(osv.Model):
_inherit = "sale_layout.category"
_columns = {
"order_id" : fields.many2one("sale.order", "Order", ondelete="cascade")
}
class sale_order(osv.Model):
_inherit = "sale.order"
_columns = {
"layout_categ_ids" : fields.one2many("sale_layout.category", "order_id", "Layout Categories")
}
class sale_order_line(osv.Model):
_inherit = "sale.order.line"
_columns = {
"prod_categ_id" : fields.related("product_id", "categ_id", string="Category", type="many2one", relation="product.category", readonly=True)
}
| agpl-3.0 | -4,435,612,682,991,795,700 | 37.365854 | 146 | 0.613477 | false | 3.893564 | false | false | false |
kmpf/uap | tools/segemehl_2017_reformatCigar.py | 1 | 4801 | #!/bin/bash
"exec" "`dirname $0`/../python_env/bin/python" "$0" "$@"
#"exec" "python" "$0" "$@"
# ^^^
# the cmd above ensures that the correct python environment is
# selected to execute this script.
# The correct environment is the one belonging to uap, since all
# neccessary python modules are installed there.
# filename: segemehl_2017_reformatCigar.py
# author: Jana Hertel
# date: 2017/06/07
# version: 1.0
# description: Reformat the cigar string such that htseq-count is able to process
# the according SAM files. Consecutive values for 'ix', 'j=' and 'kM'
# are summed up and replaced by nM with n being the sum of i, j and k.
import argparse
import sys
import re
from multiprocessing import Pool
import itertools
parser = argparse.ArgumentParser(
description='Python script to process a large file '
'using multi-processing.')
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
parser.add_argument(
'--in-file',
dest='my_file_in',
required=True,
type=argparse.FileType('r'),
help='A large file whose lines are independent from each other and '
'can be processed separately.')
parser.add_argument('--threads', dest='my_cores', default=1,
type=int,
help='Number of CPUs 2B used. Default: 1')
parser.add_argument(
'--blocksize',
dest='my_bufsize',
default=2,
type=int,
help='Size of buffer to read the input file (in MB). Default: 2')
args = parser.parse_args()
##########################################################################
# my_range(start, end, step)
#
# This function creates a range with a user defined step to walk through.
# returns: the respective new start values
def my_range(start, end, step):
while start <= end:
yield start
start += step
##########################################################################
##########################################################################
# process_line(line)
#
# function that does something with the line:
# in this case:
# - split the line into columns by tab
# - returns the columns separated by tab
def process_line(lines):
newlines = list()
c = 0
for line in lines:
c += 1
columns = line.strip().split('\t')
# don't process header lines
if(columns[0][:1] == "@"):
newlines.append(line.strip())
continue
cigar = columns[5]
x = re.split(r'(\D)', cigar)
# split cigar string and sum up consecutive values
# for '=' and 'X' (match and mismatch)
# leave values as they are for 'I','D' and 'N' (del, insertion, split)
M = 0
cigar_new = ''
for j in range(1, len(x) - 1, 2):
# match or mismatch
if x[j] == '=' or x[j] == 'X' or x[j] == 'M':
M = M + int(x[j - 1])
else: # del or ins
if M > 0:
# print the previous match/mismatch
cigar_new += str(M) + "M"
M = 0
# anything else but '=', 'X' or 'M'
cigar_new += x[j - 1] + x[j]
if M > 0:
cigar_new += str(M) + "M"
if cigar_new == "0M*":
cigar_new = "*"
# print the sam line with the new cigar string to stdout
new_line = ""
for k in range(0, 5):
new_line += "%s\t" % columns[k]
new_line += "%s\t" % cigar_new
for k in range(6, len(columns)):
new_line += "%s" % columns[k]
if(not k == len(columns)):
new_line += "\t"
newlines.append(new_line)
return newlines
# END: process_line(line)
##########################################################################
if __name__ == '__main__':
# create my_cores -1 pools, 1 control + the remaining for processing the
# lines
p = Pool(args.my_cores)
a = list()
eof_reached = False
# bufsize needs to be provided in bytes
# argument provided megabytes
bufsize = args.my_bufsize * 1000000
while not eof_reached:
for i in range(args.my_cores - 1):
linelist = args.my_file_in.readlines(bufsize)
if len(linelist) == 0:
eof_reached = True
else:
a.append(linelist) # ~ 2MB chunks
l = p.map(process_line, a)
for j in l:
print('\n'.join(j))
a[:] = [] # delete processed lines from the list
# this works in principle.. too much i/o
# for line in p.imap(process_line, args.my_file_in):
# print line, # the coma prevents printing an additional new line
# idea for mp:
# read file in chunks of the size 1/args.my_cores
# --> each chunk in one process
| gpl-3.0 | 6,380,944,447,513,988,000 | 27.076023 | 82 | 0.531764 | false | 3.762539 | false | false | false |
elewis33/doorstop | doorstop/server/utilities.py | 1 | 1176 | """Shared functions for the `doorstop.server` package."""
from doorstop import common
from doorstop import settings
log = common.logger(__name__)
class StripPathMiddleware(object): # pylint: disable=R0903
"""WSGI middleware that strips trailing slashes from all URLs."""
def __init__(self, app):
self.app = app
def __call__(self, e, h): # pragma: no cover (integration test)
e['PATH_INFO'] = e['PATH_INFO'].rstrip('/')
return self.app(e, h)
def build_url(host=None, port=None, path=None):
"""Build the server's URL with optional path."""
host = host or settings.SERVER_HOST
port = port or settings.SERVER_PORT
log.debug("building URL: {} + {} + {}".format(host, port, path))
if not host:
return None
url = 'http://{}'.format(host)
if port != 80:
url += ':{}'.format(port)
if path:
url += path
return url
def json_response(request): # pragma: no cover (integration test)
"""Determine if the request's response should be JSON."""
if request.query.get('format') == 'json':
return True
else:
return request.content_type == 'application/json'
| lgpl-3.0 | -7,028,435,530,194,350,000 | 27.682927 | 69 | 0.617347 | false | 3.78135 | false | false | false |
mtholder/taxalotl | taxalotl/parsing/col.py | 1 | 5000 | from __future__ import print_function
import io
import logging
from peyutil import shorter_fp_form
from taxalotl.resource_wrapper import TaxonomyWrapper
from taxalotl.parsing.darwin_core import normalize_darwin_core_taxonomy
_LOG = logging.getLogger(__name__)
COL_PARTMAP = {
'Archaea': frozenset([52435722]),
'Bacteria': frozenset([52433432]),
'Eukaryota': frozenset([52433499, 52435027, 52433974, 52433370]),
'Archaeplastida': frozenset([52433499]),
'Fungi': frozenset([52433393]),
'Metazoa': frozenset([52433370]),
'Viruses': frozenset([52433426]),
'Glaucophyta': frozenset([52444130]),
'Rhodophyta': frozenset([52444134]),
'Chloroplastida': frozenset([52442327, 52442210, 52442148, 52434330, 52434201, 52433500, ]),
'Annelida': frozenset([52433489]),
'Arthropoda': frozenset([52433375]),
'Malacostraca': frozenset([52433389]),
'Arachnida': frozenset([52433402]),
'Insecta': frozenset([52433376]),
'Diptera': frozenset([52433521]),
'Coleoptera': frozenset([52433486]),
'Lepidoptera': frozenset([52433663]),
'Hymenoptera': frozenset([52433621]),
'Bryozoa': frozenset([52442814]),
'Chordata': frozenset([52433371]),
'Cnidaria': frozenset([52433398]),
'Ctenophora': frozenset([52443092]),
'Mollusca': frozenset([52440786]),
'Nematoda': frozenset([52436787]),
'Platyhelminthes': frozenset([52443117]),
'Porifera': frozenset([52442836]),
}
# noinspection PyUnreachableCode
def partition_col_by_root_id(tax_part): # type (TaxonPartition) -> None
"""Reads the serialized taxonomy of the parent, adds the easy lines to their partition element,
and returns dicts needed to finish the assignments.
Signature for partition functions. Takes:
1. abs path of taxonomy file for parent taxon
2. list of PartitionElements whose roots are sets that specify IDs that are the
roots of the subtrees that are to go in each partition elemen.
Returns a tuple:
0. par_id ->[child_id] dict,
1. id -> partition_element dict for already assigned IDs,
2. id -> line dict - may only have unassigned IDs in it,
3. synonym id -> [(accepted_id, line), ] for any synonyms
4. roots_set - a frozen set of the union of the partition element roots
5. the rootless partition element ("garbage_bin" for all unassigned IDs)
6. header for taxon file
7. header for synonyms file (or None)
"""
assert False
complete_taxon_fp = tax_part.tax_fp
syn_fp = tax_part.input_synonyms_filepath
assert not syn_fp
syn_by_id = tax_part._syn_by_id
ptp = shorter_fp_form(complete_taxon_fp)
with io.open(complete_taxon_fp, 'rU', encoding='utf-8') as inp:
iinp = iter(inp)
tax_part.taxon_header = next(iinp)
prev_line = None
# vt = unicode('\x0b') # Do some lines have vertical tabs? Of course they do....
# istwo = unicode('\x1e')
for n, line in enumerate(iinp):
if not line.endswith('\n'):
if prev_line:
prev_line = prev_line + line[:-1]
else:
prev_line = line[:-1]
continue
elif prev_line:
line = prev_line + line
prev_line = ''
ls = line.split('\t')
if n % 1000 == 0:
_LOG.info(' read taxon {} from {}'.format(n, ptp))
try:
col_id, accept_id, par_id = ls[0], ls[4], ls[5]
col_id = int(col_id)
if accept_id:
try:
accept_id = int(accept_id)
except:
if n == 0:
continue
syn_by_id.setdefault(accept_id, []).append((col_id, line))
else:
tax_part.read_taxon_line(col_id, par_id, line)
except Exception:
_LOG.exception("Exception parsing line {}:\n{}".format(1 + n, line))
raise
# noinspection PyAbstractClass
class CoLTaxonomyWrapper(TaxonomyWrapper):
taxon_filename = 'taxonomy.tsv'
# synonyms_filename = None
# partition_parsing_fn = staticmethod(partition_col_by_root_id)
schema = {"http://rs.tdwg.org/dwc/"}
def __init__(self, obj, parent=None, refs=None):
TaxonomyWrapper.__init__(self, obj, parent=parent, refs=refs)
@property
def partition_source_dir(self):
return self.normalized_filedir
def get_primary_partition_map(self):
return COL_PARTMAP
def normalize(self):
normalize_darwin_core_taxonomy(self.unpacked_filepath, self.normalized_filedir, self)
def _post_process_tree(self, tree):
self.collapse_incertae_sedis_by_name_prefix(tree, 'not assigned')
def post_process_interim_tax_data(self, interim_tax_data):
self.collapse_as_incertae_sedis_interim_tax_data(interim_tax_data, 'not assigned')
| bsd-2-clause | 700,893,670,152,985,700 | 36.313433 | 99 | 0.61 | false | 3.531073 | false | false | false |
roglew/pappy-proxy | pappyproxy/interface/decode.py | 1 | 10668 | import html
import base64
import datetime
import gzip
import shlex
import string
import urllib
from ..util import hexdump, printable_data, copy_to_clipboard, clipboard_contents, encode_basic_auth, parse_basic_auth
from ..console import CommandError
from io import StringIO
def print_maybe_bin(s):
binary = False
for c in s:
if chr(c) not in string.printable:
binary = True
break
if binary:
print(hexdump(s))
else:
print(s.decode())
def asciihex_encode_helper(s):
return ''.join('{0:x}'.format(c) for c in s).encode()
def asciihex_decode_helper(s):
ret = []
try:
for a, b in zip(s[0::2], s[1::2]):
c = chr(a)+chr(b)
ret.append(chr(int(c, 16)))
return ''.join(ret).encode()
except Exception as e:
raise CommandError(e)
def gzip_encode_helper(s):
out = StringIO.StringIO()
with gzip.GzipFile(fileobj=out, mode="w") as f:
f.write(s)
return out.getvalue()
def gzip_decode_helper(s):
dec_data = gzip.GzipFile('', 'rb', 9, StringIO.StringIO(s))
dec_data = dec_data.read()
return dec_data
def base64_decode_helper(s):
try:
return base64.b64decode(s)
except TypeError:
for i in range(1, 5):
try:
s_padded = base64.b64decode(s + '='*i)
return s_padded
except:
pass
raise CommandError("Unable to base64 decode string")
def url_decode_helper(s):
bs = s.decode()
return urllib.parse.unquote(bs).encode()
def url_encode_helper(s):
bs = s.decode()
return urllib.parse.quote_plus(bs).encode()
def html_encode_helper(s):
return ''.join(['&#x{0:x};'.format(c) for c in s]).encode()
def html_decode_helper(s):
return html.unescape(s.decode()).encode()
def _code_helper(args, func, copy=True):
if len(args) == 0:
s = clipboard_contents().encode()
print('Will decode:')
print(printable_data(s))
s = func(s)
if copy:
try:
copy_to_clipboard(s)
except Exception as e:
print('Result cannot be copied to the clipboard. Result not copied.')
raise e
return s
else:
s = func(args[0].encode())
if copy:
try:
copy_to_clipboard(s)
except Exception as e:
print('Result cannot be copied to the clipboard. Result not copied.')
raise e
return s
def base64_decode(client, args):
"""
Base64 decode a string.
If no string is given, will decode the contents of the clipboard.
Results are copied to the clipboard.
"""
print_maybe_bin(_code_helper(args, base64_decode_helper))
def base64_encode(client, args):
"""
Base64 encode a string.
If no string is given, will encode the contents of the clipboard.
Results are copied to the clipboard.
"""
print_maybe_bin(_code_helper(args, base64.b64encode))
def url_decode(client, args):
"""
URL decode a string.
If no string is given, will decode the contents of the clipboard.
Results are copied to the clipboard.
"""
print_maybe_bin(_code_helper(args, url_decode_helper))
def url_encode(client, args):
"""
URL encode special characters in a string.
If no string is given, will encode the contents of the clipboard.
Results are copied to the clipboard.
"""
print_maybe_bin(_code_helper(args, url_encode_helper))
def asciihex_decode(client, args):
"""
Decode an ascii hex string.
If no string is given, will decode the contents of the clipboard.
Results are copied to the clipboard.
"""
print_maybe_bin(_code_helper(args, asciihex_decode_helper))
def asciihex_encode(client, args):
"""
Convert all the characters in a line to hex and combine them.
If no string is given, will encode the contents of the clipboard.
Results are copied to the clipboard.
"""
print_maybe_bin(_code_helper(args, asciihex_encode_helper))
def html_decode(client, args):
"""
Decode an html encoded string.
If no string is given, will decode the contents of the clipboard.
Results are copied to the clipboard.
"""
print_maybe_bin(_code_helper(args, html_decode_helper))
def html_encode(client, args):
"""
Encode a string and escape html control characters.
If no string is given, will encode the contents of the clipboard.
Results are copied to the clipboard.
"""
print_maybe_bin(_code_helper(args, html_encode_helper))
def gzip_decode(client, args):
"""
Un-gzip a string.
If no string is given, will decompress the contents of the clipboard.
Results are copied to the clipboard.
"""
print_maybe_bin(_code_helper(args, gzip_decode_helper))
def gzip_encode(client, args):
"""
Gzip a string.
If no string is given, will decompress the contents of the clipboard.
Results are NOT copied to the clipboard.
"""
print_maybe_bin(_code_helper(args, gzip_encode_helper, copy=False))
def base64_decode_raw(client, args):
"""
Same as base64_decode but the output will never be printed as a hex dump and
results will not be copied. It is suggested you redirect the output
to a file.
"""
print(_code_helper(args, base64_decode_helper, copy=False))
def base64_encode_raw(client, args):
"""
Same as base64_encode but the output will never be printed as a hex dump and
results will not be copied. It is suggested you redirect the output
to a file.
"""
print(_code_helper(args, base64.b64encode, copy=False))
def url_decode_raw(client, args):
"""
Same as url_decode but the output will never be printed as a hex dump and
results will not be copied. It is suggested you redirect the output
to a file.
"""
print(_code_helper(args, url_decode_helper, copy=False))
def url_encode_raw(client, args):
"""
Same as url_encode but the output will never be printed as a hex dump and
results will not be copied. It is suggested you redirect the output
to a file.
"""
print(_code_helper(args, url_encode_helper, copy=False))
def asciihex_decode_raw(client, args):
"""
Same as asciihex_decode but the output will never be printed as a hex dump and
results will not be copied. It is suggested you redirect the output
to a file.
"""
print(_code_helper(args, asciihex_decode_helper, copy=False))
def asciihex_encode_raw(client, args):
"""
Same as asciihex_encode but the output will never be printed as a hex dump and
results will not be copied. It is suggested you redirect the output
to a file.
"""
print(_code_helper(args, asciihex_encode_helper, copy=False))
def html_decode_raw(client, args):
"""
Same as html_decode but the output will never be printed as a hex dump and
results will not be copied. It is suggested you redirect the output
to a file.
"""
print(_code_helper(args, html_decode_helper, copy=False))
def html_encode_raw(client, args):
"""
Same as html_encode but the output will never be printed as a hex dump and
results will not be copied. It is suggested you redirect the output
to a file.
"""
print(_code_helper(args, html_encode_helper, copy=False))
def gzip_decode_raw(client, args):
"""
Same as gzip_decode but the output will never be printed as a hex dump and
results will not be copied. It is suggested you redirect the output
to a file.
"""
print(_code_helper(args, gzip_decode_helper, copy=False))
def gzip_encode_raw(client, args):
"""
Same as gzip_encode but the output will never be printed as a hex dump and
results will not be copied. It is suggested you redirect the output
to a file.
"""
print(_code_helper(args, gzip_encode_helper, copy=False))
def unix_time_decode_helper(line):
unix_time = int(line.strip())
dtime = datetime.datetime.fromtimestamp(unix_time)
return dtime.strftime('%Y-%m-%d %H:%M:%S')
def unix_time_decode(client, args):
print(_code_helper(args, unix_time_decode_helper))
def http_auth_encode(client, args):
if len(args) != 2:
raise CommandError('Usage: http_auth_encode <username> <password>')
username, password = args
print(encode_basic_auth(username, password))
def http_auth_decode(client, args):
username, password = decode_basic_auth(args[0])
print(username)
print(password)
def load_cmds(cmd):
cmd.set_cmds({
'base64_decode': (base64_decode, None),
'base64_encode': (base64_encode, None),
'asciihex_decode': (asciihex_decode, None),
'asciihex_encode': (asciihex_encode, None),
'url_decode': (url_decode, None),
'url_encode': (url_encode, None),
'html_decode': (html_decode, None),
'html_encode': (html_encode, None),
'gzip_decode': (gzip_decode, None),
'gzip_encode': (gzip_encode, None),
'base64_decode_raw': (base64_decode_raw, None),
'base64_encode_raw': (base64_encode_raw, None),
'asciihex_decode_raw': (asciihex_decode_raw, None),
'asciihex_encode_raw': (asciihex_encode_raw, None),
'url_decode_raw': (url_decode_raw, None),
'url_encode_raw': (url_encode_raw, None),
'html_decode_raw': (html_decode_raw, None),
'html_encode_raw': (html_encode_raw, None),
'gzip_decode_raw': (gzip_decode_raw, None),
'gzip_encode_raw': (gzip_encode_raw, None),
'unixtime_decode': (unix_time_decode, None),
'httpauth_encode': (http_auth_encode, None),
'httpauth_decode': (http_auth_decode, None)
})
cmd.add_aliases([
('base64_decode', 'b64d'),
('base64_encode', 'b64e'),
('asciihex_decode', 'ahd'),
('asciihex_encode', 'ahe'),
('url_decode', 'urld'),
('url_encode', 'urle'),
('html_decode', 'htmld'),
('html_encode', 'htmle'),
('gzip_decode', 'gzd'),
('gzip_encode', 'gze'),
('base64_decode_raw', 'b64dr'),
('base64_encode_raw', 'b64er'),
('asciihex_decode_raw', 'ahdr'),
('asciihex_encode_raw', 'aher'),
('url_decode_raw', 'urldr'),
('url_encode_raw', 'urler'),
('html_decode_raw', 'htmldr'),
('html_encode_raw', 'htmler'),
('gzip_decode_raw', 'gzdr'),
('gzip_encode_raw', 'gzer'),
('unixtime_decode', 'uxtd'),
('httpauth_encode', 'hae'),
('httpauth_decode', 'had'),
])
| mit | -4,319,996,795,967,323,600 | 31.723926 | 118 | 0.624953 | false | 3.587088 | false | false | false |
pycontw/pycontw2016 | src/proposals/migrations/0038_add_new_conference.py | 1 | 1404 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2019-07-10 07:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('proposals', '0037_auto_20180305_1339'),
]
operations = [
migrations.AlterField(
model_name='additionalspeaker',
name='conference',
field=models.SlugField(choices=[('pycontw-2016', 'PyCon Taiwan 2016'), ('pycontw-2017', 'PyCon Taiwan 2017'), ('pycontw-2018', 'PyCon Taiwan 2018'), ('pycontw-2019', 'PyCon Taiwan 2019')], default='pycontw-2019', verbose_name='conference'),
),
migrations.AlterField(
model_name='talkproposal',
name='conference',
field=models.SlugField(choices=[('pycontw-2016', 'PyCon Taiwan 2016'), ('pycontw-2017', 'PyCon Taiwan 2017'), ('pycontw-2018', 'PyCon Taiwan 2018'), ('pycontw-2019', 'PyCon Taiwan 2019')], default='pycontw-2019', verbose_name='conference'),
),
migrations.AlterField(
model_name='tutorialproposal',
name='conference',
field=models.SlugField(choices=[('pycontw-2016', 'PyCon Taiwan 2016'), ('pycontw-2017', 'PyCon Taiwan 2017'), ('pycontw-2018', 'PyCon Taiwan 2018'), ('pycontw-2019', 'PyCon Taiwan 2019')], default='pycontw-2019', verbose_name='conference'),
),
]
| mit | -1,369,078,986,699,272,400 | 45.8 | 252 | 0.625356 | false | 3.572519 | false | false | false |
zzh8829/RevOctane | bstream.py | 1 | 3007 | import io
import struct
little_endian_types = {
'int8': 'b',
'uint8': 'B',
'int16': 'h',
'uint16': 'H',
'int32': 'i',
'uint32': 'I',
'int64': 'q',
'uint64': 'Q',
'float': 'f',
'float32': 'f',
'double': 'd',
'char': 'c',
'bool': '?',
'pad': 'x',
'void*': 'P',
}
big_endian_types = { k:">"+v for k,v in little_endian_types.items()}
special_types = {
'int12': 'read_int12',
'uint12': 'read_int12',
'float16': 'read_float16',
}
class BStream:
def __init__(self, **kwargs):
if "file" in kwargs:
self.stream = open(kwargs["file"], "rb")
elif "stream" in kwargs:
self.stream = kwargs["stream"]
elif "bytes" in kwargs:
self.stream = io.BytesIO(kwargs["bytes"])
else:
raise Exception("unknown stream source")
self.endianness = kwargs.get("endianness","little")
if self.endianness == "little":
self.normal_types = little_endian_types
elif self.endianness == "big":
self.normal_types = big_endian_types
def read(self, type_name='char'):
if isinstance(type_name,int):
return self.unpack('%ds'%type_name)[0]
type_name = type_name.lower()
if type_name.endswith('_t'):
type_name = type_name[:-2]
if type_name in special_types:
return getattr(self, special_types[type_name])()
if type_name in self.normal_types:
return self.unpack(self.normal_types[type_name])[0]
raise Exception("unknown type")
def unpack(self, fmt):
return struct.unpack(fmt, self.stream.read(struct.calcsize(fmt)))
def read_cstring(self):
string = ""
while True:
char = self.read('char')
if ord(char) == 0:
break
string += char.decode("utf-8")
return string
def read_string(self):
return self.unpack('%ds'%self.read('uint32_t'))[0].decode('utf-8')
def read_all(self):
return self.read(self.size() - self.get_position())
def read_int12(self):
return int.from_bytes(self.read(3),byteorder=self.endianness)
def read_float16(self):
data = self.read('uint16_t')
s = int((data >> 15) & 0x00000001) # sign
e = int((data >> 10) & 0x0000001f) # exponent
f = int(data & 0x000003ff) # fraction
if e == 0:
if f == 0:
return int(s << 31)
else:
while not (f & 0x00000400):
f = f << 1
e -= 1
e += 1
f &= ~0x00000400
#print(s,e,f)
elif e == 31:
if f == 0:
return int((s << 31) | 0x7f800000)
else:
return int((s << 31) | 0x7f800000 | (f << 13))
e = e + (127 -15)
f = f << 13
buf = struct.pack('I',int((s << 31) | (e << 23) | f))
return struct.unpack('f',buf)[0]
def tell(self):
return self.stream.tell()
def seek(self, pos, whence):
return self.stream.seek(pos, whence)
def get_position(self):
return self.tell()
def set_position(self, pos, whence=0):
return self.seek(pos, whence)
def size(self):
pos = self.get_position()
self.set_position(0,2)
end = self.get_position()
self.set_position(pos,0)
return end
def align(self, alignment=4):
self.set_position((self.get_position() + alignment - 1) // alignment * alignment)
| mit | -8,549,833,761,040,858,000 | 21.954198 | 84 | 0.60858 | false | 2.628497 | false | false | false |
avedaee/DIRAC | DataManagementSystem/Client/ReplicaContainers.py | 1 | 4513 | # $HeadURL$
__RCSID__ = "$Id$"
""" This module contains three classes associated to Replicas.
The Replica class contains simply three member elements: SE, PFN and Status and provides access methods for each (inluding type checking).
The CatalogReplica class inherits the Replica class.
The PhysicalReplica class inherits the Replica class and adds the 'size','checksum','online' and 'migrated' members.
In this context Replica refers to any copy of a file. This can be the first or an additional copy.
OBSOLETE?
K.C.
"""
import types
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.Utilities.CFG import CFG
class Replica:
def __init__(self,pfn='',storageElement='',status=''):
# These are the possible attributes for a replica
if not type(pfn) in types.StringTypes:
raise AttributeError, "pfn should be string type"
self.pfn = str(pfn)
if not type(storageElement) in types.StringTypes:
raise AttributeError, "storageElement should be string type"
self.se = str(storageElement)
if not type(status) in types.StringTypes:
raise AttributeError, "status should be string type"
self.status = str(status)
def setPFN(self,pfn):
if not type(pfn) in types.StringTypes:
return S_ERROR("PFN should be %s and not %s" % (types.StringType,type(pfn)))
self.pfn = str(pfn)
return S_OK()
def setSE(self,se):
if not type(se) in types.StringTypes:
return S_ERROR("SE should be %s and not %s" % (types.StringType,type(se)))
self.se = str(se)
return S_OK()
def setStatus(self,status):
if not type(status) in types.StringTypes:
return S_ERROR("Status should be %s and not %s" % (types.StringType,type(status)))
self.status = str(status)
return S_OK()
def getPFN(self):
return S_OK(self.pfn)
def getSE(self):
return S_OK(self.se)
def getStatus(self):
return S_OK(self.status)
def digest(self):
""" Get short description string of replica and status
"""
return S_OK("%s:%s:%s" % (self.se,self.pfn,self.status))
def toCFG(self):
oCFG = CFG()
oCFG.createNewSection(self.se)
oCFG.setOption('%s/Status' % (self.se), self.status)
oCFG.setOption('%s/PFN' % (self.se), self.pfn)
return S_OK(str(oCFG))
class CatalogReplica(Replica):
def __init__(self,pfn='',storageElement='',status='U'):
Replica.__init__(self,pfn,storageElement,status)
class PhysicalReplica(Replica):
def __init__(self,pfn='',storageElement='',status='',size=0,checksum='',online=False,migrated=False):
# These are the possible attributes for a physical replica
Replica.__init__(self,pfn,storageElement,status)
try:
self.size = int(size)
except:
raise AttributeError, "size should be integer type"
if not type(checksum) in types.StringTypes:
raise AttributeError, "checksum should be string type"
self.checksum = str(checksum)
if not type(online) == types.BooleanType:
raise AttributeError, "online should be bool type"
self.online = online
if not type(migrated) == types.BooleanType:
raise AttributeError, "migrated should be bool type"
self.migrated = migrated
def setSize(self,size):
try:
self.size = int(size)
return S_OK()
except:
return S_ERROR("Size should be %s and not %s" % (types.IntType,type(size)))
def setChecksum(self,checksum):
if not type(checksum) in types.StringTypes:
return S_ERROR("Checksum should be %s and not %s" % (types.StringType,type(checksum)))
self.checksum = str(checksum)
return S_OK()
def setOnline(self,online):
if not type(online) == types.BooleanType:
return S_ERROR("online should be %s and not %s" % (types.BooleanType,type(online)))
self.online = online
return S_OK()
def setMigrated(self,migrated):
if not type(migrated) == types.BooleanType:
return S_ERROR("migrated should be %s and not %s" % (types.BooleanType,type(migrated)))
self.migrated = migrated
return S_OK()
def getSize(self):
return S_OK(self.size)
def getChecksum(self):
return S_OK(self.checksum)
def getOnline(self):
return S_OK(self.online)
def getMigrated(self):
return S_OK(self.migrated)
def digest(self):
online = 'NotOnline'
if self.online:
online = 'Online'
migrated = 'NotMigrated'
if self.migrated:
migrated = 'Migrated'
return S_OK("%s:%s:%d:%s:%s:%s" % (self.se,self.pfn,self.size,self.status,online,migrated))
| gpl-3.0 | 2,198,887,395,661,303,000 | 31.007092 | 143 | 0.670286 | false | 3.484942 | false | false | false |
erikrose/oedipus | oedipus/results.py | 1 | 4275 | class SearchResults(object):
"""Results in the order in which they came out of Sphinx
Since Sphinx stores no non-numerical attributes, we have to reach into the
DB to pull them out.
"""
def __init__(self, type, ids, fields):
self.type = type
# Sphinx may return IDs of objects since deleted from the DB.
self.ids = ids
self.fields = fields # tuple
self.objects = dict(self._objects()) # {id: obj/tuple/dict, ...}
def _queryset(self):
"""Return a QuerySet of the objects parallel to the found docs."""
return self.type.objects.filter(id__in=self.ids)
def __iter__(self):
"""Iterate over results in the same order they came out of Sphinx."""
# Ripped off from elasticutils
return (self.objects[id] for id in self.ids if id in self.objects)
class DictResults(SearchResults):
"""Results as an iterable of dictionaries"""
def _dicts_with_ids(self):
"""Return an iterable of dicts with ``id`` attrs, each representing a matched DB object."""
fields = self.fields
# Append ID to the requested fields so we can keep track of object
# identity to sort by weight (or whatever Sphinx sorted by). We could
# optimize slightly by not prepending ID if the user already
# specifically asked for it, but then we'd have to keep track of its
# offset.
if fields and 'id' not in fields:
fields += ('id',)
# Get values rather than values_list, because we need to be able to
# find the ID afterward, and we don't want to have to go rooting around
# in the Django model to figure out what order the fields were declared
# in in the case that no fields were passed in.
return self._queryset().values(*fields)
def _objects(self):
"""Return an iterable of (document ID, dict) pairs."""
should_strip_ids = self.fields and 'id' not in self.fields
for d in self._dicts_with_ids():
id = d.pop('id') if should_strip_ids else d['id']
yield id, d
@classmethod
def content_for_fields(klass, result, fields, highlight_fields):
"""Returns a tuple with content values for highlight_fields.
:param result: A result generated by this class.
:param fields: Iterable of fields for a result from this class.
:param highlight_fields: Iterable of the fields to highlight.
This should be a subset of ``fields``.
:returns: Tuple with content in the field indexes specified by
``highlight_fields``.
:raises KeyError: If there is a field in ``highlight_fields``
that doesn't exist in ``fields``.
"""
return tuple(result[field] for field in highlight_fields)
class TupleResults(DictResults):
"""Results as an iterable of tuples, like Django's values_list()"""
def _objects(self):
"""Return an iterable of (document ID, tuple) pairs."""
for d in self._dicts_with_ids():
yield d['id'], tuple(d[k] for k in self.fields)
@classmethod
def content_for_fields(klass, result, fields, highlight_fields):
"""See ``DictResults.content_for_fields``.
:raises ValueError: If there is a field in
``highlight_fields`` that doesn't exist in ``fields``.
"""
return tuple(result[fields.index(field)]
for field in highlight_fields)
class ObjectResults(SearchResults):
"""Results as an iterable of Django model-like objects"""
def _objects(self):
"""Return an iterable of (document ID, model object) pairs."""
# Assuming the document ID is called "id" lets us depend on fewer
# Djangoisms than assuming it's the pk; we'd have to get
# self.type._meta to get the name of the pk.
return ((o.id, o) for o in self._queryset())
@classmethod
def content_for_fields(klass, result, fields, highlight_fields):
"""See ``DictResults.content_for_fields``.
:raises AttributeError: If there is a field in
``highlight_fields`` that doesn't exist in ``fields``.
"""
return tuple(getattr(result, field) for field in highlight_fields)
| bsd-3-clause | 2,535,138,606,245,989 | 39.330189 | 99 | 0.629474 | false | 4.309476 | false | false | false |
arjunasuresh3/Mypykoans | python 2/koans/about_monkey_patching.py | 1 | 1451 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Related to AboutOpenClasses in the Ruby Koans
#
from runner.koan import *
class AboutMonkeyPatching(Koan):
class Dog(object):
def bark(self):
return "WOOF"
def test_as_defined_dogs_do_bark(self):
fido = self.Dog()
self.assertEqual("WOOF", fido.bark())
# ------------------------------------------------------------------
# Add a new method to an existing class.
def test_after_patching_dogs_can_both_wag_and_bark(self):
def wag(self): return "HAPPY"
self.Dog.wag = wag
fido = self.Dog()
self.assertEqual("HAPPY", fido.wag())
self.assertEqual("WOOF", fido.bark())
# ------------------------------------------------------------------
def test_most_built_in_classes_cannot_be_monkey_patched(self):
try:
int.is_even = lambda self: (self % 2) == 0
except StandardError as ex:
self.assertMatch("can't set attributes of built-in/extension type 'int'", ex[0])
# ------------------------------------------------------------------
class MyInt(int): pass
def test_subclasses_of_built_in_classes_can_be_be_monkey_patched(self):
self.MyInt.is_even = lambda self: (self % 2) == 0
self.assertEqual(False, self.MyInt(1).is_even())
self.assertEqual(True, self.MyInt(2).is_even())
| mit | 6,103,702,846,106,463,000 | 29.229167 | 92 | 0.500345 | false | 3.710997 | false | false | false |
tedlaz/pyted | misthodosia/m13a/fmy.py | 1 | 2802 | # -*- coding: utf-8 -*-
'''
Created on 16 Ιαν 2013
@author: tedlaz
'''
from utils import dec as d
def f13(poso):
poso = d(poso)
ekp = d(0)
if poso < d(21500):
ekp = d(2100)
elif poso < d(22500):
ekp = d(2000)
elif poso < d(23500):
ekp = d(1900)
elif poso < d(24500):
ekp = d(1800)
elif poso < d(25500):
ekp = d(1700)
elif poso < d(26500):
ekp = d(1600)
elif poso < d(27500):
ekp = d(1500)
elif poso < d(28500):
ekp = d(1400)
elif poso < d(29500):
ekp = d(1300)
elif poso < d(30500):
ekp = d(1200)
elif poso < d(31500):
ekp = d(1100)
elif poso < d(32500):
ekp = d(1000)
elif poso < d(33500):
ekp = d(900)
elif poso < d(34500):
ekp = d(800)
elif poso < d(35500):
ekp = d(700)
elif poso < d(36500):
ekp = d(600)
elif poso < d(37500):
ekp = d(500)
elif poso < d(38500):
ekp = d(400)
elif poso < d(39500):
ekp = d(300)
elif poso < d(40500):
ekp = d(200)
elif poso < d(41500):
ekp = d(100)
else:
ekp = d(0)
#print 'ekptosi',poso,ekp
foros = d(0)
if poso <= d(25000):
foros = d(poso * d(22) / d(100))
else:
foros = d(5500)
poso = poso - d(25000)
if poso <= d(17000):
foros += d(poso * d(32) / d(100))
else:
foros += d(5440)
poso = poso - d(17000)
foros += d(poso * d(42) / d(100))
foros = foros - ekp
if foros < d(0) :
foros = d(0)
return foros
def eea(poso):
poso = d(poso)
if poso <= d(12000):
synt = d(0)
elif poso <= d(20000):
synt = d(1)
elif poso <= d(50000):
synt = d(2)
elif poso <= d(100000):
synt = d(3)
else:
synt = d(4)
return d(poso * synt / d(100))
def eeap(poso,bar=1): #bar : 1 εάν ολόκληρη περίοδος 2 εάν μισή (πχ.επίδομα αδείας)
poso = d(poso)
tb = d(14) * d(bar)
eis = poso * tb
ee = eea(eis)
return d(ee / tb)
def fp13(poso,bar=1):
poso = poso
tb = 14 * bar
eis = poso * tb
f = f13(eis)
#pf = d(f - d(0.015,3) * f)
return f / tb
def fpXrisis(poso,bar=1,xrisi=2013):
if xrisi == 2013:
return fp13(poso,bar)
else:
return 0
def eeaXrisis(poso,bar=1,xrisi=2013):
if xrisi == 2012 or xrisi == 2013:
return eeap(poso,bar)
else:
return d(0)
if __name__ == '__main__':
p = 2035.72
print fpXrisis(p,1,2013)
print eeaXrisis(p,1,2013) | gpl-3.0 | -9,046,916,456,819,823,000 | 21.389831 | 83 | 0.451414 | false | 2.532599 | false | false | false |
Sorsly/subtle | google-cloud-sdk/platform/gsutil/third_party/apitools/run_pylint.py | 3 | 8173 | #
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Custom script to run PyLint on apitools codebase.
"Inspired" by the similar script in gcloud-python.
This runs pylint as a script via subprocess in two different
subprocesses. The first lints the production/library code
using the default rc file (PRODUCTION_RC). The second lints the
demo/test code using an rc file (TEST_RC) which allows more style
violations (hence it has a reduced number of style checks).
"""
import ConfigParser
import copy
import os
import subprocess
import sys
IGNORED_DIRECTORIES = [
'apitools/gen/testdata',
'samples/storage_sample/storage',
'venv',
]
IGNORED_FILES = [
'ez_setup.py',
'run_pylint.py',
'setup.py',
]
PRODUCTION_RC = 'default.pylintrc'
TEST_RC = 'reduced.pylintrc'
TEST_DISABLED_MESSAGES = [
'exec-used',
'invalid-name',
'missing-docstring',
'protected-access',
]
TEST_RC_ADDITIONS = {
'MESSAGES CONTROL': {
'disable': ',\n'.join(TEST_DISABLED_MESSAGES),
},
}
def read_config(filename):
"""Reads pylintrc config onto native ConfigParser object."""
config = ConfigParser.ConfigParser()
with open(filename, 'r') as file_obj:
config.readfp(file_obj)
return config
def make_test_rc(base_rc_filename, additions_dict, target_filename):
"""Combines a base rc and test additions into single file."""
main_cfg = read_config(base_rc_filename)
# Create fresh config for test, which must extend production.
test_cfg = ConfigParser.ConfigParser()
test_cfg._sections = copy.deepcopy(main_cfg._sections)
for section, opts in additions_dict.items():
curr_section = test_cfg._sections.setdefault(
section, test_cfg._dict())
for opt, opt_val in opts.items():
curr_val = curr_section.get(opt)
if curr_val is None:
raise KeyError('Expected to be adding to existing option.')
curr_section[opt] = '%s\n%s' % (curr_val, opt_val)
with open(target_filename, 'w') as file_obj:
test_cfg.write(file_obj)
def valid_filename(filename):
"""Checks if a file is a Python file and is not ignored."""
for directory in IGNORED_DIRECTORIES:
if filename.startswith(directory):
return False
return (filename.endswith('.py') and
filename not in IGNORED_FILES)
def is_production_filename(filename):
"""Checks if the file contains production code.
:rtype: boolean
:returns: Boolean indicating production status.
"""
return not ('demo' in filename or 'test' in filename or
filename.startswith('regression'))
def get_files_for_linting(allow_limited=True, diff_base=None):
"""Gets a list of files in the repository.
By default, returns all files via ``git ls-files``. However, in some cases
uses a specific commit or branch (a so-called diff base) to compare
against for changed files. (This requires ``allow_limited=True``.)
To speed up linting on Travis pull requests against master, we manually
set the diff base to origin/master. We don't do this on non-pull requests
since origin/master will be equivalent to the currently checked out code.
One could potentially use ${TRAVIS_COMMIT_RANGE} to find a diff base but
this value is not dependable.
:type allow_limited: boolean
:param allow_limited: Boolean indicating if a reduced set of files can
be used.
:rtype: pair
:returns: Tuple of the diff base using the the list of filenames to be
linted.
"""
if os.getenv('TRAVIS') == 'true':
# In travis, don't default to master.
diff_base = None
if (os.getenv('TRAVIS_BRANCH') == 'master' and
os.getenv('TRAVIS_PULL_REQUEST') != 'false'):
# In the case of a pull request into master, we want to
# diff against HEAD in master.
diff_base = 'origin/master'
if diff_base is not None and allow_limited:
result = subprocess.check_output(['git', 'diff', '--name-only',
diff_base])
print 'Using files changed relative to %s:' % (diff_base,)
print '-' * 60
print result.rstrip('\n') # Don't print trailing newlines.
print '-' * 60
else:
print 'Diff base not specified, listing all files in repository.'
result = subprocess.check_output(['git', 'ls-files'])
return result.rstrip('\n').split('\n'), diff_base
def get_python_files(all_files=None, diff_base=None):
"""Gets a list of all Python files in the repository that need linting.
Relies on :func:`get_files_for_linting()` to determine which files should
be considered.
NOTE: This requires ``git`` to be installed and requires that this
is run within the ``git`` repository.
:type all_files: list or ``NoneType``
:param all_files: Optional list of files to be linted.
:rtype: tuple
:returns: A tuple containing two lists and a boolean. The first list
contains all production files, the next all test/demo files and
the boolean indicates if a restricted fileset was used.
"""
using_restricted = False
if all_files is None:
all_files, diff_base = get_files_for_linting(diff_base=diff_base)
using_restricted = diff_base is not None
library_files = []
non_library_files = []
for filename in all_files:
if valid_filename(filename):
if is_production_filename(filename):
library_files.append(filename)
else:
non_library_files.append(filename)
return library_files, non_library_files, using_restricted
def lint_fileset(filenames, rcfile, description):
"""Lints a group of files using a given rcfile."""
# Only lint filenames that exist. For example, 'git diff --name-only'
# could spit out deleted / renamed files. Another alternative could
# be to use 'git diff --name-status' and filter out files with a
# status of 'D'.
filenames = [filename for filename in filenames
if os.path.exists(filename)]
if filenames:
rc_flag = '--rcfile=%s' % (rcfile,)
pylint_shell_command = ['pylint', rc_flag] + filenames
status_code = subprocess.call(pylint_shell_command)
if status_code != 0:
error_message = ('Pylint failed on %s with '
'status %d.' % (description, status_code))
print >> sys.stderr, error_message
sys.exit(status_code)
else:
print 'Skipping %s, no files to lint.' % (description,)
def main(argv):
"""Script entry point. Lints both sets of files."""
diff_base = argv[1] if len(argv) > 1 else None
make_test_rc(PRODUCTION_RC, TEST_RC_ADDITIONS, TEST_RC)
library_files, non_library_files, using_restricted = get_python_files(
diff_base=diff_base)
try:
lint_fileset(library_files, PRODUCTION_RC, 'library code')
lint_fileset(non_library_files, TEST_RC, 'test and demo code')
except SystemExit:
if not using_restricted:
raise
message = 'Restricted lint failed, expanding to full fileset.'
print >> sys.stderr, message
all_files, _ = get_files_for_linting(allow_limited=False)
library_files, non_library_files, _ = get_python_files(
all_files=all_files)
lint_fileset(library_files, PRODUCTION_RC, 'library code')
lint_fileset(non_library_files, TEST_RC, 'test and demo code')
if __name__ == '__main__':
main(sys.argv)
| mit | -4,517,023,543,270,012,400 | 34.534783 | 78 | 0.650679 | false | 3.916148 | true | false | false |
angr/angr | angr/analyses/decompiler/optimization_passes/mod_simplifier.py | 1 | 2880 | import logging
from ailment import Expr
from ... import AnalysesHub
from .engine_base import SimplifierAILEngine, SimplifierAILState
from .optimization_pass import OptimizationPass, OptimizationPassStage
_l = logging.getLogger(name=__name__)
class ModSimplifierAILEngine(SimplifierAILEngine):
def _ail_handle_Sub(self, expr):
operand_0 = self._expr(expr.operands[0])
operand_1 = self._expr(expr.operands[1])
x_0, c_0, x_1, c_1 = None, None, None, None
if isinstance(operand_1, Expr.BinaryOp) \
and isinstance(operand_1.operands[1], Expr.Const) \
and operand_1.op == 'Mul':
if isinstance(operand_1.operands[0], Expr.BinaryOp) \
and isinstance(operand_1.operands[0].operands[1], Expr.Const) \
and operand_1.operands[0].op in ['Div', 'DivMod']:
x_0 = operand_1.operands[0].operands[0]
x_1 = operand_0
c_0 = operand_1.operands[1]
c_1 = operand_1.operands[0].operands[1]
elif isinstance(operand_1.operands[0], Expr.Convert) \
and isinstance(operand_1.operands[0].operand, Expr.BinaryOp) \
and operand_1.operands[0].operand.op in ['Div', 'DivMod']:
x_0 = operand_1.operands[0].operand.operands[0]
x_1 = operand_0
c_0 = operand_1.operands[1]
c_1 = operand_1.operands[0].operand.operands[1]
if x_0 is not None and x_1 is not None and x_0 == x_1 and c_0.value == c_1.value:
return Expr.BinaryOp(expr.idx, 'Mod', [x_0, c_0], expr.signed, **expr.tags)
if (operand_0, operand_1) != (expr.operands[0], expr.operands[1]):
return Expr.BinaryOp(expr.idx, 'Sub', [operand_0, operand_1], expr.signed, **expr.tags)
return expr
def _ail_handle_Mod(self, expr): #pylint: disable=no-self-use
return expr
class ModSimplifier(OptimizationPass):
ARCHES = ["X86", "AMD64"]
PLATFORMS = ["linux", "windows"]
STAGE = OptimizationPassStage.AFTER_GLOBAL_SIMPLIFICATION
def __init__(self, func, **kwargs):
super().__init__(func, **kwargs)
self.state = SimplifierAILState(self.project.arch)
self.engine = ModSimplifierAILEngine()
self.analyze()
def _check(self):
return True, None
def _analyze(self, cache=None):
for block in list(self._graph.nodes()):
new_block = block
old_block = None
while new_block != old_block:
old_block = new_block
new_block = self.engine.process(state=self.state.copy(), block=old_block.copy())
_l.debug("new block: %s", new_block.statements)
self._update_block(block, new_block)
AnalysesHub.register_default("ModSimplifier", ModSimplifier)
| bsd-2-clause | 3,081,194,925,430,433,000 | 35.923077 | 99 | 0.591667 | false | 3.428571 | false | false | false |
pjz/Zappa | test_settings.py | 1 | 1325 | APP_MODULE = 'tests.test_app'
APP_FUNCTION = 'hello_world'
DJANGO_SETTINGS = None
DEBUG = 'True'
LOG_LEVEL = 'DEBUG'
SCRIPT_NAME = 'hello_world'
DOMAIN = None
API_STAGE = 'ttt888'
PROJECT_NAME = 'ttt888'
REMOTE_ENV='s3://lmbda/test_env.json'
## test_env.json
#{
# "hello": "world"
#}
#
AWS_EVENT_MAPPING = {
'arn:aws:s3:1': 'test_settings.aws_s3_event',
'arn:aws:sns:1': 'test_settings.aws_sns_event',
'arn:aws:dynamodb:1': 'test_settings.aws_dynamodb_event',
'arn:aws:kinesis:1': 'test_settings.aws_kinesis_event',
'arn:aws:sqs:1': 'test_settings.aws_sqs_event'
}
ENVIRONMENT_VARIABLES={'testenv': 'envtest'}
AUTHORIZER_FUNCTION='test_settings.authorizer_event'
def prebuild_me():
print("This is a prebuild script!")
def callback(self):
print("this is a callback")
def aws_s3_event(event, content):
return "AWS S3 EVENT"
def aws_sns_event(event, content):
return "AWS SNS EVENT"
def aws_async_sns_event(arg1, arg2, arg3):
return "AWS ASYNC SNS EVENT"
def aws_dynamodb_event(event, content):
return "AWS DYNAMODB EVENT"
def aws_kinesis_event(event, content):
return "AWS KINESIS EVENT"
def aws_sqs_event(event, content):
return "AWS SQS EVENT"
def authorizer_event(event, content):
return "AUTHORIZER_EVENT"
def command():
print("command")
| mit | -1,091,853,218,482,797,700 | 18.485294 | 61 | 0.676981 | false | 2.760417 | true | false | false |
BayesianLogic/blog | tools/blog_py_lexer/blog/lexer.py | 1 | 3373 | from pygments.lexer import RegexLexer, bygroups, include
from pygments.token import *
class BlogLexer(RegexLexer):
name = 'BLOG'
aliases = ['blog']
filenames = ['*.blog', '*.dblog']
operators = ['\\-\\>', ':', '\\+', '\\-', '\\*', '/', '\\[', ']',
'\\{', '}', '!', '\\<', '\\>', '\\<=', '\\>=', '==', '!=',
'&', '\\|', '=\\>', '#', '\\^', '%', '@']
wordops = ['isEmptyString', 'succ', 'pred',
'prev', 'inv', 'det', 'min', 'max',
'round', 'transpose', 'sin', 'cos', 'tan',
'atan2', 'sum', 'vstack', 'eye', 'zeros',
'ones', 'toInt', 'toReal', 'diag', 'repmat',
'hstack', 'vstack', 'pi', 'trace']
deliminators = [',', ';', '\\(', '\\)', '=', '~']
keywords = ['extern','import','fixed','distinct','random','origin',
'param','type', 'forall', 'exists', 'obs', 'query',
'if', 'then', 'else', 'for', 'case', 'in']
types = ['Integer','Real','Boolean','NaturalNum','List','Map',
'Timestep','RealMatrix','IntegerMatrix']
distribs = ['TabularCPD', 'Distribution','Gaussian',
'UniformChoice', 'MultivarGaussian', 'Poisson',
'Bernoulli', 'BooleanDistrib', 'Binomial', 'Beta', 'BoundedGenometric',
'Categorical', 'Dirichlet', 'EqualsCPD', 'Gamma', 'Geometric', 'Iota',
'LinearGaussian', 'MixtureDistrib', 'Multinomial',
'NegativeBinamial', 'RoundedLogNormal', 'TabularInterp',
'UniformVector', 'UnivarGaussian',
'Exponential', 'UniformInt', 'UniformReal']
idname_reg = '[a-zA-Z_]\\w*'
def gen_regex(ops):
return "|".join(ops)
tokens = {
'root' : [
(r'//.*?\n', Comment.Single),
(r'(?s)/\*.*?\*/', Comment.Multiline),
('('+idname_reg+')(\\()', bygroups(Name.Function, Punctuation)),
('('+gen_regex(types)+')\\b', Keyword.Type),
('('+gen_regex(distribs)+')\\b', Name.Class),
('('+gen_regex(keywords)+')\\b', Keyword),
(gen_regex(operators), Operator),
('(' + gen_regex(wordops) +')\\b', Operator.Word),
('(true|false|null)\\b', Keyword.Constant),
('('+idname_reg+')\\b', Name),
(r'"(\\\\|\\"|[^"])*"', String),
(gen_regex(deliminators), Punctuation),
(r'\d*\.\d+', Number.Float),
(r'\d+', Number.Integer),
(r'\s+', Text),
]
}
def run_tests():
tests = [
"type Person;",
"distinct Person Alice, Bob, P[100];",
"random Real x1_x2x3 ~ Gaussian(0, 1);\nrandom Real y ~ Gaussian(x, 1);",
"random type0 funcname(type1 x) =expression;\nrandom type0 funcname(type1 x) dependency-expression;",
"random NaturalNum x ~ Poisson(a);",
"param Real a: 0 < a & a < 10 ;"
"random Real funcname(type1 x);",
"1.0 + 2.0 * 3.0 - 4.0",
"Twice( 10.0 ) * 5.5",
"fixed NaturalNum[] c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];",
"fixed NaturalNum[][] table = [1, 2, 3; 4, 5, 6];",
"fixed List<NaturalNum> a = List(1, 2, 3, 4, 5, 6);",
"fixed Map<Boolean, Real> map1 = {true -> 0.3, false -> 0.7};",
"Categorical<Boolean> cpd1 =Categorical({true -> 0.3, false -> 0.7});",
"List",
"/*abc */",
"""
/* Evidence for the Hidden Markov Model.
*/
"""
]
lexer = BlogLexer()
for test in tests:
print(test)
for token in (lexer.get_tokens(test)):
print(token)
if __name__ == '__main__':
run_tests()
| bsd-3-clause | 4,312,323,977,143,371,000 | 37.770115 | 105 | 0.501927 | false | 3.140596 | true | false | false |
haematologic/cellcounter | cellcounter/accounts/views.py | 1 | 7496 | from braces.views import LoginRequiredMixin
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.forms import SetPasswordForm
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.utils.http import urlsafe_base64_decode
from django.utils.safestring import mark_safe
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import FormView, UpdateView, DetailView, DeleteView
from ratelimit.exceptions import Ratelimited
from ratelimit.mixins import RatelimitMixin
from ratelimit.utils import is_ratelimited
from .forms import EmailUserCreationForm, PasswordResetForm
class RateLimitedFormView(FormView):
ratelimit_key = 'ip'
ratelimit_block = True
ratelimit_rate = '1/h'
ratelimit_group = None
def dispatch(self, *args, **kwargs):
ratelimited = is_ratelimited(request=self.request,
group=self.ratelimit_group,
key=self.ratelimit_key,
rate=self.ratelimit_rate,
increment=False)
if ratelimited and self.ratelimit_block:
raise Ratelimited()
return super(RateLimitedFormView, self).dispatch(*args, **kwargs)
class RegistrationView(RateLimitedFormView):
template_name = 'accounts/register.html'
form_class = EmailUserCreationForm
ratelimit_group = 'registration'
def form_valid(self, form):
user = form.save()
messages.success(self.request,
mark_safe(
"Successfully registered, you are now logged in! <a href='%s'>View your profile</a>" %
reverse('user-detail', kwargs={'pk': user.id})))
user = authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password1'])
login(self.request, user)
is_ratelimited(request=self.request, group=self.ratelimit_group, key=self.ratelimit_key,
rate=self.ratelimit_rate, increment=True)
return super(RegistrationView, self).form_valid(form)
def get_success_url(self):
return reverse('new_count')
class PasswordChangeView(LoginRequiredMixin, FormView):
template_name = 'accounts/password_change.html'
form_class = PasswordChangeForm
def get_form_kwargs(self):
kwargs = super(PasswordChangeView, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
def form_valid(self, form):
form.save()
messages.success(self.request, "Password changed successfully")
return HttpResponseRedirect(reverse('new_count'))
class UserDetailView(LoginRequiredMixin, DetailView):
model = User
context_object_name = 'user_detail'
template_name = 'accounts/user_detail.html'
def get_object(self, queryset=None):
if self.request.user.id == int(self.kwargs['pk']):
return super(UserDetailView, self).get_object()
else:
raise PermissionDenied
def get_context_data(self, **kwargs):
context = super(UserDetailView, self).get_context_data(**kwargs)
context['keyboards'] = self.object.keyboard_set.all().order_by('-is_primary')
return context
class UserDeleteView(LoginRequiredMixin, DeleteView):
model = User
context_object_name = 'user_object'
template_name = 'accounts/user_check_delete.html'
def get_object(self, queryset=None):
if self.request.user.id == int(self.kwargs['pk']):
return super(UserDeleteView, self).get_object()
else:
raise PermissionDenied
def get_success_url(self):
messages.success(self.request, "User account deleted")
return reverse('new_count')
class UserUpdateView(LoginRequiredMixin, UpdateView):
model = User
fields = ['first_name', 'last_name', 'email', ]
template_name = 'accounts/user_update.html'
def get_object(self, queryset=None):
if self.request.user.id == int(self.kwargs['pk']):
return super(UserUpdateView, self).get_object()
else:
raise PermissionDenied
def get_success_url(self):
messages.success(self.request, "User details updated")
return reverse('user-detail', kwargs={'pk': self.kwargs['pk']})
class PasswordResetView(RatelimitMixin, FormView):
template_name = 'accounts/reset_form.html'
form_class = PasswordResetForm
ratelimit_rate = '5/h'
ratelimit_group = 'pwdreset'
ratelimit_key = 'ip'
ratelimit_block = True
def form_valid(self, form):
form.save(request=self.request)
messages.success(self.request, 'Reset email sent')
return super(PasswordResetView, self).form_valid(form)
def form_invalid(self, form):
"""Don't expose form errors to the user"""
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse('new_count')
class PasswordResetConfirmView(FormView):
template_name = 'accounts/reset_confirm.html'
form_class = SetPasswordForm
@method_decorator(sensitive_post_parameters())
def dispatch(self, request, *args, **kwargs):
return super(PasswordResetConfirmView, self).dispatch(request, *args, **kwargs)
@staticmethod
def valid_user(uidb64):
try:
uid = urlsafe_base64_decode(uidb64)
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
return None
return user
@staticmethod
def valid_token(user, token):
if user is not None:
return default_token_generator.check_token(user, token)
else:
return False
def _valid_inputs(self, uidb64, token):
self.user_object = self.valid_user(uidb64)
return self.valid_token(self.user_object, token)
def get(self, request, *args, **kwargs):
if self._valid_inputs(self.kwargs['uidb64'], self.kwargs['token']):
form = self.get_form(self.get_form_class())
return self.render_to_response(self.get_context_data(form=form, validlink=True))
else:
return self.render_to_response(self.get_context_data(validlink=False))
def post(self, request, *args, **kwargs):
if self._valid_inputs(self.kwargs['uidb64'], self.kwargs['token']):
return super(PasswordResetConfirmView, self).post(request, *args, **kwargs)
else:
return self.render_to_response(self.get_context_data(validlink=False))
def get_form_kwargs(self):
kwargs = super(PasswordResetConfirmView, self).get_form_kwargs()
kwargs['user'] = self.user_object
return kwargs
def form_valid(self, form):
form.save()
messages.success(self.request, 'Password reset successfully')
return HttpResponseRedirect(reverse('new_count'))
def rate_limited(request, exception):
messages.error(request, 'You have been rate limited')
return HttpResponseRedirect(reverse('new_count'))
| mit | -4,984,765,481,467,892,000 | 36.293532 | 115 | 0.665555 | false | 4.082789 | false | false | false |
uclouvain/osis_louvain | assessments/forms/score_file.py | 1 | 1880 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2018 Université catholique de Louvain (http://www.uclouvain.be)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
##############################################################################
from django import forms
from django.utils.translation import ugettext_lazy as _
class ScoreFileForm(forms.Form):
file = forms.FileField(error_messages={'required': _('no_file_submitted')})
def clean_file(self):
file = self.cleaned_data['file']
content_type = file.content_type.split('/')[1]
valid_content_type = 'vnd.openxmlformats-officedocument.spreadsheetml.sheet' in content_type
if ".xlsx" not in file.name or not valid_content_type:
self.add_error('file', forms.ValidationError(_('file_must_be_xlsx'), code='invalid'))
return file
| agpl-3.0 | -502,586,721,529,759,000 | 47.179487 | 100 | 0.654604 | false | 4.075922 | false | false | false |
hsharsha/perfrunner | perfrunner/tests/functional.py | 1 | 1852 | import unittest
from perfrunner.__main__ import get_options
from perfrunner.helpers.memcached import MemcachedHelper
from perfrunner.helpers.remote import RemoteHelper
from perfrunner.helpers.rest import RestHelper
from perfrunner.settings import ClusterSpec, TestConfig
from perfrunner.tests import TargetIterator
class FunctionalTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
options, _args = get_options()
override = \
_args and (arg.split('.') for arg in ' '.join(_args).split(','))
self.cluster_spec = ClusterSpec()
self.cluster_spec.parse(options.cluster_spec_fname)
self.test_config = TestConfig()
self.test_config.parse(options.test_config_fname, override)
self.target_iterator = TargetIterator(self.cluster_spec,
self.test_config)
self.memcached = MemcachedHelper(self.test_config)
self.remote = RemoteHelper(self.cluster_spec, self.test_config)
self.rest = RestHelper(self.cluster_spec)
super(FunctionalTest, self).__init__(*args, **kwargs)
class MemcachedTests(FunctionalTest):
def test_num_threads(self):
expected_threads = self.test_config.cluster.num_cpus
if expected_threads is None:
cores = self.remote.detect_number_cores()
expected_threads = int(0.75 * cores)
for target in self.target_iterator:
host = target.node.split(':')[0]
port = self.rest.get_memcached_port(target.node)
stats = self.memcached.get_stats(host, port, target.bucket,
stats='')
num_threads = int(stats['threads'])
self.assertEqual(num_threads, expected_threads)
if __name__ == '__main__':
unittest.main(argv=['functional.py'])
| apache-2.0 | 919,988,435,475,458,000 | 37.583333 | 76 | 0.636609 | false | 4.124722 | true | false | false |
mfasq1Monash/FIT3140 | interpreter.py | 1 | 6491 | '''
Author: Michael Asquith, Aaron Gruneklee
Created: 2014.12.08
Last Modified: 2014.12.23
Interpreter for a simple functional programming language.
Access with interpret(command)
Based on Peter Norvig's Lispy interpreter, http://norvig.com/lispy.html
'''
import math, operator as op
from robotio import RobotIO
Symbol = str
class VariableAlreadyPresentException(Exception):
pass
class FunctionAlreadyDefinedException(Exception):
pass
class VariableAlreadySetException(Exception):
pass
class VariableNotFoundException(Exception):
pass
class InterpretedList(list):
pass
class Procedure(object):
"""A user-defined method for the interpreter"""
def __init__(self, parms, stats, env, inter):
self.parameters = parms
self.statements = stats
self.environment = env
self.interpreter = inter
def __call__(self, *args):
localVariables = Environment(self.parameters, args, self.environment)
return self.interpreter.evaluate(self.statements, localVariables)
class Environment(dict):
"""A set of variables for the interpreter or a method within it."""
def __init__(self, parms=(), expressions=(), outer=None):
"""When evaluating, procedures will pass in their parameters"""
self.update(zip(parms, expressions))
self.outer = outer
def find(self, variable):
"""Returns the lowest level Environment which has variable"""
if variable in self:
return self
try:
return self.outer.find(variable)
except AttributeError:
raise VariableNotFoundException
def add_new(self, variable, value):
"""Adds a new definition to the environment. If the variable is already present, raises a KeyAlreadyPresentError"""
if variable in self:
raise(VariableAlreadyPresentException)
self[variable] = value
class Interpreter:
"""After initialising an interpreter, run expressions by calling interpret.
"""
def __init__(self, newRobotIO):
"""Creates an interpreter with standard math operations and variables.
Can send input/output to newRobotIO
"""
self.global_environment = self.standard_environment()
self.robotio = newRobotIO
def interpret(self, code):
"""Parses and executes code a string in the form of:
(method_name argument1 argument2)
Arguments which are expressions must be placed in brackets.
Arguments which are not expressions must not be placed in brackets.
"""
return self.evaluate(self.parse(code))
def parse(self, code):
"Read an expression from a string."
return self.read_from_tokens(self.tokenize(code))
def tokenize(self, s):
"Convert a string into a list of tokens."
return s.replace('(',' ( ').replace(')',' ) ').split()
def read_from_tokens(self, tokens):
"Read an expression from a sequence of tokens."
if len(tokens) == 0:
raise SyntaxError('unexpected EOF while reading')
token = tokens.pop(0)
if '(' == token:
L = []
while tokens[0] != ')':
L.append(self.read_from_tokens(tokens))
tokens.pop(0) # pop off ')'
return L
elif ')' == token:
raise SyntaxError('unexpected )')
else:
return self.atom(token)
def atom(self, token):
"Numbers become numbers, booleans become booleans, everything else become symbols."
try:
return int(token)
except ValueError:
if token.lower() == 'true':
return True
elif token.lower() == 'false':
return False
else:
return Symbol(token)
def standard_environment(self):
"Creates the base variable environment"
env = Environment()
env.update(vars(math))
env.update({
'+':op.add, '-':op.sub, '*':op.mul, '/':op.div,
'>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq,
'define':None, 'if':None, 'set':None, 'comment':None,
'%': lambda x,y: abs(x % y),
'and': lambda x,y: x and y,
'or': lambda x,y: x or y,
'not': lambda x: not x,
'move': lambda x: self.robotio.move(x),
'turn': lambda x: self.robotio.turn(x),
'detect-wall': lambda x: self.robotio.detect_wall(x),
'detect-goal': lambda x: self.robotio.detect_goal(x),
'[]': InterpretedList(),
'build': lambda x,y: InterpretedList([x] + y),
'head': lambda x: x[0],
'tail': lambda x: InterpretedList(x[1:])
})
return env
def evaluate(self, x, env=None):
if env == None:
env = self.global_environment
# If x is a list, must be evaluating a method
if isinstance(x, list):
if isinstance(x, InterpretedList):
return x
method = x.pop(0)
# Defines a function
if method == 'define':
try:
self.global_environment.add_new(x[0], Procedure(x[1], x[2], env, self))
except VariableAlreadyPresentException:
raise FunctionAlreadyDefinedException
# If statement. [Test, consequences, alternative]
elif method == 'if':
if self.evaluate(x[0]):
return self.evaluate(x[1])
return self.evaluate(x[2])
# Sets a variable
elif method == 'set':
try:
env.add_new(x[0], self.evaluate(x[1],env))
except VariableAlreadyPresentException:
raise VariableAlreadySetException
return
elif method == 'comment':
return
# Executes all other functions
else:
method = self.evaluate(method, self.global_environment)
args = [self.evaluate(variable, env) for variable in x]
return method(*args)
elif isinstance(x, Symbol):
return self.evaluate(env.find(x)[x])
else:
return x
| mit | 5,197,515,918,788,058,000 | 33.343915 | 123 | 0.558312 | false | 4.412644 | false | false | false |
scottrice/Ice | ice/tasks/engine.py | 1 | 1118 | # encoding: utf-8
import os
from pysteam import paths as steam_paths
from pysteam import shortcuts
from pysteam import steam as steam_module
from ice import backups
from ice import configuration
from ice import consoles
from ice import emulators
from ice import paths
from ice import settings
from ice.logs import logger
from ice.persistence.config_file_backing_store import ConfigFileBackingStore
class TaskEngine(object):
def __init__(self, steam):
self.steam = steam
logger.debug("Initializing Ice")
# We want to ignore the anonymous context, cause theres no reason to sync
# ROMs for it since you cant log in as said user.
is_user_context = lambda context: context.user_id != 'anonymous'
self.users = filter(is_user_context, steam_module.local_user_contexts(self.steam))
def run(self, tasks, app_settings, dry_run=False):
if self.steam is None:
logger.error("Cannot run Ice because Steam doesn't appear to be installed")
return
logger.info("=========== Starting Ice ===========")
for task in tasks:
task(app_settings, self.users, dry_run=dry_run)
| mit | 4,875,944,689,318,500,000 | 29.216216 | 86 | 0.723614 | false | 3.56051 | false | false | false |
TheWitchers/Team | TestingArea/TESTZONE_methods.py | 1 | 1111 | __author__ = 'dvir'
import tkFileDialog
import sqlite3
conn = sqlite3.connect(tkFileDialog.askopenfilename())
c = conn.cursor()
# using example db
def ex_show_purch(price):
l = []
for row in c.execute("SELECT symbol FROM stocks WHERE price > " + str(price) + ""):
print row
l.append(row)
print l
return l
ex_show_purch(raw_input("Enter Price: "))
# for project db
def show_purch(name):
l = []
for row in c.execute("SELECT * FROM Purchaseses WHERE nickname = '" + name + "'"):
print row
l.append(row)
print l
return l
def correct_user(id, pas):
if len(c.execute("SELECT * FROM Users WHERE username = '" + id + "' AND password = '" + pas + "'")) > 0:
print "user exists"
else:
print "user does not exist"
def has_inf(col, tbl, info):
if len(c.execute(
"SELECT '" + col + "' FROM Users WHERE username = '" + id + "' AND '" + col + "' = '" + info + "'")) > 0:
print col + "already exists"
else:
print col + " is OK"
| gpl-2.0 | 6,712,637,197,793,229,000 | 24.25 | 181 | 0.531953 | false | 3.549521 | false | false | false |
MagicStack/asyncpg | asyncpg/transaction.py | 1 | 8297 | # Copyright (C) 2016-present the asyncpg authors and contributors
# <see AUTHORS file>
#
# This module is part of asyncpg and is released under
# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0
import enum
from . import connresource
from . import exceptions as apg_errors
class TransactionState(enum.Enum):
NEW = 0
STARTED = 1
COMMITTED = 2
ROLLEDBACK = 3
FAILED = 4
ISOLATION_LEVELS = {'read_committed', 'serializable', 'repeatable_read'}
ISOLATION_LEVELS_BY_VALUE = {
'read committed': 'read_committed',
'serializable': 'serializable',
'repeatable read': 'repeatable_read',
}
class Transaction(connresource.ConnectionResource):
"""Represents a transaction or savepoint block.
Transactions are created by calling the
:meth:`Connection.transaction() <connection.Connection.transaction>`
function.
"""
__slots__ = ('_connection', '_isolation', '_readonly', '_deferrable',
'_state', '_nested', '_id', '_managed')
def __init__(self, connection, isolation, readonly, deferrable):
super().__init__(connection)
if isolation and isolation not in ISOLATION_LEVELS:
raise ValueError(
'isolation is expected to be either of {}, '
'got {!r}'.format(ISOLATION_LEVELS, isolation))
self._isolation = isolation
self._readonly = readonly
self._deferrable = deferrable
self._state = TransactionState.NEW
self._nested = False
self._id = None
self._managed = False
async def __aenter__(self):
if self._managed:
raise apg_errors.InterfaceError(
'cannot enter context: already in an `async with` block')
self._managed = True
await self.start()
async def __aexit__(self, extype, ex, tb):
try:
self._check_conn_validity('__aexit__')
except apg_errors.InterfaceError:
if extype is GeneratorExit:
# When a PoolAcquireContext is being exited, and there
# is an open transaction in an async generator that has
# not been iterated fully, there is a possibility that
# Pool.release() would race with this __aexit__(), since
# both would be in concurrent tasks. In such case we
# yield to Pool.release() to do the ROLLBACK for us.
# See https://github.com/MagicStack/asyncpg/issues/232
# for an example.
return
else:
raise
try:
if extype is not None:
await self.__rollback()
else:
await self.__commit()
finally:
self._managed = False
@connresource.guarded
async def start(self):
"""Enter the transaction or savepoint block."""
self.__check_state_base('start')
if self._state is TransactionState.STARTED:
raise apg_errors.InterfaceError(
'cannot start; the transaction is already started')
con = self._connection
if con._top_xact is None:
if con._protocol.is_in_transaction():
raise apg_errors.InterfaceError(
'cannot use Connection.transaction() in '
'a manually started transaction')
con._top_xact = self
else:
# Nested transaction block
if self._isolation:
top_xact_isolation = con._top_xact._isolation
if top_xact_isolation is None:
top_xact_isolation = ISOLATION_LEVELS_BY_VALUE[
await self._connection.fetchval(
'SHOW transaction_isolation;')]
if self._isolation != top_xact_isolation:
raise apg_errors.InterfaceError(
'nested transaction has a different isolation level: '
'current {!r} != outer {!r}'.format(
self._isolation, top_xact_isolation))
self._nested = True
if self._nested:
self._id = con._get_unique_id('savepoint')
query = 'SAVEPOINT {};'.format(self._id)
else:
query = 'BEGIN'
if self._isolation == 'read_committed':
query += ' ISOLATION LEVEL READ COMMITTED'
elif self._isolation == 'repeatable_read':
query += ' ISOLATION LEVEL REPEATABLE READ'
elif self._isolation == 'serializable':
query += ' ISOLATION LEVEL SERIALIZABLE'
if self._readonly:
query += ' READ ONLY'
if self._deferrable:
query += ' DEFERRABLE'
query += ';'
try:
await self._connection.execute(query)
except BaseException:
self._state = TransactionState.FAILED
raise
else:
self._state = TransactionState.STARTED
def __check_state_base(self, opname):
if self._state is TransactionState.COMMITTED:
raise apg_errors.InterfaceError(
'cannot {}; the transaction is already committed'.format(
opname))
if self._state is TransactionState.ROLLEDBACK:
raise apg_errors.InterfaceError(
'cannot {}; the transaction is already rolled back'.format(
opname))
if self._state is TransactionState.FAILED:
raise apg_errors.InterfaceError(
'cannot {}; the transaction is in error state'.format(
opname))
def __check_state(self, opname):
if self._state is not TransactionState.STARTED:
if self._state is TransactionState.NEW:
raise apg_errors.InterfaceError(
'cannot {}; the transaction is not yet started'.format(
opname))
self.__check_state_base(opname)
async def __commit(self):
self.__check_state('commit')
if self._connection._top_xact is self:
self._connection._top_xact = None
if self._nested:
query = 'RELEASE SAVEPOINT {};'.format(self._id)
else:
query = 'COMMIT;'
try:
await self._connection.execute(query)
except BaseException:
self._state = TransactionState.FAILED
raise
else:
self._state = TransactionState.COMMITTED
async def __rollback(self):
self.__check_state('rollback')
if self._connection._top_xact is self:
self._connection._top_xact = None
if self._nested:
query = 'ROLLBACK TO {};'.format(self._id)
else:
query = 'ROLLBACK;'
try:
await self._connection.execute(query)
except BaseException:
self._state = TransactionState.FAILED
raise
else:
self._state = TransactionState.ROLLEDBACK
@connresource.guarded
async def commit(self):
"""Exit the transaction or savepoint block and commit changes."""
if self._managed:
raise apg_errors.InterfaceError(
'cannot manually commit from within an `async with` block')
await self.__commit()
@connresource.guarded
async def rollback(self):
"""Exit the transaction or savepoint block and rollback changes."""
if self._managed:
raise apg_errors.InterfaceError(
'cannot manually rollback from within an `async with` block')
await self.__rollback()
def __repr__(self):
attrs = []
attrs.append('state:{}'.format(self._state.name.lower()))
if self._isolation is not None:
attrs.append(self._isolation)
if self._readonly:
attrs.append('readonly')
if self._deferrable:
attrs.append('deferrable')
if self.__class__.__module__.startswith('asyncpg.'):
mod = 'asyncpg'
else:
mod = self.__class__.__module__
return '<{}.{} {} {:#x}>'.format(
mod, self.__class__.__name__, ' '.join(attrs), id(self))
| apache-2.0 | -3,851,821,235,338,135,000 | 33.861345 | 78 | 0.556105 | false | 4.578918 | false | false | false |
turtledb/0install | zeroinstall/injector/qdom.py | 1 | 3485 | """A quick DOM implementation.
Python's xml.dom is very slow. The xml.sax module is also slow (as it imports urllib2).
This is our light-weight version.
"""
# Copyright (C) 2009, Thomas Leonard
# See the README file for details, or visit http://0install.net.
from xml.parsers import expat
import zeroinstall
from zeroinstall.injector import versions
_parsed_version = versions.parse_version(zeroinstall.version)
class Element(object):
"""An XML element.
@ivar uri: the element's namespace
@type uri: str
@ivar name: the element's localName
@type name: str
@ivar attrs: the element's attributes (key is in the form [namespace " "] localName)
@type attrs: {str: str}
@ivar childNodes: children
@type childNodes: [L{Element}]
@ivar content: the text content
@type content: str"""
__slots__ = ['uri', 'name', 'attrs', 'childNodes', 'content']
def __init__(self, uri, name, attrs):
"""@type uri: str
@type name: str
@type attrs: {str: str}"""
self.uri = uri
self.name = name
self.attrs = attrs.copy()
self.content = None
self.childNodes = []
def __str__(self):
"""@rtype: str"""
attrs = [n + '=' + self.attrs[n] for n in self.attrs]
start = '<{%s}%s %s' % (self.uri, self.name, ' '.join(attrs))
if self.childNodes:
return start + '>' + '\n'.join(map(str, self.childNodes)) + ('</%s>' % (self.name))
elif self.content:
return start + '>' + self.content + ('</%s>' % (self.name))
else:
return start + '/>'
def getAttribute(self, name):
"""@type name: str
@rtype: str"""
return self.attrs.get(name, None)
class QSAXhandler(object):
"""SAXHandler that builds a tree of L{Element}s"""
def __init__(self, filter_for_version = False):
"""@param filter_for_version: skip elements if their if-0install-version attribute doesn't match L{zeroinstall.version} (since 1.13).
@type filter_for_version: bool
@rtype: bool"""
self.stack = []
if filter_for_version:
self.filter_range = lambda expr: versions.parse_version_expression(expr)(_parsed_version)
else:
self.filter_range = lambda x: True
def startElementNS(self, fullname, attrs):
"""@type fullname: str
@type attrs: {str: str}"""
split = fullname.split(' ', 1)
if len(split) == 2:
self.stack.append(Element(split[0], split[1], attrs))
else:
self.stack.append(Element(None, fullname, attrs))
self.contents = ''
def characters(self, data):
"""@type data: str"""
self.contents += data
def endElementNS(self, name):
"""@type name: str"""
contents = self.contents.strip()
self.stack[-1].content = contents
self.contents = ''
new = self.stack.pop()
if self.stack:
target_versions = new.attrs.get('if-0install-version')
if target_versions and not self.filter_range(target_versions):
return
self.stack[-1].childNodes.append(new)
else:
self.doc = new
def parse(source, filter_for_version = False):
"""Parse an XML stream into a tree of L{Element}s.
@param source: data to parse
@type source: file
@param filter_for_version: skip elements if their if-0install-version attribute doesn't match L{zeroinstall.version} (since 1.13).
@type filter_for_version: bool
@return: the root
@rtype: L{Element}"""
handler = QSAXhandler(filter_for_version)
parser = expat.ParserCreate(namespace_separator = ' ')
parser.StartElementHandler = handler.startElementNS
parser.EndElementHandler = handler.endElementNS
parser.CharacterDataHandler = handler.characters
parser.ParseFile(source)
return handler.doc
| lgpl-2.1 | -237,805,872,924,645,440 | 29.840708 | 135 | 0.682927 | false | 3.119964 | false | false | false |
bandit145/ans-between | src/dictops.py | 1 | 1886 | #TODO: allow missing params and args lists to pass tests
from src import logging
class dict_mgm:
#creates ansible command to run
def make_play(data,db_data,location):
if dict_mgm.data_check(data, db_data) == 'OK':
command = 'ansible-playbook {location}'.format(location=location)
#did and incredi bad if else thing
logging.debug(data.keys())
command+=data['name']+' '
if 'params' in data.keys():
command+= dict_mgm.sort_params(data['params'])
if 'args' in data.keys():
command+= dict_mgm.sort_args(data['args'])
if 'password' in data.keys():
password = data['password']
else:
password = None
logging.debug(command)
logging.debug(password)
return command, password
else:
return 'Error', None
#check integrity of submitted data compared to its schema model
def data_check(data,db_data):
logging.debug(data)
logging.debug(db_data)
if len(data) != len(db_data):
logging.debug('triggered 1')
return 'Error'
if data.keys() != db_data.keys():
logging.debug('triggered 2')
return 'Error'
if len(data.values()) != len(db_data.values()):
logging.debug('triggered 3')
return 'Error'
#for playbooks that have no params/args
try:
if len(data['params']) != len(db_data['params']):
logging.debug('triggered 4')
return 'Error'
except KeyError:
pass
try:
if len(data['args']) != len(db_data['args']):
logging.debug('triggered 5')
return 'Error'
except KeyError:
pass
logging.debug('OK')
return 'OK'
def sort_params(params):#deals with param dics
command = ''
for item in params:
keys= list(item.keys())
values= list(item.values())
logging.debug(keys)
logging.debug(values)
command+=keys[0]+' '+values[0]+' '
return command
def sort_args(args): #deals with args list
command = ''
for arg in args:
command+= arg+' '
return command | mit | -4,789,335,474,906,966,000 | 25.208333 | 68 | 0.656416 | false | 3.107084 | false | false | false |
phense/check_duplicate_files | check_duplicate_files.py | 1 | 21660 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""check_duplicate_files.py
Finds all duplicate files in given directories using a hash-algorithm.
After scanning the filesystem for possible duplicate files (all files with a unique
filesize are dismissed, except for Images when selecting the perceptual hash
algorithm). All possible candidate duplicate files are hashed. With pre-filtering,
this module is extremely fast on large file-sets since only a handful of files
need to actually hbe ashed.
Standard use: python3 check_duplicate_files -i /some/folder ./out.txt
"""
# FEATURE(zyrkon): ignore/include win/linux/mac hidden file
# FEATURE(zyrkon): implement multiprocessor for hashing
# FEATURE(zyrkon): find broken symbolic links
# FEATURE(zyrkon): find empty files and directories
# FEATURE(zyrkon): --size 20M-1G to find files between 20mb and 1gb (example)
# FEATURE(zyrkon): maybe a GUI
__author__ = 'Peter Hense ([email protected])'
__copyright__ = 'Copyright (c) 2015, Peter Hense'
__license__ = 'Apache License Version 2.0'
__credits__ = '' # ['List', 'of', 'programmers']
__status__ = 'Development' # Prototype / Development / Production
__version__ = '0.8'
import os
import sys
if sys.version_info < (3, 0):
sys.stdout.write("Sorry, requires Python 3.x, not Python 2.x\n")
sys.exit(1)
import codecs
import datetime
import hashlib
import json
import operator
import signal
from argparse import ArgumentParser
from argparse import ArgumentTypeError
from collections import defaultdict
from tqdm import *
from stat import *
try:
from PIL import Image # Pillow (modern PIL fork)
except ImportError:
IMG_LIB_ERROR = True
else:
IMG_LIB_ERROR = False
FILEREADERROR = 255
def generate_hashes(filelist, image_list, hashtype, pHash):
""" Main-Module for handling all File-Hashing and saving the hash-results
Args:
filelist: List of file-paths to REGULAR FILES to run a normal hash-algorithm on
image_list: List of file-paths of images to run a perceptual hash-algorithm on
hashtype: hash-algorithm to use for normal files (default=md5)
pHash: boolean switch to activate perceptual image-hashing
Returns:
d_list_hash: dictionary with lists of files sorted by hash-value (key)
errorlist: list of files that could not be accessed / read
"""
d_list_hash = defaultdict(list)
errorlist = []
for file_path in tqdm(filelist, 'hashing', None, True):
hash = _hash(file_path, hashtype)
if hash != FILEREADERROR:
d_list_hash[hash].append(file_path)
else:
errorlist.append(file_path)
if pHash: # perceptual image hashing
d_list_hash_img = defaultdict(list)
for file_path in tqdm(image_list, 'hashing images:', None, True):
hash = _perceptive_hash(file_path)
if hash != FILEREADERROR:
d_list_hash_img[hash].append(file_path)
else:
errorlist.append(file_path)
# calculate hamming-distance between all image-hashes to find
# outliners (hamming distance of two perceptual hashes < 4 means the images
# are basically the same)
index_list = [key for key in d_list_hash_img]
deleted_index_keys = []
for hash1 in tqdm(index_list, 'calculating', None, True):
if hash1 in deleted_index_keys:
continue
for hash2 in index_list:
if hash1 == hash2:
continue # same entry in list
if hash2 in deleted_index_keys:
continue
if _hamming_distance(hash1, hash2) < 4:
d_list_hash_img[hash1] += d_list_hash_img[hash2]
del d_list_hash_img[hash2]
deleted_index_keys.append(hash2)
# Filter out all unique entries from our resultset
_delete_unique_entries(d_list_hash)
if pHash:
_delete_unique_entries(d_list_hash_img)
d_list_hash.update(d_list_hash_img)
return d_list_hash, errorlist
def _perceptive_hash(file_path, hash_size = 8):
"""Calculates a hash-value from an image
Conversion uses a resized, grayscaled pixel-array of the image, converting
the pixel-array to a number-array (differences between neighboring pixels)
and finally converting these values to a hex-string of length hash_size
Args:
file_path: Path to an Image File
hash_size: Size of the generated hash string
Returns:
hash_string: generated hash string
"""
# if memory consumption is to high for many images, it is posisble to use
# with open (file_path, 'rb') as f:
# image = Image.open(f)
# ...
# del image
try:
image = Image.open(file_path)
except:
return FILEREADERROR
# Grayscale and shrink the image in one step
image = image.convert('L').resize((hash_size + 1, hash_size), Image.ANTIALIAS)
pixels = list(image.getdata())
# Compage adjacent pixels
difference = []
for row in range(hash_size):
for col in range(hash_size):
pixel_left = image.getpixel((col, row))
pixel_right = image.getpixel((col +1, row))
difference.append(pixel_left > pixel_right)
# Convert binary array to hexadecimal string
decimal_value = 0
hex_string = []
for index, value in enumerate(difference):
if value:
decimal_value += 2**(index % 8)
if (index % 8) == 7:
hex_string.append(hex(decimal_value)[2:].rjust(2, '0'))
decimal_value = 0
return ''.join(hex_string)
def _hash(file_path, hashtype):
"""Uses a specified standard hash-algorithm to hash a regular file
Args:
file_path: file_path to a regular file that can be hashed
hashtype: version of hash-algorithm, default = md5
Returns:
hash: hash-string of the hashed file
Raises:
Returns global const FILEREADERROR on IOError
"""
try:
with open(file_path, 'rb') as f:
contents = f.read()
except:
return FILEREADERROR
hasher = getattr(hashlib, hashtype.lower(), hashlib.md5)
return hasher(contents).hexdigest()
def _hamming_distance(string1, string2):
""" Calculates the Hamming Distance of two strings, fast version
Args:
string1, string2: two strings of the same length
Returns:
Integer describing the Hamming Distance of the input strings
"""
assert len(string1) == len(string2)
ne = operator.ne # faster than '!=' and 'str.__ne__'
return sum(map(ne, string1, string2))
def scan_directories(directories, pHash):
""" creates file-lists from given directories
Recursively walks the given directories and their subdirectories, checking
all including files and their file-sizes. These are saved inside a dictionary
and pre-filtered by filesize. Optional separate handling of image-files.
Args:
directories: List of directories to crawl
pHash: boolean switch to active separate handling of image-files
Returns:
prefiltered_files: List of files with their file-paths
images: List of image-files if pHash is set, else an empty list
errorlist: List of files that could not be accessed
"""
extensions = ('.jpg', '.jpeg', '.png', '.bmp')
d_list_filesize = defaultdict(list)
images = []
errorlist = []
count = 0
print('Scanning directories...')
# code could be a lot smaller with `if pHash` inside the innermost loop
# it would also lead to a LOT of unnessary checking
if not pHash: # use normal hash on all files
for root_dir in directories:
for path, subdirList, fileList in os.walk(root_dir):
for fname in fileList:
qualified_filename = os.path.join(path, fname)
try: # denied permission for os.stat
st = os.stat(qualified_filename)
if S_ISREG(st.st_mode):
d_list_filesize[st.st_size].append(qualified_filename)
count += 1
except:
errorlist.append(qualified_filename)
count += 1
else: # split list of normal- and image-files
for root_dir in directories:
for path, subdirList, fileList in os.walk(root_dir):
for fname in fileList:
qualified_filename = os.path.join(path, fname)
if fname.endswith(extensions):
images.append(qualified_filename)
count += 1
else:
try:
st = os.stat(qualified_filename)
if S_ISREG(st.st_mode):
d_list_filesize[st.st_size].append(qualified_filename)
count += 1
except:
errorlist.append(qualified_filename)
count += 1
# Statistic
print('\nFiles found: %s' % count)
# pre-filter all files with unique filesize
# this is where we need the dictionary
_delete_unique_entries(d_list_filesize)
# put all filtered files in a list for easier handling
prefiltered_files = [path for paths in d_list_filesize.values() for path in paths]
# Statistic
print('Possible candidates: %s\n' % (prefiltered_files.__len__() + images.__len__()))
return prefiltered_files, images, errorlist
def _delete_unique_entries(dictionary):
""" removes all Lists from a dictionary that contain a single element
Args:
dictionary a dictionary of type defaultdict(set) or defaultdict(list)
"""
mark_for_delete = []
for key in dictionary:
if dictionary[key].__len__() == 1:
mark_for_delete.append(key)
for i in mark_for_delete:
del dictionary[i]
return
def write_output_text(d_list_hash, errorlist, outfile):
""" Writes result of this module in textform to a file
Args:
d_list_hash: found duplicates in form of a dictionary (key = hash-value)
outfile: the path and filename to write the output into (needs write-permission)
errorlist: list of files that could not be accessed
"""
write_errorlist = []
try:
with codecs.open(outfile, 'w', encoding='utf-8') as f:
f.write('\nThe Following File-Duplicates where found:')
f.write('\n==========================================\n')
for key in d_list_hash:
f.write('Hash: %s\n' %key)
for file_path in d_list_hash[key]:
try:
f.write('%s \n' % os.path.normcase(file_path))
except:
write_errorlist.append(file_path)
f.write('-------------------\n')
if errorlist.__len__() > 0:
f.write('\nThe Following Files could not be accessed:')
f.write('\n==========================================\n')
for error in errorlist:
try:
f.write('%s\n' % os.path.normcase(error))
except:
write_errorlist.append(error)
f.flush()
except: #IOError, UnicodeEncodeError
print('\n- Error - Could not open Output File.\n')
if write_errorlist.__len__() > 0:
print('- Error - These files could not be written to output file:\n')
for write_error in write_errorlist:
print('%s\n' % os.path.normcase(write_error))
print('(Please check your filesystem encoding)\n')
return
def write_output_bash(d_list_hash, outfile, create_link):
""" Writes result of this module as a bash script to a file
Args:
d_list_hash: found duplicates in form of a dictionary (key = hash-value)
outfile: the path and filename to write the output into (needs write-permission)
create_link: boolean switch to select, if a deleted file should be
replaced by a hardlink
"""
write_errorlist = []
try:
with codecs.open(outfile, 'w', encoding='utf-8') as f:
f.write('#!/bin/bash\n\n')
f.write('# This script is machine generated and might do harm to your\n')
f.write('# running system.\n')
f.write('# Please check this script carefully before running\n')
if create_link:
f.write('printf "replacing duplicates with hardlinks..."\n')
else:
f.write('printf "deleting duplicates..."\n')
for key in d_list_hash:
try:
original = os.path.normcase(d_list_hash[key][0])
f.write('# ------------------\n')
f.write('# Original: %s\n' % original)
for copy in d_list_hash[key][1:]:
f.write('rm %s\n' % copy)
if create_link:
f.write('ln %s %s\n' % (original, os.path.normcase(copy)))
except:
write_errorlist.append(file_path)
f.flush()
except: #IOError, UnicodeEncodeError
print('\n- Error - Could not open Output File.\n')
if write_errorlist.__len__() > 0:
print('- Error - These files could not be written to output file:\n')
for write_error in write_errorlist:
print('%s\n' % write_error)
print('(Please check your filesystem encoding)\n')
return
def write_output_win(d_list_hash, outfile, create_link):
""" Writes result of this module as a batch script to a file
Args:
d_list_hash: found duplicates in form of a dictionary (key = hash-value)
outfile: the path and filename to write the output into (needs write-permission)
create_link: boolean switch to select, if a deleted file should be
replaced by a hardlink
"""
write_errorlist = []
try:
with codecs.open(outfile, 'w', encoding='utf-8') as f:
f.write('@ECHO OFF\n\n')
f.write('REM This script is machine generated and might do harm to your\n')
f.write('REM running system.\n')
f.write('REM Please check this script carefully before running\n')
if create_link:
f.write('ECHO "replacing duplicates with hardlinks..."\n')
else:
f.write('ECHO "deleting duplicates..."\n')
for key in d_list_hash:
try:
original = os.path.normcase(d_list_hash[key][0])
f.write('REM ------------------\n')
f.write('REM Original: %s\n' % original)
for copy in d_list_hash[key][1:]:
f.write('DEL %s\n' % copy)
if create_link:
f.write('mklink /H %s %s\n' % (os.path.normcase(copy), original))
except:
write_errorlist.append(file_path)
f.flush()
except: #IOError, UnicodeEncodeError
print('\n- Error - Could not open Output File.\n')
if write_errorlist.__len__() > 0:
print('- Error - These files could not be written to output file:\n')
for write_error in write_errorlist:
print('%s\n' % write_error)
print('(Please check your filesystem encoding)\n')
return
def write_output_json(d_list_hash, outfile):
""" Writes result of this module as JSON to a file
Args:
d_list_hash: found duplicates in form of a dictionary (key = hash-value)
outfile: the path and filename to write the output into (needs write-permission)
"""
try:
with codecs.open(outfile, 'w', encoding='utf-8') as f:
json.dump(d_list_hash, f, ensure_ascii=False, indent=4)
except:
print('\n- Error - Could not write JSON Data to file')
return
def _query_yes_no(question, default="yes"):
"""User Console Interaction for Y/N Questions.
Args:
question: String containing a Question that needs User input
default: select the default answer of the question
"""
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'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
def _signal_handler(signal, frame):
sys.exit('Aborting...')
def _readable_dir(prospective_dir):
""" Checks if a given string is a valid path on the file-system
Args:
prospective_dir: file-path as String
Returns:
prospective_dir if checks are passed
Raises:
ArgumentTypeError if checks fail
"""
if not os.path.isdir(prospective_dir):
raise ArgumentTypeError('readable_dir:{0} is not a valid path'.format(prospective_dir))
if os.access(prospective_dir, os.R_OK):
return prospective_dir
else:
raise ArgumentTypeError('readable_dir:{0} is not a readable dir'.format(prospective_dir))
def main():
signal.signal(signal.SIGINT, _signal_handler)
signal.signal(signal.SIGTERM, _signal_handler)
start_time = datetime.datetime.now()
parser = ArgumentParser(description = 'Check Duplicate Files')
parser.add_argument('-i', action = 'append', dest = 'dir',
type = _readable_dir,
help = 'add directory to list for duplicate search'
)
parser.add_argument('--hash', action = 'store', dest = 'hashtype',
default = 'md5',
help = 'select hash-type (md5 (default), sha1, sha224, sha256, sha384, sha512)'
)
parser.add_argument('-p', '--perceptual-hashing', action = 'store_true',
dest = 'pHash', default = False,
help = 'enables perceptual hashing of images'
)
parser.add_argument('-o', '--output-format', action = 'store', dest = 'outformat',
default = 'text',
help = 'select output format (text, json, bash_rm, bash_link, win_del, win_link)'
)
parser.add_argument('outfile', #nargs='?',
help = 'output file for found duplicates'
)
parser.add_argument('--version', action='version',
version='%(prog)s {version}'.format(version=__version__))
args = parser.parse_args()
# disable perceptual hashing (normal hashes on all files) when PIL LIB could
# not be loaded and it is not enabled
pHash = ((not IMG_LIB_ERROR) and args.pHash)
if not pHash:
print('(Perceptual Image Scan disabled)')
# Scan all directories and find duplicates by filesize
prefiltered_filelist, images, read_errors = scan_directories(args.dir, pHash)
# Ask the user if he wants to continue, now that he knows how
# many files need to be hashed. Exclude the query-time from
# execution time
time_query = datetime.datetime.now()
if not _query_yes_no('Do you want to continue?', 'yes'):
sys.exit(0)
timedelta_query = datetime.datetime.now() - time_query # timedelta
# generate the hashed and calculate the execution time
# append possible new read-errors to the general error-list
d_list_hash = defaultdict(list)
d_list_hash, read_errors2 = generate_hashes(prefiltered_filelist, images, args.hashtype, pHash)
read_errors += read_errors2
execution_time = datetime.datetime.now() - start_time # timedelta
execution_time -= timedelta_query # timedelta
# write output
output = ['text', 'json', 'bash_rm', 'bash_link', 'win_del', 'win_link']
if args.outformat in output:
if args.outformat == 'text':
write_output_text(d_list_hash, read_errors, args.outfile)
elif args.outformat == 'json':
write_output_json(d_list_hash, args.outfile)
elif args.outformat == 'bash_rm':
write_output_bash(d_list_hash, args.outfile, False)
elif args.outformat == 'bash_link':
write_output_bash(d_list_hash, args.outfile, True)
elif args.outformat == 'win_del':
write_output_win(d_list_hash, args.outfile, False)
elif args.outformat == 'win_link':
write_output_win(d_list_hash, args.outfile, True)
else:
write_output_text(d_list_hash, read_errors, args.outfile)
print('\nExecution Time: %s.%s seconds' % (execution_time.seconds,
execution_time.microseconds))
# done
sys.exit(0)
if __name__ == '__main__':
main() | apache-2.0 | -369,360,307,060,061,250 | 34.862583 | 105 | 0.580979 | false | 4.094518 | false | false | false |
petrpulc/git-cmp | checkers/references.py | 1 | 1113 | """
Reference level checker (existence of given references or all refs/heads ans refs/tags).
"""
from common import Common
from utils import check_diff
def __filter(reference_list):
return set(reference for reference in
reference_list if reference.split('/')[1] in ('heads', 'tags'))
def check():
"""
Run the checker on references.
"""
print("=== References")
if Common.args.references is None:
o_refs = __filter(Common.original.listall_references())
n_refs = __filter(Common.new.listall_references())
check_diff(o_refs, n_refs, "References", 2)
else:
o_refs = set()
for reference in Common.args.references:
if reference not in Common.original.listall_references():
print(" {} does not exist, please report".format(reference))
exit(1)
if reference not in Common.new.listall_references():
print(" {} expected, but not found".format(reference))
exit(1)
o_refs.add(reference)
print(" OK")
Common.references = o_refs
| mit | 2,314,850,003,653,533,000 | 30.8 | 88 | 0.602875 | false | 4.137546 | false | false | false |
mikegagnon/sidenote | prefix-links.py | 1 | 1725 | #!/usr/bin/env python
#
# This is free and unencumbered software released into the public domain.
#
# Sometimes you want to include one sidenote document into another.
# One way you could do that is copy the .md files from one project into another.
# However, this creates a risk of link-tag collisions. I.e. one project
# defines ~foo and the other project also defines ~foo.
#
# prefix-links.py solves this problem. It takes a .md file as input, then
# prefixes each link tag with a random string. Therefore ~foo becomes
# ~4C5FGAL2foo
#
# Then you can safely include .md files from multiple projects into another
# project
#
from sidenote import *
import argparse
import random
import re
import string
# https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
key = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
def obscure(filename):
with open(filename) as f:
lines = f.readlines()
for line in lines:
newline = ""
# tokenize the line into links and non-links
for part in LINK_PARSER.split(line):
if LINK_PARSER.match(part):
newpart = part.replace("(##", "(##" + key)
newline += newpart
else:
newline += part
if TILDE_ANCHOR_PARSER.match(newline):
newline = newline.replace("~", "~" + key)
print newline,
if __name__=="__main__":
parser = argparse.ArgumentParser(description='"Obscure" links in a Sidenote document')
parser.add_argument('file', type=str,
help='the markdown file to obscure')
args = parser.parse_args()
obscure(args.file)
| unlicense | 1,335,531,607,694,736,400 | 30.363636 | 115 | 0.662029 | false | 3.799559 | false | false | false |
slipstream/SlipStreamClient | client/src/main/python/slipstream/Logger.py | 1 | 1610 | import os
import errno
import logging
from logging.handlers import RotatingFileHandler
class Logger(object):
LOGGER_NAME = 'SSClient'
LOGFILE_MAXBYTES = 2*1024*1024
LOGFILE_BACKUPCOUNT = 5
LOGFILE_FORMAT = "%(asctime)s:%(levelname)s:%(name)s:%(message)s"
log_file = '/var/log/slipstream/client/slipstream-node.log'
def __init__(self, config_holder):
self.log_to_file = True
self.log_level = 'info'
self.logger_name = ''
config_holder.assign(self)
self.logger = None
self._configure_logger()
def _configure_logger(self):
self.logger = logging.getLogger(self.logger_name or Logger.LOGGER_NAME)
numeric_level = getattr(logging, self.log_level.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError('Invalid log level: %s' % self.log_level)
self.logger.setLevel(numeric_level)
formatter = logging.Formatter(self.LOGFILE_FORMAT)
if self.log_to_file:
self._create_log_dir()
handler = RotatingFileHandler(self.log_file,
maxBytes=self.LOGFILE_MAXBYTES,
backupCount=self.LOGFILE_BACKUPCOUNT)
else:
handler = logging.StreamHandler()
handler.setFormatter(formatter)
self.logger.addHandler(handler)
def _create_log_dir(self):
log_dir = os.path.dirname(self.log_file)
try:
os.makedirs(log_dir)
except OSError, ex:
if ex.errno != errno.EEXIST:
raise
def get_logger(self):
return self.logger
| apache-2.0 | -4,789,312,884,300,418,000 | 30.568627 | 79 | 0.618012 | false | 3.851675 | false | false | false |
psychopy/psychopy | psychopy/sound/microphone.py | 1 | 35191 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Audio recording using a microphone.
"""
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2021 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
__all__ = ['Microphone']
import sys
import psychopy.logging as logging
from psychopy.constants import NOT_STARTED, STARTED
from psychopy.preferences import prefs
from .audioclip import *
from .audiodevice import *
from .exceptions import *
import numpy as np
_hasPTB = True
try:
import psychtoolbox.audio as audio
except (ImportError, ModuleNotFoundError):
logging.warning(
"The 'psychtoolbox' library cannot be loaded but is required for audio "
"capture (use `pip install psychtoolbox` to get it). Microphone "
"recording will be unavailable this session. Note that opening a "
"microphone stream will raise an error.")
_hasPTB = False
class RecordingBuffer(object):
"""Class for a storing a recording from a stream.
Think of instances of this class behaving like an audio tape whereas the
`Microphone` class is the tape recorder. Samples taken from the stream are
written to the tape which stores the data.
Used internally by the `Microphone` class, users usually do not create
instances of this class themselves.
Parameters
----------
sampleRateHz : int
Sampling rate for audio recording in Hertz (Hz). By default, 48kHz
(``sampleRateHz=480000``) is used which is adequate for most consumer
grade microphones (headsets and built-in).
channels : int
Number of channels to record samples to `1=Mono` and `2=Stereo`.
maxRecordingSize : int
Maximum recording size in kilobytes (Kb). Since audio recordings tend to
consume a large amount of system memory, one might want to limit the
size of the recording buffer to ensure that the application does not run
out of memory. By default, the recording buffer is set to 24000 KB (or
24 MB). At a sample rate of 48kHz, this will result in 62.5 seconds of
continuous audio being recorded before the buffer is full.
policyWhenFull : str
What to do when the recording buffer is full and cannot accept any more
samples. If 'ignore', samples will be silently dropped and the `isFull`
property will be set to `True`. If 'warn', a warning will be logged and
the `isFull` flag will be set. Finally, if 'error' the application will
raise an exception.
"""
def __init__(self, sampleRateHz=SAMPLE_RATE_48kHz, channels=2,
maxRecordingSize=24000, policyWhenFull='ignore'):
self._channels = channels
self._sampleRateHz = sampleRateHz
self._maxRecordingSize = maxRecordingSize
self._samples = None # `ndarray` created in _allocRecBuffer`
self._offset = 0 # recording offset
self._lastSample = 0 # offset of the last sample from stream
self._spaceRemaining = None # set in `_allocRecBuffer`
self._totalSamples = None # set in `_allocRecBuffer`
# check if the value is valid
if policyWhenFull not in ['ignore', 'warn', 'error']:
raise ValueError("Invalid value for `policyWhenFull`.")
self._policyWhenFull = policyWhenFull
self._warnedRecBufferFull = False
self._loops = 0
self._allocRecBuffer()
def _allocRecBuffer(self):
"""Allocate the recording buffer. Called internally if properties are
changed."""
# allocate another array
nBytes = self._maxRecordingSize * 1000
recArraySize = int((nBytes / self._channels) / (np.float32()).itemsize)
self._samples = np.zeros(
(recArraySize, self._channels), dtype=np.float32, order='C')
# sanity check
assert self._samples.nbytes == nBytes
self._totalSamples = len(self._samples)
self._spaceRemaining = self._totalSamples
@property
def samples(self):
"""Reference to the actual sample buffer (`ndarray`)."""
return self._samples
@property
def bufferSecs(self):
"""Capacity of the recording buffer in seconds (`float`)."""
return self._totalSamples / self._sampleRateHz
@property
def nbytes(self):
"""Number of bytes the recording buffer occupies in memory (`int`)."""
return self._samples.nbytes
@property
def sampleBytes(self):
"""Number of bytes per sample (`int`)."""
return np.float32().itemsize
@property
def spaceRemaining(self):
"""The space remaining in the recording buffer (`int`). Indicates the
number of samples that the buffer can still add before overflowing.
"""
return self._spaceRemaining
@property
def isFull(self):
"""Is the recording buffer full (`bool`)."""
return self._spaceRemaining <= 0
@property
def totalSamples(self):
"""Total number samples the recording buffer can hold (`int`)."""
return self._totalSamples
@property
def writeOffset(self):
"""Index in the sample buffer where new samples will be written when
`write()` is called (`int`).
"""
return self._offset
@property
def lastSample(self):
"""Index of the last sample recorded (`int`). This can be used to slice
the recording buffer, only getting data from the beginning to place
where the last sample was written to.
"""
return self._lastSample
@property
def loopCount(self):
"""Number of times the recording buffer restarted (`int`). Only valid if
`loopback` is ``True``."""
return self._loops
@property
def maxRecordingSize(self):
"""Maximum recording size in kilobytes (`int`).
Since audio recordings tend to consume a large amount of system memory,
one might want to limit the size of the recording buffer to ensure that
the application does not run out of memory. By default, the recording
buffer is set to 24000 KB (or 24 MB). At a sample rate of 48kHz, this
will result in 62.5 seconds of continuous audio being recorded before
the buffer is full.
Setting this value will allocate another recording buffer of appropriate
size. Avoid doing this in any time sensitive parts of your application.
"""
return self._maxRecordingSize
@maxRecordingSize.setter
def maxRecordingSize(self, value):
value = int(value)
# don't do this unless the value changed
if value == self._maxRecordingSize:
return
# if different than last value, update the recording buffer
self._maxRecordingSize = value
self._allocRecBuffer()
def seek(self, offset, absolute=False):
"""Set the write offset.
Use this to specify where to begin writing samples the next time `write`
is called. You should call `seek(0)` when starting a new recording.
Parameters
----------
offset : int
Position in the sample buffer to set.
absolute : bool
Use absolute positioning. Use relative positioning if `False` where
the value of `offset` will be added to the current offset. Default
is `False`.
"""
if not absolute:
self._offset += offset
else:
self._offset = absolute
assert 0 <= self._offset < self._totalSamples
self._spaceRemaining = self._totalSamples - self._offset
def write(self, samples):
"""Write samples to the recording buffer.
Parameters
----------
samples : ArrayLike
Samples to write to the recording buffer, usually of a stream. Must
have the same number of dimensions as the internal array.
Returns
-------
int
Number of samples overflowed. If this is zero then all samples have
been recorded, if not, the number of samples rejected is given.
"""
nSamples = len(samples)
if self.isFull:
if self._policyWhenFull == 'ignore':
return nSamples # samples lost
elif self._policyWhenFull == 'warn':
if not self._warnedRecBufferFull:
logging.warning(
f"Audio recording buffer filled! This means that no "
f"samples are saved beyond {round(self.bufferSecs, 6)} "
f"seconds. Specify a larger recording buffer next time "
f"to avoid data loss.")
logging.flush()
self._warnedRecBufferFull = True
return nSamples
elif self._policyWhenFull == 'error':
raise AudioRecordingBufferFullError(
"Cannot write samples, recording buffer is full.")
else:
return nSamples # whatever
if not nSamples: # no samples came out of the stream, just return
return
if self._spaceRemaining >= nSamples:
self._lastSample = self._offset + nSamples
audioData = samples[:, :]
else:
self._lastSample = self._offset + self._spaceRemaining
audioData = samples[:self._spaceRemaining, :]
self._samples[self._offset:self._lastSample, :] = audioData
self._offset += nSamples
self._spaceRemaining -= nSamples
# Check if the recording buffer is now full. Next call to `poll` will
# not record anything.
if self._spaceRemaining <= 0:
self._spaceRemaining = 0
d = nSamples - self._spaceRemaining
return 0 if d < 0 else d
def clear(self):
# reset all live attributes
self._samples = None
self._offset = 0
self._lastSample = 0
self._spaceRemaining = None
self._totalSamples = None
# reallocate buffer
self._allocRecBuffer()
def getSegment(self, start=0, end=None):
"""Get a segment of recording data as an `AudioClip`.
Parameters
----------
start : float or int
Absolute time in seconds for the start of the clip.
end : float or int
Absolute time in seconds for the end of the clip. If `None` the time
at the last sample is used.
Returns
-------
AudioClip
Audio clip object with samples between `start` and `end`.
"""
idxStart = int(start * self._sampleRateHz)
idxEnd = self._lastSample if end is None else int(
end * self._sampleRateHz)
return AudioClip(
np.array(self._samples[idxStart:idxEnd, :],
dtype=np.float32, order='C'),
sampleRateHz=self._sampleRateHz)
class Microphone(object):
"""Class for recording audio from a microphone or input stream.
Creating an instance of this class will open a stream using the specified
device. Streams should remain open for the duration of your session. When a
stream is opened, a buffer is allocated to store samples coming off it.
Samples from the input stream will written to the buffer once
:meth:`~Microphone.start()` is called.
Parameters
----------
device : int or `~psychopy.sound.AudioDevice`
Audio capture device to use. You may specify the device either by index
(`int`) or descriptor (`AudioDevice`).
sampleRateHz : int
Sampling rate for audio recording in Hertz (Hz). By default, 48kHz
(``sampleRateHz=480000``) is used which is adequate for most consumer
grade microphones (headsets and built-in).
channels : int
Number of channels to record samples to `1=Mono` and `2=Stereo`.
streamBufferSecs : float
Stream buffer size to pre-allocate for the specified number of seconds.
The default is 2.0 seconds which is usually sufficient.
maxRecordingSize : int
Maximum recording size in kilobytes (Kb). Since audio recordings tend to
consume a large amount of system memory, one might want to limit the
size of the recording buffer to ensure that the application does not run
out of memory. By default, the recording buffer is set to 24000 KB (or
24 MB). At a sample rate of 48kHz, this will result in 62.5 seconds of
continuous audio being recorded before the buffer is full.
audioLatencyMode : int or None
Audio latency mode to use, values range between 0-4. If `None`, the
setting from preferences will be used. Using `3` (exclusive mode) is
adequate for most applications and required if using WASAPI on Windows
for other settings (such audio quality) to take effect. Symbolic
constants `psychopy.sound.audiodevice.AUDIO_PTB_LATENCY_CLASS_` can also
be used.
audioRunMode : int
Run mode for the recording device. Default is standby-mode (`0`) which
allows the system to put the device to sleep. However when the device is
needed, waking the device results in some latency. Using a run mode of
`1` will keep the microphone running (or 'hot') with reduces latency
when th recording is started. Cannot be set when after initialization at
this time.
Examples
--------
Capture 10 seconds of audio from the primary microphone::
import psychopy.core as core
import psychopy.sound.Microphone as Microphone
mic = Microphone(bufferSecs=10.0) # open the microphone
mic.start() # start recording
core.wait(10.0) # wait 10 seconds
mic.stop() # stop recording
audioClip = mic.getRecording()
print(audioClip.duration) # should be ~10 seconds
audioClip.save('test.wav') # save the recorded audio as a 'wav' file
The prescribed method for making long recordings is to poll the stream once
per frame (or every n-th frame)::
mic = Microphone(bufferSecs=2.0)
mic.start() # start recording
# main trial drawing loop
mic.poll()
win.flip() # calling the window flip function
mic.stop() # stop recording
audioClip = mic.getRecording()
"""
# Force the use of WASAPI for audio capture on Windows. If `True`, only
# WASAPI devices will be returned when calling static method
# `Microphone.getDevices()`
enforceWASAPI = True
def __init__(self,
device=None,
sampleRateHz=None,
channels=2,
streamBufferSecs=2.0,
maxRecordingSize=24000,
policyWhenFull='warn',
audioLatencyMode=None,
audioRunMode=0):
if not _hasPTB: # fail if PTB is not installed
raise ModuleNotFoundError(
"Microphone audio capture requires package `psychtoolbox` to "
"be installed.")
# get information about the selected device
devices = Microphone.getDevices()
if isinstance(device, AudioDeviceInfo):
self._device = device
elif isinstance(device, (int, float)):
devicesByIndex = {d.deviceIndex: d for d in devices}
if device in devicesByIndex:
self._device = devicesByIndex[device]
else:
raise AudioInvalidCaptureDeviceError(
'No suitable audio recording devices found matching index '
'{}.'.format(device))
else:
# get default device, first enumerated usually
if not devices:
raise AudioInvalidCaptureDeviceError(
'No suitable audio recording devices found on this system. '
'Check connections and try again.')
self._device = devices[0] # use first
logging.info('Using audio device #{} ({}) for audio capture'.format(
self._device.deviceIndex, self._device.deviceName))
# error if specified device is not suitable for capture
if not self._device.isCapture:
raise AudioInvalidCaptureDeviceError(
'Specified audio device not suitable for audio recording. '
'Has no input channels.')
# get the sample rate
self._sampleRateHz = \
self._device.defaultSampleRate if sampleRateHz is None else int(
sampleRateHz)
logging.debug('Set stream sample rate to {} Hz'.format(
self._sampleRateHz))
# set the audio latency mode
if audioLatencyMode is None:
self._audioLatencyMode = int(prefs.hardware["audioLatencyMode"])
else:
self._audioLatencyMode = audioLatencyMode
logging.debug('Set audio latency mode to {}'.format(
self._audioLatencyMode))
assert 0 <= self._audioLatencyMode <= 4 # sanity check for pref
# set the number of recording channels
self._channels = \
self._device.inputChannels if channels is None else int(channels)
logging.debug('Set recording channels to {} ({})'.format(
self._channels, 'stereo' if self._channels > 1 else 'mono'))
if self._channels > self._device.inputChannels:
raise AudioInvalidDeviceError(
'Invalid number of channels for audio input specified.')
# internal recording buffer size in seconds
assert isinstance(streamBufferSecs, (float, int))
self._streamBufferSecs = float(streamBufferSecs)
# PTB specific stuff
self._mode = 2 # open a stream in capture mode
# Handle for the recording stream, should only be opened once per
# session
logging.debug('Opening audio stream for device #{}'.format(
self._device.deviceIndex))
self._stream = audio.Stream(
device_id=self._device.deviceIndex,
latency_class=self._audioLatencyMode,
mode=self._mode,
freq=self._sampleRateHz,
channels=self._channels)
logging.debug('Stream opened')
assert isinstance(audioRunMode, (float, int)) and \
(audioRunMode == 0 or audioRunMode == 1)
self._audioRunMode = int(audioRunMode)
self._stream.run_mode = self._audioRunMode
logging.debug('Set run mode to `{}`'.format(
self._audioRunMode))
# set latency bias
self._stream.latency_bias = 0.0
logging.debug('Set stream latency bias to {} ms'.format(
self._stream.latency_bias))
# pre-allocate recording buffer, called once
self._stream.get_audio_data(self._streamBufferSecs)
logging.debug(
'Allocated stream buffer to hold {} seconds of data'.format(
self._streamBufferSecs))
# status flag
self._statusFlag = NOT_STARTED
# setup recording buffer
self._recording = RecordingBuffer(
sampleRateHz=self._sampleRateHz,
channels=self._channels,
maxRecordingSize=maxRecordingSize,
policyWhenFull=policyWhenFull
)
# setup clips and transcripts dicts
self.clips = {}
self.lastClip = None
self.scripts = {}
self.lastScript = None
logging.debug('Audio capture device #{} ready'.format(
self._device.deviceIndex))
@staticmethod
def getDevices():
"""Get a `list` of audio capture device (i.e. microphones) descriptors.
On Windows, only WASAPI devices are used.
Returns
-------
list
List of `AudioDevice` descriptors for suitable capture devices. If
empty, no capture devices have been found.
"""
try:
Microphone.enforceWASAPI = bool(prefs.hardware["audioForceWASAPI"])
except KeyError:
pass # use default if option not present in settings
# query PTB for devices
if Microphone.enforceWASAPI and sys.platform == 'win32':
allDevs = audio.get_devices(device_type=13)
else:
allDevs = audio.get_devices()
# make sure we have an array of descriptors
allDevs = [allDevs] if isinstance(allDevs, dict) else allDevs
# create list of descriptors only for capture devices
inputDevices = [desc for desc in [
AudioDeviceInfo.createFromPTBDesc(dev) for dev in allDevs]
if desc.isCapture]
return inputDevices
# def warmUp(self):
# """Warm-/wake-up the audio stream.
#
# On some systems the first time `start` is called incurs additional
# latency, whereas successive calls do not. To deal with this, it is
# recommended that you run this warm-up routine prior to capturing audio
# samples. By default, this routine is called when instancing a new
# microphone object.
#
# """
# # We should put an actual test here to see if timing stabilizes after
# # multiple invocations of this function.
# self._stream.start()
# self._stream.stop()
@property
def recording(self):
"""Reference to the current recording buffer (`RecordingBuffer`)."""
return self._recording
@property
def recBufferSecs(self):
"""Capacity of the recording buffer in seconds (`float`)."""
return self.recording.bufferSecs
@property
def maxRecordingSize(self):
"""Maximum recording size in kilobytes (`int`).
Since audio recordings tend to consume a large amount of system memory,
one might want to limit the size of the recording buffer to ensure that
the application does not run out. By default, the recording buffer is
set to 64000 KB (or 64 MB). At a sample rate of 48kHz, this will result
in about. Using stereo audio (``nChannels == 2``) requires twice the
buffer over mono (``nChannels == 2``) for the same length clip.
Setting this value will allocate another recording buffer of appropriate
size. Avoid doing this in any time sensitive parts of your application.
"""
return self._recording.maxRecordingSize
@maxRecordingSize.setter
def maxRecordingSize(self, value):
self._recording.maxRecordingSize = value
@property
def latencyBias(self):
"""Latency bias to add when starting the microphone (`float`).
"""
return self._stream.latency_bias
@latencyBias.setter
def latencyBias(self, value):
self._stream.latency_bias = float(value)
@property
def audioLatencyMode(self):
"""Audio latency mode in use (`int`). Cannot be set after
initialization.
"""
return self._audioLatencyMode
@property
def streamBufferSecs(self):
"""Size of the internal audio storage buffer in seconds (`float`).
To ensure all data is captured, there must be less time elapsed between
subsequent `getAudioClip` calls than `bufferSecs`.
"""
return self._streamBufferSecs
@property
def status(self):
"""Status flag for the microphone. Value can be one of
``psychopy.constants.STARTED`` or ``psychopy.constants.NOT_STARTED``.
For detailed stream status information, use the
:attr:`~psychopy.sound.microphone.Microphone.streamStatus` property.
"""
if hasattr(self, "_statusFlag"):
return self._statusFlag
@status.setter
def status(self, value):
self._statusFlag = value
@property
def streamStatus(self):
"""Status of the audio stream (`AudioDeviceStatus` or `None`).
See :class:`~psychopy.sound.AudioDeviceStatus` for a complete overview
of available status fields. This property has a value of `None` if
the stream is presently closed.
Examples
--------
Get the capture start time of the stream::
# assumes mic.start() was called
captureStartTime = mic.status.captureStartTime
Check if microphone recording is active::
isActive = mic.status.active
Get the number of seconds recorded up to this point::
recordedSecs = mic.status.recordedSecs
"""
currentStatus = self._stream.status
if currentStatus != -1:
return AudioDeviceStatus.createFromPTBDesc(currentStatus)
@property
def isRecBufferFull(self):
"""`True` if there is an overflow condition with the recording buffer.
If this is `True`, then `poll()` is still collecting stream samples but
is no longer writing them to anything, causing stream samples to be
lost.
"""
return self._recording.isFull
@property
def isStarted(self):
"""``True`` if stream recording has been started (`bool`)."""
return self.status == STARTED
def start(self, when=None, waitForStart=0, stopTime=None):
"""Start an audio recording.
Calling this method will begin capturing samples from the microphone and
writing them to the buffer.
Parameters
----------
when : float, int or None
When to start the stream. If the time specified is a floating point
(absolute) system time, the device will attempt to begin recording
at that time. If `None` or zero, the system will try to start
recording as soon as possible.
waitForStart : bool
Wait for sound onset if `True`.
stopTime : float, int or None
Number of seconds to record. If `None` or `-1`, recording will
continue forever until `stop` is called.
Returns
-------
float
Absolute time the stream was started.
"""
# check if the stream has been
if self.isStarted:
raise AudioStreamError(
"Cannot start a stream, already started.")
if self._stream is None:
raise AudioStreamError("Stream not ready.")
# reset the writing 'head'
self._recording.seek(0, absolute=True)
# reset warnings
# self._warnedRecBufferFull = False
startTime = self._stream.start(
repetitions=0,
when=when,
wait_for_start=int(waitForStart),
stop_time=stopTime)
# recording has begun or is scheduled to do so
self._statusFlag = STARTED
logging.debug(
'Scheduled start of audio capture for device #{} at t={}.'.format(
self._device.deviceIndex, startTime))
return startTime
def record(self, when=None, waitForStart=0, stopTime=None):
"""Start an audio recording (alias of `.start()`).
Calling this method will begin capturing samples from the microphone and
writing them to the buffer.
Parameters
----------
when : float, int or None
When to start the stream. If the time specified is a floating point
(absolute) system time, the device will attempt to begin recording
at that time. If `None` or zero, the system will try to start
recording as soon as possible.
waitForStart : bool
Wait for sound onset if `True`.
stopTime : float, int or None
Number of seconds to record. If `None` or `-1`, recording will
continue forever until `stop` is called.
Returns
-------
float
Absolute time the stream was started.
"""
return self.start(
when=when,
waitForStart=waitForStart,
stopTime=stopTime)
def stop(self, blockUntilStopped=True, stopTime=None):
"""Stop recording audio.
Call this method to end an audio recording if in progress. This will
simply halt recording and not close the stream. Any remaining samples
will be polled automatically and added to the recording buffer.
Parameters
----------
blockUntilStopped : bool
Halt script execution until the stream has fully stopped.
stopTime : float or None
Scheduled stop time for the stream in system time. If `None`, the
stream will stop as soon as possible.
Returns
-------
tuple
Tuple containing `startTime`, `endPositionSecs`, `xruns` and
`estStopTime`.
"""
if not self.isStarted:
raise AudioStreamError(
"Cannot stop a stream that has not been started.")
# poll remaining samples, if any
if not self.isRecBufferFull:
self.poll()
startTime, endPositionSecs, xruns, estStopTime = self._stream.stop(
block_until_stopped=int(blockUntilStopped),
stopTime=stopTime)
self._statusFlag = NOT_STARTED
logging.debug(
('Device #{} stopped capturing audio samples at estimated time '
't={}. Total overruns: {} Total recording time: {}').format(
self._device.deviceIndex, estStopTime, xruns, endPositionSecs))
return startTime, endPositionSecs, xruns, estStopTime
def pause(self, blockUntilStopped=True, stopTime=None):
"""Pause a recording (alias of `.stop`).
Call this method to end an audio recording if in progress. This will
simply halt recording and not close the stream. Any remaining samples
will be polled automatically and added to the recording buffer.
Parameters
----------
blockUntilStopped : bool
Halt script execution until the stream has fully stopped.
stopTime : float or None
Scheduled stop time for the stream in system time. If `None`, the
stream will stop as soon as possible.
Returns
-------
tuple
Tuple containing `startTime`, `endPositionSecs`, `xruns` and
`estStopTime`.
"""
return self.stop(blockUntilStopped=blockUntilStopped, stopTime=stopTime)
def close(self):
"""Close the stream.
Should not be called until you are certain you're done with it. Ideally,
you should never close and reopen the same stream within a single
session.
"""
self._stream.close()
logging.debug('Stream closed')
def poll(self):
"""Poll audio samples.
Calling this method adds audio samples collected from the stream buffer
to the recording buffer that have been captured since the last `poll`
call. Time between calls of this function should be less than
`bufferSecs`. You do not need to call this if you call `stop` before
the time specified by `bufferSecs` elapses since the `start` call.
Can only be called between called of `start` (or `record`) and `stop`
(or `pause`).
Returns
-------
int
Number of overruns in sampling.
"""
if not self.isStarted:
raise AudioStreamError(
"Cannot poll samples from audio device, not started.")
# figure out what to do with this other information
audioData, absRecPosition, overflow, cStartTime = \
self._stream.get_audio_data()
if overflow:
logging.warning(
"Audio stream buffer overflow, some audio samples have been "
"lost! To prevent this, ensure `Microphone.poll()` is being "
"called often enough, or increase the size of the audio buffer "
"with `bufferSecs`.")
overruns = self._recording.write(audioData)
return overruns
def bank(self, tag=None, transcribe=False, **kwargs):
"""Store current buffer as a clip within the microphone object.
This method is used internally by the Microphone component in Builder,
don't use it for other applications. Either `stop()` or `pause()` must
be called before calling this method.
Parameters
----------
tag : str or None
Label for the clip.
transcribe : bool or str
Set to the name of a transcription engine (e.g. "GOOGLE") to
transcribe using that engine, or set as `False` to not transcribe.
kwargs : dict
Additional keyword arguments to pass to
:class:`~psychopy.sound.AudioClip.transcribe()`.
"""
# make sure the tag exists in both clips and transcripts dicts
if tag not in self.clips:
self.clips[tag] = []
if tag not in self.scripts:
self.scripts[tag] = []
# append current recording to clip list according to tag
self.lastClip = self.getRecording()
self.clips[tag].append(self.lastClip)
# append current clip's transcription according to tag
if transcribe:
if transcribe in ('Built-in', True, 'BUILT_IN', 'BUILT-IN',
'Built-In', 'built-in'):
engine = "sphinx"
elif type(transcribe) == str:
engine = transcribe
self.lastScript = self.lastClip.transcribe(
engine=engine, **kwargs)
else:
self.lastScript = "Transcription disabled."
self.scripts[tag].append(self.lastScript)
# clear recording buffer
self._recording.clear()
# return banked items
if transcribe:
return self.lastClip, self.lastScript
else:
return self.lastClip
def clear(self):
"""Wipe all clips. Deletes previously banked audio clips.
"""
# clear clips
self.clips = {}
# clear recording
self._recording.clear()
def flush(self):
"""Get a copy of all banked clips, then clear the clips from storage."""
# get copy of clips dict
clips = self.clips.copy()
# clear
self.clear()
return clips
def getRecording(self):
"""Get audio data from the last microphone recording.
Call this after `stop` to get the recording as an `AudioClip` object.
Raises an error if a recording is in progress.
Returns
-------
AudioClip
Recorded data between the last calls to `start` (or `record`) and
`stop`.
"""
if self.isStarted:
raise AudioStreamError(
"Cannot get audio clip, recording was in progress. Be sure to "
"call `Microphone.stop` first.")
return self._recording.getSegment() # full recording
if __name__ == "__main__":
pass
| gpl-3.0 | 1,498,106,364,352,994,300 | 34.909184 | 80 | 0.613424 | false | 4.634664 | false | false | false |
sipwise/repoapi | build/test/test_utils.py | 1 | 11161 | # Copyright (C) 2017-2020 The Sipwise Team - http://sipwise.com
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
import re
from unittest.mock import patch
from django.test import override_settings
from django.test import SimpleTestCase
from build import exceptions as err
from build.conf import settings
from build.utils import get_common_release
from build.utils import get_simple_release
from build.utils import is_release_trunk
from build.utils import ReleaseConfig
from build.utils import trigger_build
from build.utils import trigger_copy_deps
class SimpleIsReleaseTrunkTest(SimpleTestCase):
def test_trunk(self):
ok, val = is_release_trunk("trunk")
self.assertFalse(ok)
self.assertIsNone(val)
def test_mrXX(self):
ok, val = is_release_trunk("release-mr8.5")
self.assertFalse(ok)
self.assertIsNone(val)
def test_release_trunk(self):
ok, val = is_release_trunk("release-trunk-buster")
self.assertTrue(ok)
self.assertEqual(val, "buster")
ok, val = is_release_trunk("release-trunk-bullseye")
self.assertTrue(ok)
self.assertEqual(val, "bullseye")
class SimpleReleaseTest(SimpleTestCase):
def test_trunk(self):
val = get_simple_release("release-trunk-buster")
self.assertEqual(val, "trunk")
def test_branch_release(self):
val = get_simple_release("release-mr8.0")
self.assertEqual(val, "mr8.0")
def test_release_ok(self):
val = get_simple_release("release-mr8.1.1")
self.assertEqual(val, "mr8.1.1")
def test_release_update_ok(self):
val = get_simple_release("release-mr8.1-update")
self.assertEqual(val, "mr8.1")
def test_release_ko(self):
val = get_simple_release("mr8.1.1")
self.assertIsNone(val)
class CommonReleaseTest(SimpleTestCase):
def test_trunk(self):
val = get_common_release("release-trunk-buster")
self.assertEqual(val, "master")
def test_branch_release(self):
val = get_common_release("release-mr8.0")
self.assertEqual(val, "mr8.0")
def test_release_ok(self):
val = get_common_release("mr8.1.1")
self.assertEqual(val, "mr8.1")
def test_release_ko(self):
val = get_common_release("whatever-mr8.1.1")
self.assertIsNone(val)
class ReleaseConfigTestCase(SimpleTestCase):
build_deps = [
"data-hal",
"ngcp-schema",
"libinewrate",
"libswrate",
"libtcap",
"sipwise-base",
"check-tools",
]
@override_settings(BUILD_RELEASES_SKIP=["mr0.1"])
def test_supported_releases(self):
supported = [
"release-trunk-buster",
"release-trunk-bullseye",
"mr8.1.2",
"mr8.1",
"mr7.5.3",
"mr7.5.2",
"mr7.5.1",
"mr7.5",
]
res = ReleaseConfig.supported_releases()
self.assertListEqual(res, supported)
@patch.object(ReleaseConfig, "supported_releases")
def test_supported_releases_dict(self, sr):
res_ok = [
{"release": "release-trunk-buster", "base": "master"},
{"release": "mr8.0", "base": "mr8.0"},
{"release": "mr8.0.1", "base": "mr8.0"},
{"release": "mr7.5.1", "base": "mr7.5"},
]
sr.return_value = [
"release-trunk-buster",
"mr8.0",
"mr8.0.1",
"mr7.5.1",
]
res = ReleaseConfig.supported_releases_dict()
self.assertListEqual(res, res_ok)
def test_no_release_config(self):
with self.assertRaises(err.NoConfigReleaseFile):
ReleaseConfig("fake_release")
def test_no_jenkins_jobs(self):
with self.assertRaises(err.NoJenkinsJobsInfo):
ReleaseConfig("mr0.1")
def test_ok(self):
rc = ReleaseConfig("trunk")
self.assertIsNotNone(rc.config)
self.assertListEqual(list(rc.build_deps.keys()), self.build_deps)
self.assertEqual(rc.debian_release, "buster")
self.assertEqual(len(rc.projects), 73)
def test_debian_release_value(self):
rc = ReleaseConfig("trunk")
self.assertEqual(rc.debian_release, "buster")
rc = ReleaseConfig("release-trunk-bullseye")
self.assertEqual(rc.debian_release, "bullseye")
rc = ReleaseConfig("trunk", "bullseye")
self.assertEqual(rc.debian_release, "bullseye")
# distribution parameter is only used with trunk
rc = ReleaseConfig("release-mr8.1-update", "bullseye")
self.assertEqual(rc.debian_release, "buster")
def test_release_value(self):
rc = ReleaseConfig("trunk")
self.assertEqual(rc.release, "trunk")
def test_branch_tag_value_trunk(self):
rc = ReleaseConfig("trunk")
self.assertEqual(rc.branch, "master")
self.assertIsNone(rc.tag)
def test_branch_tag_value_mrXX(self):
rc = ReleaseConfig("mr8.1")
self.assertEqual(rc.branch, "mr8.1")
self.assertIsNone(rc.tag)
def test_branch_tag_value_mrXXX(self):
rc = ReleaseConfig("mr7.5.2")
self.assertEqual(rc.branch, "mr7.5.2")
self.assertEqual(rc.tag, "mr7.5.2.1")
def test_build_deps(self):
rc = ReleaseConfig("trunk")
build_deps = [
"data-hal",
"ngcp-schema",
"libinewrate",
"libswrate",
"libtcap",
"sipwise-base",
"check-tools",
]
self.assertListEqual(list(rc.build_deps.keys()), build_deps)
def test_build_deps_iter_step_1(self):
rc = ReleaseConfig("trunk")
build_deps = [
"data-hal",
"libinewrate",
"libswrate",
"libtcap",
"sipwise-base",
"check-tools",
]
values = []
for prj in rc.wanna_build_deps(0):
values.append(prj)
self.assertListEqual(build_deps, values)
def test_build_deps_iter_step_2(self):
rc = ReleaseConfig("trunk")
values = []
for prj in rc.wanna_build_deps(1):
values.append(prj)
self.assertListEqual(["ngcp-schema"], values)
@patch("build.utils.open_jenkins_url")
class TriggerBuild(SimpleTestCase):
def test_project_build(self, openurl):
params = {
"project": "kamailio-get-code",
"release_uuid": "UUID_mr8.2",
"trigger_release": "release-mr8.2",
"trigger_branch_or_tag": "branch/mr8.2",
"trigger_distribution": "buster",
"uuid": "UUID_A",
}
url = (
"{base}/job/{project}/buildWithParameters?"
"token={token}&cause={trigger_release}&uuid={uuid}&"
"release_uuid={release_uuid}&"
"branch=mr8.2&tag=none&"
"release={trigger_release}&distribution={trigger_distribution}"
)
res = trigger_build(**params)
params["base"] = settings.JENKINS_URL
params["token"] = settings.JENKINS_TOKEN
self.assertEqual(res, "{base}/job/{project}/".format(**params))
openurl.assert_called_once_with(url.format(**params))
def test_project_build_uuid(self, openurl):
params = {
"project": "kamailio-get-code",
"release_uuid": "UUID_mr8.2",
"trigger_release": "release-mr8.2",
"trigger_branch_or_tag": "branch/mr8.2",
"trigger_distribution": "buster",
}
res = [trigger_build(**params), trigger_build(**params)]
params["base"] = settings.JENKINS_URL
params["token"] = settings.JENKINS_TOKEN
self.assertEqual(res[0], "{base}/job/{project}/".format(**params))
self.assertEqual(res[0], res[1])
uuids = list()
self.assertEqual(len(openurl.call_args_list), 2)
for call in openurl.call_args_list:
m = re.match(r".+&uuid=([^&]+)&.+", str(call))
self.assertIsNotNone(m)
uuids.append(m.groups(0))
self.assertNotEqual(uuids[0], uuids[1])
def test_copy_debs_build(self, openurl):
params = {
"release": "release-mr8.2",
"internal": True,
"release_uuid": "UUID_mr8.2",
"uuid": "UUID_A",
}
url = (
"{base}/job/{project}/buildWithParameters?"
"token={token}&cause={release}&uuid={uuid}&"
"release_uuid={release_uuid}&"
"release=mr8.2&internal=true"
)
res = trigger_copy_deps(**params)
params["project"] = "release-copy-debs-yml"
params["base"] = settings.JENKINS_URL
params["token"] = settings.JENKINS_TOKEN
self.assertEqual(res, "{base}/job/{project}/".format(**params))
openurl.assert_called_once_with(url.format(**params))
def test_project_build_trunk(self, openurl):
params = {
"project": "kamailio-get-code",
"release_uuid": "UUID_mr8.2",
"trigger_release": "trunk",
"trigger_branch_or_tag": "branch/master",
"trigger_distribution": "buster",
"uuid": "UUID_A",
}
url = (
"{base}/job/{project}/buildWithParameters?"
"token={token}&cause={trigger_release}&uuid={uuid}&"
"release_uuid={release_uuid}&"
"branch=master&tag=none&"
"release=trunk&distribution={trigger_distribution}"
)
res = trigger_build(**params)
params["base"] = settings.JENKINS_URL
params["token"] = settings.JENKINS_TOKEN
self.assertEqual(res, "{base}/job/{project}/".format(**params))
openurl.assert_called_once_with(url.format(**params))
def test_copy_debs_build_trunk(self, openurl):
params = {
"release": "release-trunk-buster",
"internal": True,
"release_uuid": "UUID_master",
"uuid": "UUID_B",
}
url = (
"{base}/job/{project}/buildWithParameters?"
"token={token}&cause={release}&uuid={uuid}&"
"release_uuid={release_uuid}&"
"release=release-trunk-buster&internal=true"
)
res = trigger_copy_deps(**params)
params["project"] = "release-copy-debs-yml"
params["base"] = settings.JENKINS_URL
params["token"] = settings.JENKINS_TOKEN
self.assertEqual(res, "{base}/job/{project}/".format(**params))
openurl.assert_called_once_with(url.format(**params))
| gpl-3.0 | -7,227,835,457,043,220,000 | 33.55418 | 77 | 0.585431 | false | 3.58644 | true | false | false |
grovesdixon/metaTranscriptomes | scripts/parse_codeml_pairwise_outputBACKUP.py | 1 | 6189 | #!/usr/bin/env python
##parse_codeml_pairwise_output.py
##written 6/26/14 by Groves Dixon
ProgramName = 'parse_codeml_pairwise_output.py'
LastUpdated = '6/26/14'
By = 'Groves Dixon'
VersionNumber = '1.0'
print "\nRunning Program {}...".format(ProgramName)
VersionString = '{} version {} Last Updated {} by {}'.format(ProgramName, VersionNumber, LastUpdated, By)
Description = '''
Description:
Parses a list of codeml output files that were generated using pair-wise
dN/dS estimation (runmode -2). Pairs are set up against one base species
(set as spp1) and all other species (a list file)
'''
AdditionalProgramInfo = '''
Additional Program Information:
'''
##Import Modules
import time
import argparse
from sys import argv
from sys import exit
import numpy as np
Start_time = time.time() ##keeps track of how long the script takes to run
##Set Up Argument Parsing
parser = argparse.ArgumentParser(description=Description, epilog=AdditionalProgramInfo) ##create argument parser that will automatically return help texts from global variables above
parser.add_argument('-f', required = True, dest = 'files', nargs="+", help = 'A glob to the codeml output files (probably *.codeml)')
parser.add_argument('-spp1', required = True, dest = 'spp1', help = 'The search tag for species 1')
parser.add_argument('-sppList', required = True, dest = 'sppList', help = 'The List of species to pair with species 1')
parser.add_argument('-o', required = True, dest = 'out', help = 'The desired output file name')
args = parser.parse_args()
#Assign Arguments
FileList = args.files
Spp1 = args.spp1
SppListName = args.sppList
OutfileName = args.out
SppList = []
with open(SppListName, 'r') as infile:
for line in infile:
SppList.append(line.strip("\n"))
def read_files(FileList, Spp1, SppList):
'''Function to reads through each file and parses out
dN and dS estimates for the specified species pair.
'''
print "\nLooking for data in {} codeml output files...".format(len(FileList))
geneList = []
dNList = []
dSList = []
speciesList = []
highDScount = 0
for species in SppList:
if species == Spp1:
continue
for file in FileList:
with open(file, 'r') as infile:
hit = 0
hitCount = 0 #this should never exceed 1
for line in infile:
if hitCount > 1:
exit("Found more than one instance of pairing in a file. Something is wrong.")
if hit == 0:
##look for your species pair
if "("+Spp1+")" in line:
if "("+species+")" in line:
if "..." in line:
hit = 1
continue
elif hit == 1:
if "dN/dS=" in line:
line = line.split()
try:
dn = line[10]
ds = line[13]
except IndexError: #occurs sometimes when dS is very large
#the dn value is also sometimes so high it must be split differently
#this probably means its a bad alignment/ortholog call, but pasrse it anyway
try:
dn = line[10]
ds = line[12]
#it's rare, but possible that N is double digits and S is not, so only "strip" the = from the front of ds if its there
if "=" in ds:
ds = ds.split('=')[1] #split the large ds value assuming that dS is >= 10.0 but dN is not
except IndexError:
dn = line[9].split('=')[1] #this means that the dN value was also >= 10.0, so grab it differently
ds = line[11].split('=')[1] #dS is also in a different place because of the big dN, so grab it
geneName = file.strip(".codeml")
geneList.append(geneName)
dNList.append(dn)
dSList.append(ds)
speciesList.append(species)
hit = 0
hitCount += 1
# print geneName
# print species
# print dn
return geneList, dNList, dSList, speciesList
def output(OutfileName, geneList, dNList, dSList, speciesList):
"""Outputs the data into a table"""
badValues = []
lineNums = []
with open(OutfileName, 'w') as out:
out.write("EST\tspecies\tdN\tdS")
for i in range(len(geneList)):
#########
##there is a bug that occurs when the synonymous substitution rate is >99.99
#these are obviously wrong anyway and they stop the output from uploading into R so skip them
fourData = 'TRUE'
outList = [geneList[i], speciesList[i], dNList[i], dSList[i]]
try:
float(dNList[i])
float(dSList[i])
except ValueError:
badValues.append([dNList[i], dSList[i]])
lineNums.append(i)
continue
for x in outList:
if x == "":
fourData = 'FALSE'
if fourData == 'FALSE':
continue
###########
outString = "\n{}\t{}\t{}\t{}".format(geneList[i], speciesList[i], dNList[i], dSList[i])
out.write("\n{}\t{}\t{}\t{}".format(geneList[i], speciesList[i], dNList[i], dSList[i]))
geneList, dNList, dSList, speciesList = read_files(FileList, Spp1, SppList)
output(OutfileName, geneList, dNList, dSList, speciesList)
#return time to run
Time = time.time() - Start_time
print('\nTime took to run: {}'.format(Time))
| mit | 5,886,263,383,535,908,000 | 40.536913 | 182 | 0.527549 | false | 4.207342 | false | false | false |
Wintermute0110/plugin.program.advanced.emulator.launcher | tests/fakes.py | 1 | 8256 | from abc import ABCMeta, abstractmethod
from resources.objects import *
from resources.utils import *
from resources.scrap import *
class FakeRomSetRepository(ROMSetRepository):
def __init__(self, roms):
self.roms = roms
def find_by_launcher(self, launcher):
return self.roms
def save_rom_set(self, launcher, roms):
self.roms = roms
def delete_all_by_launcher(self, launcher):
self.roms = {}
class FakeExecutor(ExecutorABC):
def __init__(self):
self.actualApplication = None
self.actualArgs = None
super(FakeExecutor, self).__init__(None)
def getActualApplication(self):
return self.actualApplication
def getActualArguments(self):
return self.actualArgs
def execute(self, application, arguments, non_blocking):
self.actualApplication = application
self.actualArgs = arguments
pass
class FakeClass():
def FakeMethod(self, value, key, launcher):
self.value = value
class FakeFile(FileName):
def __init__(self, pathString):
self.fakeContent = ''
self.path_str = pathString
self.path_tr = pathString
self.exists = self.exists_fake
self.write = self.write_fake
def setFakeContent(self, content):
self.fakeContent = content
def getFakeContent(self):
return self.fakeContent
def loadFileToStr(self, encoding = 'utf-8'):
return self.fakeContent
def readAllUnicode(self, encoding='utf-8'):
contents = unicode(self.fakeContent)
return contents
def saveStrToFile(self, data_str, encoding = 'utf-8'):
self.fakeContent = data_str
def write_fake(self, bytes):
self.fakeContent = self.fakeContent + bytes
def open(self, mode):
pass
def close(self):
pass
def writeAll(self, bytes, flags='w'):
self.fakeContent = self.fakeContent + bytes
def pjoin(self, *args):
child = FakeFile(self.path_str)
child.setFakeContent(self.fakeContent)
for arg in args:
child.path_str = os.path.join(child.path_str, arg)
child.path_tr = os.path.join(child.path_tr, arg)
return child
def switchExtension(self, targetExt):
switched_fake = super(FakeFile, self).switchExtension(targetExt)
#switched_fake = FakeFile(switched_type.getPath())
switched_fake.setFakeContent(self.fakeContent)
return switched_fake
def exists_fake(self):
return True
def scanFilesInPathAsFileNameObjects(self, mask = '*.*'):
return []
#backwards compatiblity
def __create__(self, path):
return FakeFile(path)
class Fake_Paths:
def __init__(self, fake_base, fake_addon_id = 'ael-tests'):
# --- Base paths ---
self.ADDONS_DATA_DIR = FileName(fake_base, isdir = True)
self.ADDON_DATA_DIR = self.ADDONS_DATA_DIR.pjoin(fake_addon_id, isdir = True)
self.PROFILE_DIR = self.ADDONS_DATA_DIR.pjoin('profile', isdir = True)
self.HOME_DIR = self.ADDONS_DATA_DIR.pjoin('home', isdir = True)
self.ADDONS_DIR = self.HOME_DIR.pjoin('addons', isdir = True)
self.ADDON_CODE_DIR = self.ADDONS_DIR.pjoin(fake_addon_id, isdir = True)
self.ICON_FILE_PATH = self.ADDON_CODE_DIR.pjoin('media/icon.png')
self.FANART_FILE_PATH = self.ADDON_CODE_DIR.pjoin('media/fanart.jpg')
# --- Databases and reports ---
self.CATEGORIES_FILE_PATH = self.ADDON_DATA_DIR.pjoin('categories.xml')
self.FAV_JSON_FILE_PATH = self.ADDON_DATA_DIR.pjoin('favourites.json')
self.COLLECTIONS_FILE_PATH = self.ADDON_DATA_DIR.pjoin('collections.xml')
self.VCAT_TITLE_FILE_PATH = self.ADDON_DATA_DIR.pjoin('vcat_title.xml')
self.VCAT_YEARS_FILE_PATH = self.ADDON_DATA_DIR.pjoin('vcat_years.xml')
self.VCAT_GENRE_FILE_PATH = self.ADDON_DATA_DIR.pjoin('vcat_genre.xml')
self.VCAT_DEVELOPER_FILE_PATH = self.ADDON_DATA_DIR.pjoin('vcat_developers.xml')
self.VCAT_NPLAYERS_FILE_PATH = self.ADDON_DATA_DIR.pjoin('vcat_nplayers.xml')
self.VCAT_ESRB_FILE_PATH = self.ADDON_DATA_DIR.pjoin('vcat_esrb.xml')
self.VCAT_RATING_FILE_PATH = self.ADDON_DATA_DIR.pjoin('vcat_rating.xml')
self.VCAT_CATEGORY_FILE_PATH = self.ADDON_DATA_DIR.pjoin('vcat_category.xml')
# Launcher app stdout/stderr file
self.LAUNCH_LOG_FILE_PATH = self.ADDON_DATA_DIR.pjoin('launcher.log')
self.RECENT_PLAYED_FILE_PATH = self.ADDON_DATA_DIR.pjoin('history.json')
self.MOST_PLAYED_FILE_PATH = self.ADDON_DATA_DIR.pjoin('most_played.json')
self.BIOS_REPORT_FILE_PATH = self.ADDON_DATA_DIR.pjoin('report_BIOS.txt')
self.LAUNCHER_REPORT_FILE_PATH = self.ADDON_DATA_DIR.pjoin('report_Launchers.txt')
# --- Offline scraper databases ---
self.GAMEDB_INFO_DIR = self.ADDON_CODE_DIR.pjoin('GameDBInfo', isdir = True)
self.GAMEDB_JSON_BASE_NOEXT = 'GameDB_info'
self.LAUNCHBOX_INFO_DIR = self.ADDON_CODE_DIR.pjoin('LaunchBox', isdir = True)
self.LAUNCHBOX_JSON_BASE_NOEXT = 'LaunchBox_info'
# --- Artwork and NFO for Categories and Launchers ---
self.CATEGORIES_ASSET_DIR = self.ADDON_DATA_DIR.pjoin('asset-categories', isdir = True)
self.COLLECTIONS_ASSET_DIR = self.ADDON_DATA_DIR.pjoin('asset-collections', isdir = True)
self.LAUNCHERS_ASSET_DIR = self.ADDON_DATA_DIR.pjoin('asset-launchers', isdir = True)
self.FAVOURITES_ASSET_DIR = self.ADDON_DATA_DIR.pjoin('asset-favourites', isdir = True)
self.VIRTUAL_CAT_TITLE_DIR = self.ADDON_DATA_DIR.pjoin('db_title', isdir = True)
self.VIRTUAL_CAT_YEARS_DIR = self.ADDON_DATA_DIR.pjoin('db_year', isdir = True)
self.VIRTUAL_CAT_GENRE_DIR = self.ADDON_DATA_DIR.pjoin('db_genre', isdir = True)
self.VIRTUAL_CAT_DEVELOPER_DIR = self.ADDON_DATA_DIR.pjoin('db_developer', isdir = True)
self.VIRTUAL_CAT_NPLAYERS_DIR = self.ADDON_DATA_DIR.pjoin('db_nplayer', isdir = True)
self.VIRTUAL_CAT_ESRB_DIR = self.ADDON_DATA_DIR.pjoin('db_esrb', isdir = True)
self.VIRTUAL_CAT_RATING_DIR = self.ADDON_DATA_DIR.pjoin('db_rating', isdir = True)
self.VIRTUAL_CAT_CATEGORY_DIR = self.ADDON_DATA_DIR.pjoin('db_category', isdir = True)
self.ROMS_DIR = self.ADDON_DATA_DIR.pjoin('db_ROMs', isdir = True)
self.COLLECTIONS_DIR = self.ADDON_DATA_DIR.pjoin('db_Collections', isdir = True)
self.REPORTS_DIR = self.ADDON_DATA_DIR.pjoin('reports', isdir = True)
class FakeScraper(Scraper):
def __init__(self, settings, launcher, rom_data_to_apply = None):
self.rom_data_to_apply = rom_data_to_apply
scraper_settings = ScraperSettings(1,1,False,True)
super(FakeScraper, self).__init__(scraper_settings, launcher, True, [])
def getName(self):
return 'FakeScraper'
def supports_asset_type(self, asset_info):
return True
def _get_candidates(self, searchTerm, romPath, rom):
return ['fake']
def _load_metadata(self, candidate, romPath, rom):
gamedata = self._new_gamedata_dic()
if self.rom_data_to_apply :
gamedata['title'] = self.rom_data_to_apply['m_name'] if 'm_name' in self.rom_data_to_apply else ''
gamedata['year'] = self.rom_data_to_apply['m_year'] if 'm_year' in self.rom_data_to_apply else ''
gamedata['genre'] = self.rom_data_to_apply['m_genre'] if 'm_genre' in self.rom_data_to_apply else ''
gamedata['developer'] = self.rom_data_to_apply['m_developer']if 'm_developer' in self.rom_data_to_apply else ''
gamedata['plot'] = self.rom_data_to_apply['m_plot'] if 'm_plot' in self.rom_data_to_apply else ''
else:
gamedata['title'] = romPath.getBase_noext()
def _load_assets(self, candidate, romPath, rom):
pass
| gpl-2.0 | -8,512,910,359,609,642,000 | 42.005208 | 123 | 0.622941 | false | 3.251674 | false | false | false |
coolbombom/CouchPotatoServer | couchpotato/core/downloaders/transmission/main.py | 1 | 10725 | from base64 import b64encode
from couchpotato.core.downloaders.base import Downloader, StatusList
from couchpotato.core.helpers.encoding import isInt
from couchpotato.core.logger import CPLog
from couchpotato.environment import Env
from datetime import timedelta
import httplib
import json
import os.path
import re
import traceback
import urllib2
log = CPLog(__name__)
class Transmission(Downloader):
type = ['torrent', 'torrent_magnet']
log = CPLog(__name__)
def download(self, data, movie, filedata = None):
log.info('Sending "%s" (%s) to Transmission.', (data.get('name'), data.get('type')))
# Load host from config and split out port.
host = self.conf('host').split(':')
if not isInt(host[1]):
log.error('Config properties are not filled in correctly, port is missing.')
return False
# Set parameters for Transmission
params = {
'paused': self.conf('paused', default = 0),
}
if len(self.conf('directory', default = '')) > 0:
folder_name = self.createFileName(data, filedata, movie)[:-len(data.get('type')) - 1]
params['download-dir'] = os.path.join(self.conf('directory', default = ''), folder_name).rstrip(os.path.sep)
torrent_params = {}
if self.conf('ratio'):
torrent_params = {
'seedRatioLimit': self.conf('ratio'),
'seedRatioMode': self.conf('ratiomode')
}
if not filedata and data.get('type') == 'torrent':
log.error('Failed sending torrent, no data')
return False
# Send request to Transmission
try:
trpc = TransmissionRPC(host[0], port = host[1], username = self.conf('username'), password = self.conf('password'))
if data.get('type') == 'torrent_magnet':
remote_torrent = trpc.add_torrent_uri(data.get('url'), arguments = params)
torrent_params['trackerAdd'] = self.torrent_trackers
else:
remote_torrent = trpc.add_torrent_file(b64encode(filedata), arguments = params)
if not remote_torrent:
return False
# Change settings of added torrents
elif torrent_params:
trpc.set_torrent(remote_torrent['torrent-added']['hashString'], torrent_params)
log.info('Torrent sent to Transmission successfully.')
return self.downloadReturnId(remote_torrent['torrent-added']['hashString'])
except:
log.error('Failed to change settings for transfer: %s', traceback.format_exc())
return False
def getAllDownloadStatus(self):
log.debug('Checking Transmission download status.')
# Load host from config and split out port.
host = self.conf('host').split(':')
if not isInt(host[1]):
log.error('Config properties are not filled in correctly, port is missing.')
return False
# Go through Queue
try:
trpc = TransmissionRPC(host[0], port = host[1], username = self.conf('username'), password = self.conf('password'))
return_params = {
'fields': ['id', 'name', 'hashString', 'percentDone', 'status', 'eta', 'isFinished', 'downloadDir', 'uploadRatio']
}
queue = trpc.get_alltorrents(return_params)
except Exception, err:
log.error('Failed getting queue: %s', err)
return False
if not queue:
return []
statuses = StatusList(self)
# Get torrents status
# CouchPotato Status
#status = 'busy'
#status = 'failed'
#status = 'completed'
# Transmission Status
#status = 0 => "Torrent is stopped"
#status = 1 => "Queued to check files"
#status = 2 => "Checking files"
#status = 3 => "Queued to download"
#status = 4 => "Downloading"
#status = 4 => "Queued to seed"
#status = 6 => "Seeding"
#To do :
# add checking file
# manage no peer in a range time => fail
for item in queue['torrents']:
log.debug('name=%s / id=%s / downloadDir=%s / hashString=%s / percentDone=%s / status=%s / eta=%s / uploadRatio=%s / confRatio=%s / isFinished=%s', (item['name'], item['id'], item['downloadDir'], item['hashString'], item['percentDone'], item['status'], item['eta'], item['uploadRatio'], self.conf('ratio'), item['isFinished']))
if not os.path.isdir(Env.setting('from', 'renamer')):
log.error('Renamer "from" folder doesn\'t to exist.')
return
if (item['percentDone'] * 100) >= 100 and (item['status'] == 6 or item['status'] == 0) and item['uploadRatio'] > self.conf('ratio'):
try:
trpc.stop_torrent(item['hashString'], {})
statuses.append({
'id': item['hashString'],
'name': item['name'],
'status': 'completed',
'original_status': item['status'],
'timeleft': str(timedelta(seconds = 0)),
'folder': os.path.join(item['downloadDir'], item['name']),
})
if ((not os.path.isdir(item['downloadDir']))) and (self.conf('from') in item['downloadDir'])):
trpc.remove_torrent(item['id'], "true", {})
except Exception, err:
log.error('Failed to stop and remove torrent "%s" with error: %s', (item['name'], err))
statuses.append({
'id': item['hashString'],
'name': item['name'],
'status': 'failed',
'original_status': item['status'],
'timeleft': str(timedelta(seconds = 0)),
})
else:
statuses.append({
'id': item['hashString'],
'name': item['name'],
'status': 'busy',
'original_status': item['status'],
'timeleft': str(timedelta(seconds = item['eta'])), # Is ETA in seconds??
})
return statuses
class TransmissionRPC(object):
"""TransmissionRPC lite library"""
def __init__(self, host = 'localhost', port = 9091, username = None, password = None):
super(TransmissionRPC, self).__init__()
self.url = 'http://' + host + ':' + str(port) + '/transmission/rpc'
self.tag = 0
self.session_id = 0
self.session = {}
if username and password:
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(realm = None, uri = self.url, user = username, passwd = password)
opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(password_manager), urllib2.HTTPDigestAuthHandler(password_manager))
opener.addheaders = [('User-agent', 'couchpotato-transmission-client/1.0')]
urllib2.install_opener(opener)
elif username or password:
log.debug('User or password missing, not using authentication.')
self.session = self.get_session()
def _request(self, ojson):
self.tag += 1
headers = {'x-transmission-session-id': str(self.session_id)}
request = urllib2.Request(self.url, json.dumps(ojson).encode('utf-8'), headers)
try:
open_request = urllib2.urlopen(request)
response = json.loads(open_request.read())
log.debug('request: %s', json.dumps(ojson))
log.debug('response: %s', json.dumps(response))
if response['result'] == 'success':
log.debug('Transmission action successfull')
return response['arguments']
else:
log.debug('Unknown failure sending command to Transmission. Return text is: %s', response['result'])
return False
except httplib.InvalidURL, err:
log.error('Invalid Transmission host, check your config %s', err)
return False
except urllib2.HTTPError, err:
if err.code == 401:
log.error('Invalid Transmission Username or Password, check your config')
return False
elif err.code == 409:
msg = str(err.read())
try:
self.session_id = \
re.search('X-Transmission-Session-Id:\s*(\w+)', msg).group(1)
log.debug('X-Transmission-Session-Id: %s', self.session_id)
# #resend request with the updated header
return self._request(ojson)
except:
log.error('Unable to get Transmission Session-Id %s', err)
else:
log.error('TransmissionRPC HTTPError: %s', err)
except urllib2.URLError, err:
log.error('Unable to connect to Transmission %s', err)
def get_session(self):
post_data = {'method': 'session-get', 'tag': self.tag}
return self._request(post_data)
def add_torrent_uri(self, torrent, arguments):
arguments['filename'] = torrent
post_data = {'arguments': arguments, 'method': 'torrent-add', 'tag': self.tag}
return self._request(post_data)
def add_torrent_file(self, torrent, arguments):
arguments['metainfo'] = torrent
post_data = {'arguments': arguments, 'method': 'torrent-add', 'tag': self.tag}
return self._request(post_data)
def set_torrent(self, torrent_id, arguments):
arguments['ids'] = torrent_id
post_data = {'arguments': arguments, 'method': 'torrent-set', 'tag': self.tag}
return self._request(post_data)
def get_alltorrents(self, arguments):
post_data = {'arguments': arguments, 'method': 'torrent-get', 'tag': self.tag}
return self._request(post_data)
def stop_torrent(self, torrent_id, arguments):
arguments['ids'] = torrent_id
post_data = {'arguments': arguments, 'method': 'torrent-stop', 'tag': self.tag}
return self._request(post_data)
def remove_torrent(self, torrent_id, remove_local_data, arguments):
arguments['ids'] = torrent_id
arguments['delete-local-data'] = remove_local_data
post_data = {'arguments': arguments, 'method': 'torrent-remove', 'tag': self.tag}
return self._request(post_data)
| gpl-3.0 | 1,714,337,725,172,411,100 | 41.9 | 339 | 0.554499 | false | 4.288285 | true | false | false |
astroswego/magellanic-structure | src/magstruct/transformations.py | 1 | 1722 | import numpy
from numpy import array, sin, cos
__all__ = [
'Equatorial2Cartesian',
'Rotation3D',
'rotation_matrix_3d'
]
class Equatorial2Cartesian():
def __init__(self, RA_0, Dec_0, D_0):
self.RA_0 = RA_0
self.Dec_0 = Dec_0
self.D_0 = D_0
def fit(self, X, y=None):
return self
def transform(self, X, y=None, **params):
X_new = numpy.empty_like(X)
x, y, z = X_new[:,0], X_new[:,1], X_new[:,2]
RA, Dec, D = X[:,0], X[:,1], X[:,2]
delta_RA = RA - self.RA_0
x[:] = -D * sin(delta_RA) * cos(Dec)
y[:] = D * (sin(Dec) * cos(self.Dec_0) +
sin(self.Dec_0) * cos(delta_RA) * cos(Dec))
z[:] = self.D_0 \
- D * (sin(Dec)*sin(self.Dec_0) + cos(RA)*cos(self.Dec_0)) \
- self.RA_0*cos(Dec)
return X_new
def rotation_matrix_3d(angle, axis):
assert axis in range(3), 'Axis must be 0, 1, or 2'
T = numpy.empty((3, 3), dtype=float)
# find the index of the -sin(angle) term
# this formula is the polynomial which passes through all of the pairs
# (axis, index)
i = axis**2 - 4*axis + 5
T.flat[::3+1] = cos(angle)
T.flat[i::3-1] = sin(angle)
# negate the -sin(angle) term, as it is currently just sin(angle)
T.flat[i] *= -1
T[axis,:] = 0
T[:,axis] = 0
T[axis,axis] = 1
return T
class Rotation3D():
def __init__(self, angle, axis):
self.axis = axis
self.angle = angle
self.rotation_matrix = rotation_matrix_3d(angle, axis)
def fit(self, X, y=None):
return self
def transform(self, X, y=None, **params):
return self.rotation_matrix.dot(X)
| mit | -4,956,154,805,142,992,000 | 24.701493 | 74 | 0.522648 | false | 2.903879 | false | false | false |
lindemann09/pyForceDAQ | forceDAQ/data_handling/read_force_data.py | 1 | 2147 | """
Functions to read your force and event data
"""
__author__ = 'Oliver Lindemann'
import os
import sys
import gzip
from collections import OrderedDict
import numpy as np
TAG_COMMENTS = "#"
TAG_UDPDATA = TAG_COMMENTS + "UDP"
TAG_DAQEVENTS = TAG_COMMENTS + "T"
def _csv(line):
return list(map(lambda x: x.strip(), line.split(",")))
def DataFrameDict(data, varnames):
"""data frame: Dict of numpy arrays
does not require Pandas, but can be easily converted to pandas dataframe
via pandas.DataFrame(data_frame_dict)
"""
rtn = OrderedDict()
for v in varnames:
rtn[v] = []
for row in data:
for v, d in zip(varnames, row):
rtn[v].append(d)
return rtn
def data_frame_to_text(data_frame):
rtn = ",".join(data_frame.keys())
rtn += "\n"
for x in np.array(list(data_frame.values())).T:
rtn += ",".join(x) + "\n"
return rtn
def read_raw_data(path):
"""reading trigger and udp data
Returns: data, udp_event, daq_events and comments
data, udp_event, daq_events: DataFrameDict
comments: text string
"""
daq_events = []
udp_events = []
comments = ""
data = []
varnames = None
app_dir = os.path.split(sys.argv[0])[0]
path = os.path.abspath(os.path.join(app_dir, path))
if path.endswith("gz"):
fl = gzip.open(path, "rt")
else:
fl = open(path, "rt")
for ln in fl:
if ln.startswith(TAG_COMMENTS):
comments += ln
if ln.startswith(TAG_UDPDATA + ","):
udp_events.append(_csv(ln[len(TAG_UDPDATA) + 1:]))
elif ln.startswith(TAG_DAQEVENTS):
daq_events.append(_csv(ln[len(TAG_DAQEVENTS) + 1:]))
else:
# data
if varnames is None:
# first row contains varnames
varnames = _csv(ln)
else:
data.append(_csv(ln))
fl.close()
return (DataFrameDict(data, varnames),
DataFrameDict(udp_events, ["time", "value"]),
DataFrameDict(daq_events, ["time", "value"]),
comments)
| mit | -4,905,626,410,306,586,000 | 23.123596 | 76 | 0.56218 | false | 3.451768 | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.