code
stringlengths
3
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.05M
"""MegaStates: A 'MegaState' is a state which absorbs and implements multiple AnalyzerState-s in a manner that is beneficial in terms of code size, computational speed, or both. All MegaState-s shall be derived from class MegaState, and thus are committed to the described interface. The final product of a MegaState is a piece of code which can act on behalf of its absorbed AnalyzerState-s. A 'state_key' indicates for any point in time the AnalyzerState which the MegaState represents. The following scheme displays the general idea of a class hierarchy with a MegaState involved. At the time of this writing there are two derived classes 'TemplateState' and 'PathWalkerState'--each represent a compression algorith: AnalyzerState <------- MegaState <----+---- TemplateState | '---- PathWalkerState Analogous to the AnalyzerState, a MegaState has special classes to implement 'Entry' and 'DropOut', namely 'MegaState_Entry' and 'MegaState_DropOut'. Where an AnalyzerState's transition_map associates a character interval with a target state index, the MegaState's transition_map associates a character interval with a 'MegaState_Target'. Given a state_key, the MegaState_Target provides the target state index for the given character interval. The following pinpoints the general idea of a MegaState. -------------------------------------------------------------------------- MegaStateEntry: ... entry doors of absorbed states ... /* Some Specific Actions ... */ tansition_map( input ) { in interval_0: MegaState_Target_0[state_key]; --> Target states in interval_1: MegaState_Target_1[state_key]; --> depending on in interval_2: MegaState_Target_2[state_key]; --> current input ... --> character. in interval_N: MegaState_Target_N[state_key]; } MegaState_DropOut: ... drop-out actions of absorbed states ... -------------------------------------------------------------------------- This file provides two special classes for states: -- PseudoMegaState: represents an AnalyzerState as if it was a MegaState. This way, it may act homogeneously in algorithms that work on MegaState-s and AnalyzerState-s at the same time. -- AbsorbedState: represent an AnalyzerState in the original state database, even though it is absorbed by a MegaState. (C) 2012 Frank-Rene Schaefer """ from quex.engine.analyzer.state.core import AnalyzerState from quex.engine.analyzer.state.entry import Entry from quex.engine.analyzer.state.drop_out import DropOut, DropOutBackward, DropOutBackwardInputPositionDetection from quex.engine.analyzer.state.entry_action import DoorID from quex.blackboard import E_StateIndices from copy import copy class MegaState_Entry(Entry): """Implements a common base class for Entry classes of MegaState-s. """ def __init__(self, MegaStateIndex): Entry.__init__(self, MegaStateIndex, FromStateIndexList=[]) class MegaState(AnalyzerState): """Interface for all derived MegaState-s: .implemented_state_index_list(): List of indices of AnalyzerState-s which have been absorbed by the MegaState. .map_state_index_to_state_key(): Provides the state_key that the MegaState requires to act on behalf of state_index. .map_state_key_to_state_index(): Determines the state_index on whose behalf the MegaState acts, if its state_key is as specified. 'bad_company' Keeps track of indices of AnalyzerState-s which are not good company. Algorithms that try to combine multiple MegaState-s into one (e.g. 'Template Compression') profit from avoiding to combine MegaStates where its elements are bad company to each other. .finalize_transition_map() Adapts the transition_map. When it detects that all elements of a 'scheme' enter the same state door, it is replaced by the DoorID. If a uniform target state is entered through different doors depending on the absorbed state, then it is replaced by a scheme that contains the target state multiple times. The transition_map can only be finalized after ALL MegaState-s have been generated. """ def __init__(self, TheEntry, TheDropOut, StateIndex): # A 'PseudoMegaState' does not implement a 'MegaState_Entry' and 'MegaState_DropOut'. # On the long term 'MegaState_DropOut' should be derived from 'DropOut'. assert isinstance(TheEntry, Entry), Entry.__class__.__name__ assert isinstance(TheDropOut, (MegaState_DropOut, DropOut, DropOutBackward, DropOutBackwardInputPositionDetection)) assert isinstance(StateIndex, long) self.__entry = TheEntry self.__drop_out = TheDropOut AnalyzerState.set_index(self, StateIndex) # Maintain a list of states with which the state may not combine well self.__bad_company = set() # State Index Sequence: Implemented States (and may be others) in an # ordered Sequence. self.__state_index_sequence = None @property def entry(self): return self.__entry @property def drop_out(self): return self.__drop_out @property def init_state_f(self): return False def state_index_sequence(self): assert False, "This function needs to be overwritten by derived class." def implemented_state_index_list(self): assert False, "This function needs to be overwritten by derived class." def map_state_index_to_state_key(self, StateIndex): assert False, "This function needs to be overwritten by derived class." def map_state_key_to_state_index(self, StateKey): assert False, "This function needs to be overwritten by derived class." def bad_company_add(self, StateIndex): self.__bad_company.add(StateIndex) def bad_company_set(self, StateIndexSet): self.__bad_company = StateIndexSet def bad_company(self): """RETURN: List of state indices with which the MegaState does not combine well. """ return self.__bad_company def finalize_transition_map(self, StateDB): scheme_db = {} for i, info in enumerate(self.transition_map): interval, target = info adapted = target.finalize(self, StateDB, scheme_db) if adapted is None: continue self.transition_map[i] = (interval, adapted) MegaState_Target_DROP_OUT_hash = hash(E_StateIndices.DROP_OUT) class MegaState_Target(object): """ABSTRACT: ______________________________________________________________ Where an AnalyzerState's transition map associates a character interval with a target state index, a MegaState's transition map associates a character interval with a MegaState_Target. A MegaState_Target determines the target state, or target state's entry door, by means of a state key. It is very well possible that it is homogeneous and independent of the state key. In that case, it contains a '.target_state_index' or '.door_id'. If not, the '.scheme' member describes the relationship between and target state index. For example, a given interval X triggers to MegaState_Target T, i.e. there is an element in the transition map: ... [ X, T ] ... then 'T.scheme[state key]' tells the 'target state index' for a given state key. The door through which it enters is determined by the transition id: TransitionID(FromStateIndex = MS.map_state_key_to_state_index(state key), ToStateIndex = T.scheme[state key]) where MS is the MegaState that contains the transition map. The TransitionID can be translated into a DoorID by the target state's entry database 'transition_db'. TRACKING SCHEMES: _________________________________________________________ There might be multiple intervals following the same target scheme. This class keeps track of the schemes by means of the '.object_db'. Before handling a transition map the function MegaState_Target.init() initializes the .object_db. An independent copy of the .object_db can be obtained by my_copy = MegaState_Target.disconnect_object_db() FINALIZATION: _____________________________________________________________ Once the whole state configuration and the states' entry doors are determined, the actual MegaState_Target object can be finalized. That is: -- A common target may become a scheme, if the DoorIDs differ depending on the 'from_state_index' (from .implemented_state_index_list()). -- A scheme may become a common target, if the target DoorID is the same for all indices in .implemented_state_index_list(). Finalization sets the 'scheme_id' if it is a scheme. It set's the '.door_id' if the target state's door is the same for all involved states. ___________________________________________________________________________ NOTE: All 'DropOut' MegaState_Target are represented by the single object 'MegaState_Target_DROP_OUT'. This saves memory. """ __slots__ = ('__drop_out_f', '__scheme', '__scheme_id', '__hash', '__target_state_index', '__door_id') __object_db = dict() @staticmethod def init(): """Initializes: '__object_db' which keeps track of generated MegaState_Target-s.""" MegaState_Target.__object_db.clear() # The Drop-Out target must be always in there. MegaState_Target.__object_db[E_StateIndices.DROP_OUT] = MegaState_Target_DROP_OUT @staticmethod def disconnect_object_db(): """Disconnects the '__object_db' so that it may be used without influencing the '__object_db' of MegaState_Target. """ tmp_object_db = MegaState_Target.__object_db MegaState_Target.__object_db = dict() return tmp_object_db @staticmethod def create(Target): assert Target is not None result = MegaState_Target.__object_db.get(Target) if result is None: result = MegaState_Target(Target) MegaState_Target.__object_db[Target] = result return result def __init__(self, Target): global MegaState_Target_DROP_OUT_hash if Target is None: # Only to be used by 'self.clone()' return self.__target_state_index = None self.__scheme = None self.__scheme_id = None # Only possibly set in 'finalize' self.__door_id = None # Only possibly set in 'finalize' if Target == E_StateIndices.DROP_OUT: self.__drop_out_f = True; self.__hash = MegaState_Target_DROP_OUT_hash return self.__drop_out_f = False self.__hash = None if isinstance(Target, long): self.__target_state_index = Target elif isinstance(Target, tuple): self.__scheme = Target elif isinstance(Target, DoorID): self.__door_id = Target # only by '.finalize()' else: assert False, Target.__class__.__name__ def get_hash(self): if self.__hash is None: if self.__target_state_index is not None: self.__hash = hash(self.__target_state_index) elif self.__scheme is not None: self.__hash = hash(self.__scheme) else: self.__hash = hash(self.__door_id) return self.__hash @property def scheme(self): return self.__scheme @property def target_state_index(self): return self.__target_state_index @property def target_door_id(self): return self.__door_id @property def drop_out_f(self): return self.__drop_out_f @property def scheme_id(self): return self.__scheme_id def finalize(self, TheMegaState, StateDB, scheme_db): """Once the whole state configuration and the states' entry doors are determined, the actual MegaState_Target object can be finalized. That is: -- A common target may become a scheme, if the DoorIDs differ depending on the 'from_state_index' (which is one of the .implemented_state_index_list()). -- A scheme may become a common target, if the target DoorID is the same for all indices in .implemented_state_index_list(). """ if self.drop_out_f: return implemented_state_index_list = TheMegaState.implemented_state_index_list() L = len(implemented_state_index_list) assert L > 1 def determine_scheme_id(scheme_db, Scheme): scheme_id = scheme_db.get(Scheme) if scheme_id is None: scheme_id = len(scheme_db) scheme_db[Scheme] = scheme_id return scheme_id if self.scheme is not None: assert len(self.scheme) == L # The 'scheme' may result in the same DoorID of a MegaState, for # example. In that case case the 'scheme' would translate into a # direct transition to target state. prototype = None for state_index in implemented_state_index_list: state_key = TheMegaState.map_state_index_to_state_key(state_index) target_state_index = self.scheme[state_key] if target_state_index != E_StateIndices.DROP_OUT: # DROP_OUT cannot be in a scheme, if there was some non-DROP-OUT there. # => Only give it a chance as long as no DROP_OUT target appears. target_entry = StateDB[target_state_index].entry door_id = target_entry.get_door_id(target_state_index, state_index) if prototype is None: prototype = door_id; continue elif prototype == door_id: continue # The scheme is indeed not uniform => Stay with the scheme self.__scheme_id = determine_scheme_id(scheme_db, self.__scheme) return # Nothing to be done else: # All has been uniform => generate transition through common DoorID assert prototype is not None return MegaState_Target.create(prototype) else: assert self.target_state_index is not None # The common target state may be entered by different doors # depending on the 'from_state' which is currently implemented by # the MegaState. Then, it translates into a scheme. target_entry = StateDB[self.target_state_index].entry prototype = None for state_index in implemented_state_index_list: door_id = target_entry.get_door_id(self.target_state_index, state_index) if prototype is None: prototype = door_id; continue elif prototype == door_id: continue # The door_ids are not uniform => generate a scheme result = MegaState_Target.create((self.target_state_index,) * L) result.__scheme_id = determine_scheme_id(scheme_db, result.scheme) return result else: # All has been uniform => Stay with 'target_state_index' return # Nothing to be done def __repr__(self): if self.drop_out_f: return "MegaState_Target:DropOut" elif self.target_state_index is not None: return "MegaState_Target:(%s)" % repr(self.__target_state_index).replace("L", "") elif self.target_door_id is not None: return "MegaState_Target:%s" % repr(self.__door_id).replace("L", "") elif self.scheme is not None: return "MegaState_Target:scheme(%s)" % repr(self.__scheme).replace("L", "") else: return "MegaState_Target:<ERROR>" def __hash__(self): if self.__drop_out_f: return 0 elif self.__target_state_index is not None: return self.__target_state_index.state_index elif self.__scheme is not None: return hash(self.__scheme) else: assert False def __eq__(self, Other): if isinstance(Other, MegaState_Target) == False: return False elif self.__drop_out_f and Other.__drop_out_f: return True elif self.__target_state_index is not None and Other.__target_state_index is not None: return self.__target_state_index == Other.__target_state_index elif self.__scheme is not None and Other.__scheme is not None: return self.__scheme == Other.__scheme else: return False ## if self.__scheme_id != Other.__scheme_id: return False return self.__scheme == Other.__scheme # Globally unique object to stand up for all 'drop-outs'. MegaState_Target_DROP_OUT = MegaState_Target(E_StateIndices.DROP_OUT) class MegaState_DropOut(dict): """ABSTRACT: ______________________________________________________________ Map: 'DropOut' object --> indices of states that implement the same drop out actions. EXPLANATION: ______________________________________________________________ For example, if four states 1, 4, 7, and 9 have the same drop_out behavior DropOut_X, then this is stated by an entry in the dictionary as { ... DropOut_X: [1, 4, 7, 9], ... } For this to work, the drop-out objects must support a proper interaction with the 'dict'-objects. Namely, they must support: __hash__ --> get the right 'bucket'. __eq__ or __cmp__ --> compare elements of 'bucket'. ___________________________________________________________________________ """ def __init__(self, *StateList): """Receives a list of states, extracts the drop outs and associates each DropOut with the state indices that implement it. """ for state in StateList: self.update_from_state(state) return @property def uniform_f(self): """Uniform drop-out means, that for all drop-outs mentioned the same actions have to be performed. This is the case, if all states are categorized under the same drop-out. Thus the dictionary's size will be '1'. """ return len(self) == 1 def is_uniform_with(self, Other): """The given Other drop-out belongs to a 'normal state'. This function investigates if it's drop-out behavior is the same as all in others in this MegaState_DropOut. If this MegaState_DropOut is not uniform, then of course it cannot become uniform with 'Other'. """ if not self.uniform_f: return False prototype = self.iterkeys().next() return prototype == Other def update_from_other(self, MS_DropOut): for drop_out, state_index_set in MS_DropOut.iteritems(): # assert hasattr(drop_out, "__hash__") # assert hasattr(drop_out, "__eq__") # PathWalker may enter 'None' in unit test x = self.get(drop_out) if x is None: self[drop_out] = copy(state_index_set) else: x.update(state_index_set) def update_from_state(self, TheState): drop_out = TheState.drop_out if hasattr(drop_out, "iteritems"): self.update_from_other(drop_out) return #assert hasattr(drop_out, "__hash__") #assert hasattr(drop_out, "__eq__") x = self.get(drop_out) if x is None: self[drop_out] = set([TheState.index]) else: x.add(TheState.index) class PseudoMegaState(MegaState): """ABSTRACT: ______________________________________________________________ Represents an AnalyzerState in a way to that it acts homogeneously with other MegaState-s. That is, the transition_map is adapted so that it maps from a character interval to a MegaState_Target. transition_map: interval --> MegaState_Target instead of mapping to a target state index. ___________________________________________________________________________ """ def __init__(self, Represented_AnalyzerState): assert not isinstance(Represented_AnalyzerState, MegaState) self.__state = Represented_AnalyzerState pseudo_mega_state_drop_out = MegaState_DropOut(Represented_AnalyzerState) MegaState.__init__(self, self.__state.entry, pseudo_mega_state_drop_out, Represented_AnalyzerState.index) self.__state_index_sequence = [ Represented_AnalyzerState.index ] self.transition_map = self.__transition_map_construct() def __transition_map_construct(self): """Build a transition map that triggers to MegaState_Target-s rather than simply to target states. CAVEAT: In general, it is **NOT TRUE** that if two transitions (x,a) and (x, b) to a state 'x' share a DoorID in the original state, then they share the DoorID in the MegaState. The critical case is the recursive transition (x,x). It may trigger the same actions as another transition (x,a) in the original state. However, when 'x' is implemented in a MegaState it needs to set a 'state_key' upon entry from 'a'. This is, or may be, necessary to tell the MegaState on which's behalf it has to operate. The recursive transition from 'x' to 'x', though, does not have to set the state_key, since the MegaState still operates on behalf of the same state. While (x,x) and (x,a) have the same DoorID in the original state, their DoorID differs in the MegaState which implements 'x'. THUS: A translation 'old DoorID' --> 'new DoorID' is not sufficient to adapt transition maps! Here, the recursive target is implemented as a 'scheme' in order to prevent that it may be treated as 'uniform' with other targets. """ return [ (interval, MegaState_Target.create(target)) \ for interval, target in self.__state.transition_map] def state_index_sequence(self): return self.__state_index_sequence def implemented_state_index_list(self): return self.__state_index_sequence def map_state_index_to_state_key(self, StateIndex): assert False, "PseudoMegaState-s exist only for analysis. They shall never be implemented." def map_state_key_to_state_index(self, StateKey): assert False, "PseudoMegaState-s exist only for analysis. They shall never be implemented." class AbsorbedState_Entry(Entry): """The information about what transition is implemented by what DoorID is stored in this Entry. It is somewhat isolated from the AbsorbedState's Entry object. """ def __init__(self, StateIndex, TransitionDB, DoorDB): Entry.__init__(self, StateIndex, FromStateIndexList=[]) self.set_transition_db(TransitionDB) self.set_door_db(DoorDB) class AbsorbedState(AnalyzerState): """ABSTRACT: ______________________________________________________________ An AbsorbedState object represents an AnalyzerState which has been implemented by a MegaState. Its sole purpose is to pinpoint to the MegaState which implements it and to translate the transtions into itself to DoorIDs into the MegaState. ___________________________________________________________________________ """ def __init__(self, AbsorbedAnalyzerState, AbsorbingMegaState): AnalyzerState.set_index(self, AbsorbedAnalyzerState.index) # The absorbing MegaState may, most likely, contain other transitions # than the transitions into the AbsorbedAnalyzerState. Those, others # do not do any harm, though. Filtering out those out of the hash map # does, most likely, not bring any benefit. assert AbsorbedAnalyzerState.index in AbsorbingMegaState.implemented_state_index_list() if False: for transition_id in AbsorbedAnalyzerState.entry.door_db.iterkeys(): if transition_id.state_index != AbsorbedAnalyzerState.index: continue assert AbsorbingMegaState.entry.door_db.has_key(transition_id), \ "MegaState %i absorbed %s but does not implement transition %s" % \ (AbsorbingMegaState.index, \ AbsorbingMegaState.implemented_state_index_list(), transition_id) #---------------------------------------------------------------------- self.__entry = AbsorbedState_Entry(AbsorbedAnalyzerState.index, AbsorbingMegaState.entry.transition_db, AbsorbingMegaState.entry.door_db) self.absorbed_by = AbsorbingMegaState self.__state = AbsorbedAnalyzerState @property def drop_out(self): return self.__state.drop_out @property def entry(self): return self.__entry
coderjames/pascal
quex-0.63.1/quex/engine/analyzer/mega_state/core.py
Python
bsd-2-clause
26,146
from email.mime.text import MIMEText from email.utils import formatdate import smtplib from flask import Blueprint, request, render_template, redirect, url_for, abort, current_app, flash, g from flask.ext.babel import _ from werkzeug.exceptions import ServiceUnavailable from sqlalchemy import func from sqlalchemy.orm import joinedload from skylines.database import db from skylines.model import User from skylines.model.event import create_new_user_event from skylines.frontend.forms import CreatePilotForm, RecoverStep1Form, RecoverStep2Form users_blueprint = Blueprint('users', 'skylines') @users_blueprint.route('/') def index(): users = User.query() \ .options(joinedload(User.club)) \ .order_by(func.lower(User.name)) return render_template('users/list.jinja', active_page='settings', users=users) @users_blueprint.route('/new', methods=['GET', 'POST']) def new(): form = CreatePilotForm() if form.validate_on_submit(): return new_post(form) return render_template('users/new.jinja', form=form) def new_post(form): user = User( first_name=form.first_name.data, last_name=form.last_name.data, email_address=form.email_address.data, password=form.password.data ) user.created_ip = request.remote_addr db.session.add(user) create_new_user_event(user) db.session.commit() flash(_('Welcome to SkyLines, %(user)s! You can now log in and share your flights with the world!', user=user)) return redirect(url_for('index')) def hex(value): return int(value, 16) @users_blueprint.route('/recover', methods=['GET', 'POST']) def recover(): key = request.values.get('key', type=hex) if key is None: return recover_step1() else: return recover_step2(key) def recover_step1(): form = RecoverStep1Form() if form.validate_on_submit(): return recover_step1_post(form) return render_template('users/recover_step1.jinja', form=form) def recover_step1_post(form): user = User.by_email_address(form.email_address.data) if not user: abort(404) user.generate_recover_key(request.remote_addr) send_recover_mail(user) flash('Check your email, we have sent you a link to recover your password.') db.session.commit() return redirect(url_for('index')) def send_recover_mail(user): text = u"""Hi %s, you have asked to recover your password (from IP %s). To enter a new password, click on the following link: http://skylines.aero/users/recover?key=%x The SkyLines Team """ % (unicode(user), request.remote_addr, user.recover_key) msg = MIMEText(text.encode('utf-8'), 'plain', 'utf-8') msg['Subject'] = 'SkyLines password recovery' msg['From'] = current_app.config['EMAIL_FROM'] msg['To'] = user.email_address.encode('ascii') msg['Date'] = formatdate(localtime=1) try: smtp = smtplib.SMTP(current_app.config['SMTP_SERVER']) smtp.ehlo() smtp.sendmail(current_app.config['EMAIL_FROM'].encode('ascii'), user.email_address.encode('ascii'), msg.as_string()) smtp.quit() except: raise ServiceUnavailable(description=_( "The mail server is currently not reachable. " "Please try again later or contact the developers.")) def recover_step2(key): user = User.by_recover_key(key) if not user: abort(404) form = RecoverStep2Form(key='%x' % key) if form.validate_on_submit(): return recover_step2_post(key, form) return render_template('users/recover_step2.jinja', form=form) def recover_step2_post(key, form): user = User.by_recover_key(key) if not user: abort(404) user.password = form.password.data user.recover_key = None flash(_('Password changed.')) db.session.commit() return redirect(url_for('index')) @users_blueprint.route('/generate_keys') def generate_keys(): """Hidden method that generates missing tracking keys.""" if not g.current_user or not g.current_user.is_manager(): abort(403) for user in User.query(): if user.tracking_key is None: user.generate_tracking_key() db.session.commit() return redirect(url_for('.index'))
TobiasLohner/SkyLines
skylines/frontend/views/users.py
Python
agpl-3.0
4,343
from __future__ import absolute_import, unicode_literals ###################### # MEZZANINE SETTINGS # ###################### # The following settings are already defined with default values in # the ``defaults.py`` module within each of Mezzanine's apps, but are # common enough to be put here, commented out, for convenient # overriding. Please consult the settings documentation for a full list # of settings Mezzanine implements: # http://mezzanine.jupo.org/docs/configuration.html#default-settings # Controls the ordering and grouping of the admin menu. # # ADMIN_MENU_ORDER = ( # ("Content", ("pages.Page", "blog.BlogPost", # "generic.ThreadedComment", ("Media Library", "fb_browse"),)), # ("Site", ("sites.Site", "redirects.Redirect", "conf.Setting")), # ("Users", ("auth.User", "auth.Group",)), # ) # A three item sequence, each containing a sequence of template tags # used to render the admin dashboard. # # DASHBOARD_TAGS = ( # ("blog_tags.quick_blog", "mezzanine_tags.app_list"), # ("comment_tags.recent_comments",), # ("mezzanine_tags.recent_actions",), # ) # A sequence of templates used by the ``page_menu`` template tag. Each # item in the sequence is a three item sequence, containing a unique ID # for the template, a label for the template, and the template path. # These templates are then available for selection when editing which # menus a page should appear in. Note that if a menu template is used # that doesn't appear in this setting, all pages will appear in it. # PAGE_MENU_TEMPLATES = ( # (1, "Top navigation bar", "pages/menus/dropdown.html"), # (2, "Left-hand tree", "pages/menus/tree.html"), # (3, "Footer", "pages/menus/footer.html"), # ) # A sequence of fields that will be injected into Mezzanine's (or any # library's) models. Each item in the sequence is a four item sequence. # The first two items are the dotted path to the model and its field # name to be added, and the dotted path to the field class to use for # the field. The third and fourth items are a sequence of positional # args and a dictionary of keyword args, to use when creating the # field instance. When specifying the field class, the path # ``django.models.db.`` can be omitted for regular Django model fields. # # EXTRA_MODEL_FIELDS = ( # ( # # Dotted path to field. # "mezzanine.blog.models.BlogPost.image", # # Dotted path to field class. # "somelib.fields.ImageField", # # Positional args for field class. # ("Image",), # # Keyword args for field class. # {"blank": True, "upload_to": "blog"}, # ), # # Example of adding a field to *all* of Mezzanine's content types: # ( # "mezzanine.pages.models.Page.another_field", # "IntegerField", # 'django.db.models.' is implied if path is omitted. # ("Another name",), # {"blank": True, "default": 1}, # ), # ) # Setting to turn on featured images for blog posts. Defaults to False. # # BLOG_USE_FEATURED_IMAGE = True # If True, the south application will be automatically added to the # INSTALLED_APPS setting. USE_SOUTH = True ######################## # MAIN DJANGO SETTINGS # ######################## # People who get code error notifications. # In the format (('Full Name', 'email@example.com'), # ('Full Name', 'anotheremail@example.com')) ADMINS = ( ('administrator', 'administrator@example.com'), ) MANAGERS = ADMINS # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['127.0.0.1'] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = "Europe/Rome" # If you set this to True, Django will use timezone-aware datetimes. USE_TZ = True # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = "en" # Supported languages _ = lambda s: s LANGUAGES = ( ('en', _('English')), ) # A boolean that turns on/off debug mode. When set to ``True``, stack traces # are displayed for error pages. Should always be set to ``False`` in # production. Best set to ``True`` in local_settings.py DEBUG = True # Whether a user's session cookie expires when the Web browser is closed. SESSION_EXPIRE_AT_BROWSER_CLOSE = True SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = False # Tuple of IP addresses, as strings, that: # * See debug comments, when DEBUG is true # * Receive x-headers INTERNAL_IPS = ("127.0.0.1",) # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ) AUTHENTICATION_BACKENDS = ("mezzanine.core.auth_backends.MezzanineBackend",) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # The numeric mode to set newly-uploaded files to. The value should be # a mode you'd pass directly to os.chmod. FILE_UPLOAD_PERMISSIONS = 0o644 ############# # DATABASES # ############# DATABASES = { "default": { # Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.postgresql_psycopg2", # DB name or path to database file if using sqlite3. "NAME": "mezzanine_mailchimper", # Not used with sqlite3. "USER": "", # Not used with sqlite3. "PASSWORD": "", # Set to empty string for localhost. Not used with sqlite3. "HOST": "localhost", # Set to empty string for default. Not used with sqlite3. "PORT": "", "ATOMIC_REQUESTS": True, } } ######### # PATHS # ######### import os # Full filesystem path to the project. PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # Name of the directory for the project. PROJECT_DIRNAME = PROJECT_ROOT.split(os.sep)[-1] # Every cache key will get prefixed with this value - here we set it to # the name of the directory the project is in to try and use something # project specific. CACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_DIRNAME # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = "/static/" # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = os.path.join(PROJECT_ROOT, STATIC_URL.strip("/")) # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = STATIC_URL + "media/" # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip("/").split("/")) # Package/module name to import the root urlpatterns from for the project. ROOT_URLCONF = "%s.urls" % PROJECT_DIRNAME # Put strings here, like "/home/html/django_templates" # or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, "templates"),) ########### # LOGGING # ########### LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'null': { 'class': 'django.utils.log.NullHandler', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', # 'email_backend': 'django.core.mail.backends.console.' # 'EmailBackend', } }, 'loggers': { 'django': { 'handlers': ['console'], }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'django.security': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, 'py.warnings': { 'handlers': ['console'], }, } } ################ # APPLICATIONS # ################ INSTALLED_APPS = ( "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.redirects", "django.contrib.sessions", "django.contrib.sites", "django.contrib.sitemaps", "django.contrib.staticfiles", "mailchimper", "mezzanine.boot", "mezzanine.conf", "mezzanine.core", "mezzanine.generic", "mezzanine.pages", "mezzanine.accounts", # "django_pdb", "crispy_forms", # "functional_tests", ) # List of processors used by RequestContext to populate the context. # Each one should be a callable that takes the request object as its # only parameter and returns a dictionary to add to the context. TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.static", "django.core.context_processors.media", "django.core.context_processors.request", "django.core.context_processors.tz", "mezzanine.conf.context_processors.settings", ) # List of middleware classes to use. Order is important; in the request phase, # these middleware classes will be applied in the order given, and in the # response phase the middleware will be applied in reverse order. MIDDLEWARE_CLASSES = ( "mezzanine.core.middleware.UpdateCacheMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "mezzanine.core.request.CurrentRequestMiddleware", "mezzanine.core.middleware.RedirectFallbackMiddleware", "mezzanine.core.middleware.TemplateForDeviceMiddleware", "mezzanine.core.middleware.TemplateForHostMiddleware", "mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware", "mezzanine.core.middleware.SitePermissionMiddleware", # Uncomment the following if using any of the SSL settings: # "mezzanine.core.middleware.SSLRedirectMiddleware", "mezzanine.pages.middleware.PageMiddleware", "mezzanine.core.middleware.FetchFromCacheMiddleware", # "django_pdb.middleware.PdbMiddleware", ) # Store these package names here as they may change in the future since # at the moment we are using custom forks of them. PACKAGE_NAME_FILEBROWSER = "filebrowser_safe" PACKAGE_NAME_GRAPPELLI = "grappelli_safe" ######################### # OPTIONAL APPLICATIONS # ######################### # These will be added to ``INSTALLED_APPS``, only if available. OPTIONAL_APPS = ( "debug_toolbar", "django_extensions", "compressor", PACKAGE_NAME_FILEBROWSER, PACKAGE_NAME_GRAPPELLI, ) DEBUG_TOOLBAR_CONFIG = {"INTERCEPT_REDIRECTS": False} ################### # DEPLOY SETTINGS # ################### # These settings are used by the default fabfile.py provided. # Check fabfile.py for defaults. # FABRIC = { # "SSH_USER": "", # SSH username # "SSH_PASS": "", # SSH password (consider key-based authentication) # "SSH_KEY_PATH": "", # Local path to SSH key file, for key-based auth # "HOSTS": [], # List of hosts to deploy to # "VIRTUALENV_HOME": "", # Absolute remote path for virtualenvs # "PROJECT_NAME": "", # Unique identifier for project # "REQUIREMENTS_PATH": "", # Path to pip requirements, relative to project # "GUNICORN_PORT": 8000, # Port gunicorn will listen on # "LOCALE": "en_US.UTF-8", # Should end with ".UTF-8" # "LIVE_HOSTNAME": "www.example.com", # Host for public site. # "REPO_URL": "", # Git or Mercurial remote repo URL for the project # "DB_PASS": "", # Live database password # "ADMIN_PASS": "", # Live admin user password # "SECRET_KEY": SECRET_KEY, # "NEVERCACHE_KEY": NEVERCACHE_KEY, # } ################## # LOCAL SETTINGS # ################## # Allow any settings to be defined in local_settings.py which should be # ignored in your version control system allowing for settings to be # defined per machine. try: from local_settings import * except ImportError: pass # Make these unique, and don't share it with anybody. SECRET_KEY = "%(SECRET_KEY)s" NEVERCACHE_KEY = "%(NEVERCACHE_KEY)s" CRISPY_TEMPLATE_PACK = 'bootstrap' # for functional tests INSTALLED_APPS = list(INSTALLED_APPS) + [ PACKAGE_NAME_GRAPPELLI, PACKAGE_NAME_FILEBROWSER, 'django.contrib.redirects'] from django import get_version if int(get_version().split('.')[1]) <= 5: TEST_RUNNER = 'discover_runner.DiscoverRunner' TEST_DISCOVER_PATTERN = "test_*.py" else: TEST_RUNNER = 'django.test.runner.DiscoverRunner' #################### # DYNAMIC SETTINGS # #################### # set_dynamic_settings() will rewrite globals based on what has been # defined so far, in order to provide some better defaults where # applicable. We also allow this settings module to be imported # without Mezzanine installed, as the case may be when using the # fabfile, where setting the dynamic settings below isn't strictly # required. try: from mezzanine.utils.conf import set_dynamic_settings except ImportError: pass else: set_dynamic_settings(globals())
simodalla/mezzanine_mailchimper
project_template/settings.py
Python
bsd-3-clause
14,784
# Copyright (c) 2016 Cyso < development [at] cyso . com > # # This file is part of omniconf, a.k.a. python-omniconf . # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 3.0 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library. If not, see # <http://www.gnu.org/licenses/>. from omniconf.backends import available_backends from omniconf.backends.json import JsonBackend from omniconf.config import ConfigRegistry from omniconf.setting import SettingRegistry, Setting from mock import patch import nose.tools JSON_FILE = """ { "foo": "bar", "section": { "bar": "baz", "subsection": { "baz": "foo" } } } """ CONFIGS = [ ("foo", "bar", None), ("section.bar", "baz", None), ("section.subsection.baz", "foo", None), ("", None, KeyError), ("section", {"bar": "baz", "subsection": {"baz": "foo"}}, None), ("unknown", None, KeyError) ] def test_json_backend_in_available_backends(): nose.tools.assert_in(JsonBackend, available_backends) @patch("json.loads") def test_json_backend_autoconfigure(mock): prefix = "testconf" settings = SettingRegistry() settings.add(JsonBackend.autodetect_settings(prefix)[0]) conf = ConfigRegistry(setting_registry=settings) backend = JsonBackend.autoconfigure(conf, prefix) nose.tools.assert_is(backend, None) conf.set("{0}.json.filename".format(prefix), "bar") backend = JsonBackend.autoconfigure(conf, prefix) nose.tools.assert_is_instance(backend, JsonBackend) def test_json_backend_get_value(): for key, value, sideeffect in CONFIGS: yield _test_get_value, key, value, sideeffect def _test_get_value(key, value, sideeffect): backend = JsonBackend(JSON_FILE) setting = Setting(key=key, _type=str) if sideeffect: with nose.tools.assert_raises(sideeffect): backend.get_value(setting) else: nose.tools.assert_equal(backend.get_value(setting), value)
cyso/omniconf
omniconf/tests/backends/test_json.py
Python
lgpl-3.0
2,458
# Copyright (c) 2018, Frappe Technologies and contributors # For license information, please see license.txt # don't remove this function it is used in tests def test_method(): '''test function''' return 'overridden'
mhbu50/erpnext
erpnext/regional/france/utils.py
Python
gpl-3.0
222
import os import sys import argparse from django.conf import settings class QuickDjangoTest(object): """ A quick way to run the Django test suite without a fully-configured project. Example usage: >>> QuickDjangoTest('app1', 'app2') Based on a script published by Lukasz Dziedzia at: http://stackoverflow.com/questions/3841725/how-to-launch-tests-for-django-reusable-app """ DIRNAME = os.path.dirname(__file__) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.staticfiles', 'paperclip', 'leaflet', 'djgeojson', 'compressor', 'easy_thumbnails', 'crispy_forms', 'floppyforms', 'rest_framework', 'embed_video', ) def __init__(self, *args, **kwargs): self.apps = args self.run_tests() def run_tests(self): """ Fire up the Django test suite developed for version 1.2 """ apps = [app for app in self.apps] apps += ['%s.tests' % app for app in self.apps] settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': os.path.join(self.DIRNAME, 'database.db'), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } }, CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', } }, INSTALLED_APPS=self.INSTALLED_APPS + tuple(apps), STATIC_ROOT='.', STATIC_URL='/static/', ROOT_URLCONF='mapentity.tests.urls', MEDIA_URL='/media/', MEDIA_URL_SECURE='/media_secure/', MEDIA_ROOT='/tmp/', MIDDLEWARE_CLASSES=( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'mapentity.middleware.AutoLoginMiddleware' ), TEMPLATE_CONTEXT_PROCESSORS=( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.contrib.messages.context_processors.messages", "django.core.context_processors.request", "mapentity.context_processors.settings", ), TEMPLATE_DIRS=( os.path.join(self.DIRNAME, 'mapentity'), ), SRID=3857, COMPRESS_ENABLED=False, TEST=True ) from django.test.simple import DjangoTestSuiteRunner runner = DjangoTestSuiteRunner() failures = runner.run_tests(self.apps, verbosity=1) if failures: # pragma: no cover sys.exit(failures) if __name__ == '__main__': """ What do when the user hits this file from the shell. Example usage: $ python quicktest.py app1 app2 """ parser = argparse.ArgumentParser( usage="[args]", description="Run Django tests on the provided applications." ) parser.add_argument('apps', nargs='+', type=str) args = parser.parse_args() QuickDjangoTest(*args.apps)
Anaethelion/django-mapentity
quicktest.py
Python
bsd-3-clause
3,994
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import errno import os import shutil import sys import tempfile import time from datetime import datetime, timedelta from io import BytesIO try: import threading except ImportError: import dummy_threading as threading from django.conf import settings from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured from django.core.files.base import File, ContentFile from django.core.files.images import get_image_dimensions from django.core.files.storage import FileSystemStorage, get_storage_class from django.core.files.uploadedfile import UploadedFile from django.test import SimpleTestCase from django.utils import six from django.utils import unittest from django.test.utils import override_settings from ..servers.tests import LiveServerBase # Try to import PIL in either of the two ways it can end up installed. # Checking for the existence of Image is enough for CPython, but # for PyPy, you need to check for the underlying modules try: from PIL import Image, _imaging except ImportError: try: import Image, _imaging except ImportError: Image = None class GetStorageClassTests(SimpleTestCase): def test_get_filesystem_storage(self): """ get_storage_class returns the class for a storage backend name/path. """ self.assertEqual( get_storage_class('django.core.files.storage.FileSystemStorage'), FileSystemStorage) def test_get_invalid_storage_module(self): """ get_storage_class raises an error if the requested import don't exist. """ self.assertRaisesMessage( ImproperlyConfigured, "NonExistingStorage isn't a storage module.", get_storage_class, 'NonExistingStorage') def test_get_nonexisting_storage_class(self): """ get_storage_class raises an error if the requested class don't exist. """ self.assertRaisesMessage( ImproperlyConfigured, 'Storage module "django.core.files.storage" does not define a '\ '"NonExistingStorage" class.', get_storage_class, 'django.core.files.storage.NonExistingStorage') def test_get_nonexisting_storage_module(self): """ get_storage_class raises an error if the requested module don't exist. """ # Error message may or may not be the fully qualified path. six.assertRaisesRegex(self, ImproperlyConfigured, ('Error importing storage module django.core.files.non_existing_' 'storage: "No module named .*non_existing_storage'), get_storage_class, 'django.core.files.non_existing_storage.NonExistingStorage' ) class FileStorageTests(unittest.TestCase): storage_class = FileSystemStorage def setUp(self): self.temp_dir = tempfile.mkdtemp() self.storage = self.storage_class(location=self.temp_dir, base_url='/test_media_url/') # Set up a second temporary directory which is ensured to have a mixed # case name. self.temp_dir2 = tempfile.mkdtemp(suffix='aBc') def tearDown(self): shutil.rmtree(self.temp_dir) shutil.rmtree(self.temp_dir2) def test_emtpy_location(self): """ Makes sure an exception is raised if the location is empty """ storage = self.storage_class(location='') self.assertEqual(storage.base_location, '') self.assertEqual(storage.location, os.getcwd()) def test_file_access_options(self): """ Standard file access options are available, and work as expected. """ self.assertFalse(self.storage.exists('storage_test')) f = self.storage.open('storage_test', 'w') f.write('storage contents') f.close() self.assertTrue(self.storage.exists('storage_test')) f = self.storage.open('storage_test', 'r') self.assertEqual(f.read(), 'storage contents') f.close() self.storage.delete('storage_test') self.assertFalse(self.storage.exists('storage_test')) def test_file_accessed_time(self): """ File storage returns a Datetime object for the last accessed time of a file. """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) atime = self.storage.accessed_time(f_name) self.assertEqual(atime, datetime.fromtimestamp( os.path.getatime(self.storage.path(f_name)))) self.assertTrue(datetime.now() - self.storage.accessed_time(f_name) < timedelta(seconds=2)) self.storage.delete(f_name) def test_file_created_time(self): """ File storage returns a Datetime object for the creation time of a file. """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) ctime = self.storage.created_time(f_name) self.assertEqual(ctime, datetime.fromtimestamp( os.path.getctime(self.storage.path(f_name)))) self.assertTrue(datetime.now() - self.storage.created_time(f_name) < timedelta(seconds=2)) self.storage.delete(f_name) def test_file_modified_time(self): """ File storage returns a Datetime object for the last modified time of a file. """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) mtime = self.storage.modified_time(f_name) self.assertEqual(mtime, datetime.fromtimestamp( os.path.getmtime(self.storage.path(f_name)))) self.assertTrue(datetime.now() - self.storage.modified_time(f_name) < timedelta(seconds=2)) self.storage.delete(f_name) def test_file_save_without_name(self): """ File storage extracts the filename from the content object if no name is given explicitly. """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f.name = 'test.file' storage_f_name = self.storage.save(None, f) self.assertEqual(storage_f_name, f.name) self.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name))) self.storage.delete(storage_f_name) def test_file_save_with_path(self): """ Saving a pathname should create intermediate directories as necessary. """ self.assertFalse(self.storage.exists('path/to')) self.storage.save('path/to/test.file', ContentFile('file saved with path')) self.assertTrue(self.storage.exists('path/to')) with self.storage.open('path/to/test.file') as f: self.assertEqual(f.read(), b'file saved with path') self.assertTrue(os.path.exists( os.path.join(self.temp_dir, 'path', 'to', 'test.file'))) self.storage.delete('path/to/test.file') def test_file_path(self): """ File storage returns the full path of a file """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) self.assertEqual(self.storage.path(f_name), os.path.join(self.temp_dir, f_name)) self.storage.delete(f_name) def test_file_url(self): """ File storage returns a url to access a given file from the Web. """ self.assertEqual(self.storage.url('test.file'), '%s%s' % (self.storage.base_url, 'test.file')) # should encode special chars except ~!*()' # like encodeURIComponent() JavaScript function do self.assertEqual(self.storage.url(r"""~!*()'@#$%^&*abc`+ =.file"""), """/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%20%3D.file""") # should stanslate os path separator(s) to the url path separator self.assertEqual(self.storage.url("""a/b\\c.file"""), """/test_media_url/a/b/c.file""") self.storage.base_url = None self.assertRaises(ValueError, self.storage.url, 'test.file') def test_listdir(self): """ File storage returns a tuple containing directories and files. """ self.assertFalse(self.storage.exists('storage_test_1')) self.assertFalse(self.storage.exists('storage_test_2')) self.assertFalse(self.storage.exists('storage_dir_1')) f = self.storage.save('storage_test_1', ContentFile('custom content')) f = self.storage.save('storage_test_2', ContentFile('custom content')) os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1')) dirs, files = self.storage.listdir('') self.assertEqual(set(dirs), set(['storage_dir_1'])) self.assertEqual(set(files), set(['storage_test_1', 'storage_test_2'])) self.storage.delete('storage_test_1') self.storage.delete('storage_test_2') os.rmdir(os.path.join(self.temp_dir, 'storage_dir_1')) def test_file_storage_prevents_directory_traversal(self): """ File storage prevents directory traversal (files can only be accessed if they're below the storage location). """ self.assertRaises(SuspiciousOperation, self.storage.exists, '..') self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd') def test_file_storage_preserves_filename_case(self): """The storage backend should preserve case of filenames.""" # Create a storage backend associated with the mixed case name # directory. temp_storage = self.storage_class(location=self.temp_dir2) # Ask that storage backend to store a file with a mixed case filename. mixed_case = 'CaSe_SeNsItIvE' file = temp_storage.open(mixed_case, 'w') file.write('storage contents') file.close() self.assertEqual(os.path.join(self.temp_dir2, mixed_case), temp_storage.path(mixed_case)) temp_storage.delete(mixed_case) def test_makedirs_race_handling(self): """ File storage should be robust against directory creation race conditions. """ real_makedirs = os.makedirs # Monkey-patch os.makedirs, to simulate a normal call, a raced call, # and an error. def fake_makedirs(path): if path == os.path.join(self.temp_dir, 'normal'): real_makedirs(path) elif path == os.path.join(self.temp_dir, 'raced'): real_makedirs(path) raise OSError(errno.EEXIST, 'simulated EEXIST') elif path == os.path.join(self.temp_dir, 'error'): raise OSError(errno.EACCES, 'simulated EACCES') else: self.fail('unexpected argument %r' % path) try: os.makedirs = fake_makedirs self.storage.save('normal/test.file', ContentFile('saved normally')) with self.storage.open('normal/test.file') as f: self.assertEqual(f.read(), b'saved normally') self.storage.save('raced/test.file', ContentFile('saved with race')) with self.storage.open('raced/test.file') as f: self.assertEqual(f.read(), b'saved with race') # Check that OSErrors aside from EEXIST are still raised. self.assertRaises(OSError, self.storage.save, 'error/test.file', ContentFile('not saved')) finally: os.makedirs = real_makedirs def test_remove_race_handling(self): """ File storage should be robust against file removal race conditions. """ real_remove = os.remove # Monkey-patch os.remove, to simulate a normal call, a raced call, # and an error. def fake_remove(path): if path == os.path.join(self.temp_dir, 'normal.file'): real_remove(path) elif path == os.path.join(self.temp_dir, 'raced.file'): real_remove(path) raise OSError(errno.ENOENT, 'simulated ENOENT') elif path == os.path.join(self.temp_dir, 'error.file'): raise OSError(errno.EACCES, 'simulated EACCES') else: self.fail('unexpected argument %r' % path) try: os.remove = fake_remove self.storage.save('normal.file', ContentFile('delete normally')) self.storage.delete('normal.file') self.assertFalse(self.storage.exists('normal.file')) self.storage.save('raced.file', ContentFile('delete with race')) self.storage.delete('raced.file') self.assertFalse(self.storage.exists('normal.file')) # Check that OSErrors aside from ENOENT are still raised. self.storage.save('error.file', ContentFile('delete with error')) self.assertRaises(OSError, self.storage.delete, 'error.file') finally: os.remove = real_remove def test_file_chunks_error(self): """ Test behaviour when file.chunks() is raising an error """ f1 = ContentFile('chunks fails') def failing_chunks(): raise IOError f1.chunks = failing_chunks with self.assertRaises(IOError): self.storage.save('error.file', f1) class CustomStorage(FileSystemStorage): def get_available_name(self, name): """ Append numbers to duplicate files rather than underscores, like Trac. """ parts = name.split('.') basename, ext = parts[0], parts[1:] number = 2 while self.exists(name): name = '.'.join([basename, str(number)] + ext) number += 1 return name class CustomStorageTests(FileStorageTests): storage_class = CustomStorage def test_custom_get_available_name(self): first = self.storage.save('custom_storage', ContentFile('custom contents')) self.assertEqual(first, 'custom_storage') second = self.storage.save('custom_storage', ContentFile('more contents')) self.assertEqual(second, 'custom_storage.2') self.storage.delete(first) self.storage.delete(second) class UnicodeFileNameTests(unittest.TestCase): def test_unicode_file_names(self): """ Regression test for #8156: files with unicode names I can't quite figure out the encoding situation between doctest and this file, but the actual repr doesn't matter; it just shouldn't return a unicode object. """ uf = UploadedFile(name='¿Cómo?',content_type='text') self.assertEqual(type(uf.__repr__()), str) # Tests for a race condition on file saving (#4948). # This is written in such a way that it'll always pass on platforms # without threading. class SlowFile(ContentFile): def chunks(self): time.sleep(1) return super(ContentFile, self).chunks() class FileSaveRaceConditionTest(unittest.TestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) self.thread = threading.Thread(target=self.save_file, args=['conflict']) def tearDown(self): shutil.rmtree(self.storage_dir) def save_file(self, name): name = self.storage.save(name, SlowFile(b"Data")) def test_race_condition(self): self.thread.start() name = self.save_file('conflict') self.thread.join() self.assertTrue(self.storage.exists('conflict')) self.assertTrue(self.storage.exists('conflict_1')) self.storage.delete('conflict') self.storage.delete('conflict_1') @unittest.skipIf(sys.platform.startswith('win'), "Windows only partially supports umasks and chmod.") class FileStoragePermissions(unittest.TestCase): def setUp(self): self.umask = 0o027 self.old_umask = os.umask(self.umask) self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) def tearDown(self): shutil.rmtree(self.storage_dir) os.umask(self.old_umask) @override_settings(FILE_UPLOAD_PERMISSIONS=0o654) def test_file_upload_permissions(self): name = self.storage.save("the_file", ContentFile("data")) actual_mode = os.stat(self.storage.path(name))[0] & 0o777 self.assertEqual(actual_mode, 0o654) @override_settings(FILE_UPLOAD_PERMISSIONS=None) def test_file_upload_default_permissions(self): fname = self.storage.save("some_file", ContentFile("data")) mode = os.stat(self.storage.path(fname))[0] & 0o777 self.assertEqual(mode, 0o666 & ~self.umask) class FileStoragePathParsing(unittest.TestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) def tearDown(self): shutil.rmtree(self.storage_dir) def test_directory_with_dot(self): """Regression test for #9610. If the directory name contains a dot and the file name doesn't, make sure we still mangle the file name instead of the directory name. """ self.storage.save('dotted.path/test', ContentFile("1")) self.storage.save('dotted.path/test', ContentFile("2")) self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path'))) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test'))) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_1'))) def test_first_character_dot(self): """ File names with a dot as their first character don't have an extension, and the underscore should get added to the end. """ self.storage.save('dotted.path/.test', ContentFile("1")) self.storage.save('dotted.path/.test', ContentFile("2")) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test'))) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1'))) class DimensionClosingBug(unittest.TestCase): """ Test that get_image_dimensions() properly closes files (#8817) """ @unittest.skipUnless(Image, "PIL not installed") def test_not_closing_of_files(self): """ Open files passed into get_image_dimensions() should stay opened. """ empty_io = BytesIO() try: get_image_dimensions(empty_io) finally: self.assertTrue(not empty_io.closed) @unittest.skipUnless(Image, "PIL not installed") def test_closing_of_filenames(self): """ get_image_dimensions() called with a filename should closed the file. """ # We need to inject a modified open() builtin into the images module # that checks if the file was closed properly if the function is # called with a filename instead of an file object. # get_image_dimensions will call our catching_open instead of the # regular builtin one. class FileWrapper(object): _closed = [] def __init__(self, f): self.f = f def __getattr__(self, name): return getattr(self.f, name) def close(self): self._closed.append(True) self.f.close() def catching_open(*args): return FileWrapper(open(*args)) from django.core.files import images images.open = catching_open try: get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png")) finally: del images.open self.assertTrue(FileWrapper._closed) class InconsistentGetImageDimensionsBug(unittest.TestCase): """ Test that get_image_dimensions() works properly after various calls using a file handler (#11158) """ @unittest.skipUnless(Image, "PIL not installed") def test_multiple_calls(self): """ Multiple calls of get_image_dimensions() should return the same size. """ from django.core.files.images import ImageFile img_path = os.path.join(os.path.dirname(__file__), "test.png") image = ImageFile(open(img_path, 'rb')) image_pil = Image.open(img_path) size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image) self.assertEqual(image_pil.size, size_1) self.assertEqual(size_1, size_2) class ContentFileTestCase(unittest.TestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) def tearDown(self): shutil.rmtree(self.storage_dir) def test_content_file_default_name(self): self.assertEqual(ContentFile(b"content").name, None) def test_content_file_custom_name(self): """ Test that the constructor of ContentFile accepts 'name' (#16590). """ name = "I can have a name too!" self.assertEqual(ContentFile(b"content", name=name).name, name) def test_content_file_input_type(self): """ Test that ContentFile can accept both bytes and unicode and that the retrieved content is of the same type. """ self.assertTrue(isinstance(ContentFile(b"content").read(), bytes)) if six.PY3: self.assertTrue(isinstance(ContentFile("español").read(), six.text_type)) else: self.assertTrue(isinstance(ContentFile("español").read(), bytes)) def test_content_saving(self): """ Test that ContentFile can be saved correctly with the filesystem storage, both if it was initialized with string or unicode content""" self.storage.save('bytes.txt', ContentFile(b"content")) self.storage.save('unicode.txt', ContentFile("español")) class NoNameFileTestCase(unittest.TestCase): """ Other examples of unnamed files may be tempfile.SpooledTemporaryFile or urllib.urlopen() """ def test_noname_file_default_name(self): self.assertEqual(File(BytesIO(b'A file with no name')).name, None) def test_noname_file_get_size(self): self.assertEqual(File(BytesIO(b'A file with no name')).size, 19) class FileLikeObjectTestCase(LiveServerBase): """ Test file-like objects (#15644). """ def setUp(self): self.temp_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(location=self.temp_dir) def tearDown(self): shutil.rmtree(self.temp_dir) def test_urllib2_urlopen(self): """ Test the File storage API with a file like object coming from urllib2.urlopen() """ file_like_object = self.urlopen('/example_view/') f = File(file_like_object) stored_filename = self.storage.save("remote_file.html", f) stored_file = self.storage.open(stored_filename) remote_file = self.urlopen('/example_view/') self.assertEqual(stored_file.read(), remote_file.read())
chrisfranzen/django
tests/regressiontests/file_storage/tests.py
Python
bsd-3-clause
23,517
from amqplib import client_0_8 as amqp queue_name = "Game1" queue_exchange = "Game1" queue_rooting_key = "Game1" consumer_tag = "Game1" # connect to server lConnection = amqp.Connection(host="localhost:5672", userid="guest", password="guest", virtual_host="/", insist=False) lChannel = lConnection.channel() lChannel.queue_declare(queue=queue_name, durable=True, exclusive=False, auto_delete=False) lChannel.exchange_declare(exchange=queue_exchange, type="direct", durable=True, auto_delete=False) lChannel.queue_bind(queue=queue_name, exchange=queue_exchange, routing_key=queue_rooting_key) def data_receieved(msg): print('Received: ' + msg.body) lChannel.basic_consume(queue=queue_name, no_ack=True, callback=data_receieved, consumer_tag=consumer_tag) while True: lChannel.wait() lChannel.basic_cancel(consumer_tag) lChannel.close() lConnection.close()
Vallher/siemienskathon
staff/quetest.py
Python
apache-2.0
874
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-04-23 19:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('zerver', '0075_attachment_path_id_unique'), ] operations = [ migrations.AddField( model_name='userprofile', name='emojiset', field=models.CharField(choices=[('apple', 'Apple style'), ('emojione', 'Emoji One style'), ('google', 'Google style'), ('twitter', 'Twitter style')], default='google', max_length=20), ), ]
amanharitsh123/zulip
zerver/migrations/0076_userprofile_emojiset.py
Python
apache-2.0
567
import sys import platform import twisted import scrapy from scrapy.command import ScrapyCommand class Command(ScrapyCommand): def syntax(self): return "[-v]" def short_desc(self): return "Print Scrapy version" def add_options(self, parser): ScrapyCommand.add_options(self, parser) parser.add_option("--verbose", "-v", dest="verbose", action="store_true", help="also display twisted/python/platform info (useful for bug reports)") def run(self, args, opts): if opts.verbose: print "Scrapy : %s" % scrapy.__version__ print "Twisted : %s" % twisted.version.short() print "Python : %s" % sys.version.replace("\n", "- ") print "Platform: %s" % platform.platform() else: print "Scrapy %s" % scrapy.__version__
openhatch/oh-mainline
vendor/packages/scrapy/scrapy/commands/version.py
Python
agpl-3.0
850
#!/usr/bin/env python2 from os import path import sys import wordcloud d = path.dirname(__file__) # Read the whole text. text = open(path.join(d, 'alice.txt')).read() # Separate into a list of (word, frequency). words = wordcloud.process_text(text, max_features=2000) # Compute the position of the words. elements = wordcloud.fit_words(words, width=500, height=500) # Draw the positioned words to a PNG file. wordcloud.draw(elements, path.join(d, 'alice.png'), width=500, height=500, scale=2)
0x0all/word_cloud
examples/more.py
Python
mit
504
from nba_ss_db import CONFIG CONFIG['DB_NAME'] = 'test_db' CONFIG['DB_PATH'] = 'tests/test_db/databases' from nba_ss_db import db def init_test_db(): db.utils.drop_tables() db.initialize.init_db() db.utils.execute_sql("""CREATE TABLE IF NOT EXISTS player_ids (PLAYER_ID text, PLAYER_NAME text, SEASON text);""")
jsonchin/nba_stats_scraper_db_storage
tests/test_setup.py
Python
apache-2.0
358
def checkio(land): result = 0 rocks = unmatched(land) if len(rocks) == 0: return len(land) * len(land[0]) for i in range(len(land)): for j in range(len(land[i])): temp = count(land, i, j, rocks, len(land), len(land[i])) if temp > result: result = temp return result def unmatched(land): result = [] for i in range(len(land)): for j in range(len(land[i])): if land[i][j] != 'G' and land[i][j] != 'S': result.append([i, j]) return result def count(land, i, j, rocks, lbound, rbound): if [i, j] in rocks: return 0 possibleRocks = [e for e in rocks if i <= e[0] < lbound and j <= e[1] < rbound] if len(possibleRocks) == 0: return (lbound - i) * (rbound - j) condition1 = 0 if len(possibleRocks) > 0: possibleRocks.sort(key=lambda x: x[0]) lbounditem = possibleRocks[0] condition1 = count(land, i, j, rocks, lbound, lbounditem[1]) else: lbounditem = [lbound, j] condition2 = 0 if (len(possibleRocks)) > 0: possibleRocks.sort(key=lambda x: x[1]) rbounditem = possibleRocks[0] condition2 = count(land, i, j, rocks, rbounditem[0], rbound) else: rbounditem = [i, rbound] if len(rbounditem) > 0 and len(lbounditem) > 0: condition3 = (lbounditem[0] - i) * (rbounditem[1] - j) return max(condition1, condition2, condition3) if __name__ == '__main__': assert checkio(['G']) == 1, 'First' assert checkio(['GS', 'GS']) == 4, 'Second' assert checkio(['GT', 'GG']) == 2, 'Third' assert checkio(['GGTGG', 'TGGGG', 'GSSGT', 'GGGGT', 'GWGGG', 'RGTRT', 'RTGWT', 'WTWGR']) == 9, 'Forth'
edwardzhu/checkio-solution
CheckIO/Scientific Expedition/landingStrip.py
Python
mit
1,747
# Copyright 2014 Netflix, 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. # Insert any config items for local devleopment here. # This will be fed into Flask/SQLAlchemy inside security_monkey/__init__.py LOG_LEVEL = "DEBUG" LOG_FILE = "security_monkey-local.log" SQLALCHEMY_DATABASE_URI = 'postgresql://securitymonkeyuser:securitymonkeypass@localhost:5432/securitymonkeydb' SQLALCHEMY_POOL_SIZE = 50 SQLALCHEMY_MAX_OVERFLOW = 15 ENVIRONMENT = 'local' USE_ROUTE53 = False FQDN = '127.0.0.1' API_PORT = '5000' WEB_PORT = '8080' WEB_PATH = '/ui.html' FRONTED_BY_NGINX = False NGINX_PORT = '80' BASE_URL = 'http://{}:{}{}'.format(FQDN, WEB_PORT, WEB_PATH) SECRET_KEY = '<INSERT_RANDOM_STRING_HERE>' MAIL_DEFAULT_SENDER = 'securitymonkey@example.com' SECURITY_REGISTERABLE = True SECURITY_CONFIRMABLE = False SECURITY_RECOVERABLE = False SECURITY_PASSWORD_HASH = 'bcrypt' SECURITY_PASSWORD_SALT = '<INSERT_RANDOM_STRING_HERE>' SECURITY_POST_LOGIN_VIEW = BASE_URL SECURITY_POST_REGISTER_VIEW = BASE_URL SECURITY_POST_CONFIRM_VIEW = BASE_URL SECURITY_POST_RESET_VIEW = BASE_URL SECURITY_POST_CHANGE_VIEW = BASE_URL # This address gets all change notifications SECURITY_TEAM_EMAIL = ['securityteam@example.com'] # These are only required if using SMTP instead of SES EMAILS_USE_SMTP = False # Otherwise, Use SES MAIL_SERVER = 'smtp.example.com' MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USERNAME = 'username' MAIL_PASSWORD = 'password'
JaguarSecurity/SMG
env-config/config-local.py
Python
apache-2.0
1,982
# Basic OBJ file viewer. needs objloader from: # http://www.pygame.org/wiki/OBJFileLoader # LMB + move: rotate # RMB + move: pan # Scroll wheel: zoom in/out import sys, pygame from pygame.locals import * from pygame.constants import * from OpenGL.GL import * from OpenGL.GLU import * # IMPORT OBJECT LOADER from objloader import * pygame.init() viewport = (800, 600) # hx = viewport[0]/2 # hy = viewport[1]/2 srf = pygame.display.set_mode(viewport, OPENGL | DOUBLEBUF) glLightfv(GL_LIGHT0, GL_POSITION, (-40, 2000, 1000, 0.0)) glLightfv(GL_LIGHT0, GL_AMBIENT, (0.2, 0.2, 0.2, 1.0)) glLightfv(GL_LIGHT0, GL_DIFFUSE, (0.5, 0.5, 0.5, 1.0)) glEnable(GL_LIGHT0) glEnable(GL_LIGHTING) glEnable(GL_COLOR_MATERIAL) glEnable(GL_DEPTH_TEST) glShadeModel(GL_SMOOTH) # most obj files expect to be smooth-shaded # LOAD OBJECT AFTER PYGAME INIT obj = OBJ(sys.argv[1], swapyz=False) clock = pygame.time.Clock() glMatrixMode(GL_PROJECTION) glLoadIdentity() width, height = viewport gluPerspective(90.0, width/float(height), 1, 100.0) glEnable(GL_DEPTH_TEST) glMatrixMode(GL_MODELVIEW) rx, ry = (0,0) tx, ty = (0,0) zpos = 5 rotate = move = False while 1: clock.tick(30) for e in pygame.event.get(): if e.type == QUIT: sys.exit() elif e.type == KEYDOWN and e.key == K_ESCAPE: sys.exit() elif e.type == MOUSEBUTTONDOWN: if e.button == 4: zpos = max(1, zpos-1) elif e.button == 5: zpos += 1 elif e.button == 1: rotate = True elif e.button == 3: move = True elif e.type == MOUSEBUTTONUP: if e.button == 1: rotate = False elif e.button == 3: move = False elif e.type == MOUSEMOTION: i, j = e.rel if rotate: rx += i ry += j if move: tx += i ty -= j glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() # RENDER OBJECT glTranslate(tx/20., ty/20., - zpos) glRotate(ry, 1, 0, 0) glRotate(rx, 0, 1, 0) glCallList(obj.gl_list) pygame.display.flip()
jennifersalas/3D_CA
objefileviewer.py
Python
agpl-3.0
2,135
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. import pytest from shuup.notify.base import Event from shuup_tests.notify.fixtures import ATestEvent, get_initialized_test_event @pytest.mark.django_db def test_event_init(): assert get_initialized_test_event().variable_values def test_extra_vars_fails(): with pytest.raises(ValueError): ATestEvent(not_valid=True) def test_missing_vars_fails(): with pytest.raises(ValueError): ATestEvent(just_some_text="Hello") def test_init_empty_fails(): with pytest.raises(ValueError): Event() def test_auto_name(): assert ATestEvent.name == "Test Event"
shoopio/shoop
shuup_tests/notify/test_event.py
Python
agpl-3.0
852
#!/usr/bin/env python import argparse import os import shutil import string import subprocess import sys import tempfile BUFFSIZE = 1048576 # Translation table for reverse Complement, with ambiguity codes. DNA_COMPLEMENT = string.maketrans("ACGTRYKMBDHVacgtrykmbdhv", "TGCAYRMKVHDBtgcayrmkvhdb") def reverse(sequence): # Reverse sequence string. return sequence[::-1] def dna_complement(sequence): # Complement DNA sequence string. return sequence.translate(DNA_COMPLEMENT) def dna_reverse_complement(sequence): # Returns the reverse complement of the sequence. sequence = reverse(sequence) return dna_complement(sequence) def stop_err(msg): sys.stderr.write(msg) sys.exit(1) parser = argparse.ArgumentParser() parser.add_argument('--input_motifs', dest='input_motifs', help='MEME output formatted files for input to fimo') parser.add_argument('--input_fasta', dest='input_fasta', help='Fassta sequence file') parser.add_argument('--options_type', dest='options_type', help='Basic or Advance options') parser.add_argument('--input_psp', dest='input_psp', default=None, help='File containing position specific priors') parser.add_argument('--input_prior_dist', dest='input_prior_dist', default=None, help='File containing binned distribution of priors') parser.add_argument('--alpha', dest='alpha', type=float, default=1.0, help='The alpha parameter for calculating position specific priors') parser.add_argument('--bgfile', dest='bgfile', default=None, help='Background file type, used only if not "default"') parser.add_argument('--max_strand', action='store_true', help='If matches on both strands at a given position satisfy the output threshold, only report the match for the strand with the higher score') parser.add_argument('--max_stored_scores', dest='max_stored_scores', type=int, help='Maximum score count to store') parser.add_argument('--motif', dest='motifs', action='append', default=[], help='Specify motif by id') parser.add_argument('--motif_pseudo', dest='motif_pseudo', type=float, default=0.1, help='Pseudocount to add to counts in motif matrix') parser.add_argument('--no_qvalue', action='store_true', help='Do not compute a q-value for each p-value') parser.add_argument('--norc', action='store_true', help='Do not score the reverse complement DNA strand') parser.add_argument('--output_path', dest='output_path', help='Output files directory') parser.add_argument('--parse_genomic_coord', action='store_true', help='Check each sequence header for UCSC style genomic coordinates') parser.add_argument('--qv_thresh', action='store_true', help='Use q-values for the output threshold') parser.add_argument('--thresh', dest='thresh', type=float, help='p-value threshold') parser.add_argument('--gff_output', dest='gff_output', help='Gff output file') parser.add_argument('--html_output', dest='html_output', help='HTML output file') parser.add_argument('--interval_output', dest='interval_output', help='Interval output file') parser.add_argument('--txt_output', dest='txt_output', help='Text output file') parser.add_argument('--xml_output', dest='xml_output', help='XML output file') args = parser.parse_args() fimo_cmd_list = ['fimo'] if args.options_type == 'advanced': fimo_cmd_list.append('--alpha %4f' % args.alpha) if args.bgfile is not None: fimo_cmd_list.append('--bgfile "%s"' % args.bgfile) if args.max_strand: fimo_cmd_list.append('--max-strand') fimo_cmd_list.append('--max-stored-scores %d' % args.max_stored_scores) if len(args.motifs) > 0: for motif in args.motifs: fimo_cmd_list.append('--motif "%s"' % motif) fimo_cmd_list.append('--motif-pseudo %4f' % args.motif_pseudo) if args.no_qvalue: fimo_cmd_list.append('--no-qvalue') if args.norc: fimo_cmd_list.append('--norc') if args.parse_genomic_coord: fimo_cmd_list.append('--parse-genomic-coord') if args.qv_thresh: fimo_cmd_list.append('--qv-thresh') fimo_cmd_list.append('--thresh %4f' % args.thresh) if args.input_psp is not None: fimo_cmd_list.append('--psp "%s"' % args.input_psp) if args.input_prior_dist is not None: fimo_cmd_list.append('--prior-dist "%s"' % args.input_prior_dist) fimo_cmd_list.append('--o "%s"' % (args.output_path)) fimo_cmd_list.append('--verbosity 1') fimo_cmd_list.append(args.input_motifs) fimo_cmd_list.append(args.input_fasta) fimo_cmd = ' '.join(fimo_cmd_list) try: tmp_stderr = tempfile.NamedTemporaryFile() proc = subprocess.Popen(args=fimo_cmd, shell=True, stderr=tmp_stderr) returncode = proc.wait() tmp_stderr.seek(0) stderr = '' try: while True: stderr += tmp_stderr.read(BUFFSIZE) if not stderr or len(stderr) % BUFFSIZE != 0: break except OverflowError: pass if returncode != 0: stop_err(stderr) except Exception as e: stop_err('Error running FIMO:\n%s' % str(e)) shutil.move(os.path.join(args.output_path, 'fimo.txt'), args.txt_output) shutil.move(os.path.join(args.output_path, 'fimo.gff'), args.gff_output) shutil.move(os.path.join(args.output_path, 'fimo.xml'), args.xml_output) shutil.move(os.path.join(args.output_path, 'fimo.html'), args.html_output) out_file = open(args.interval_output, 'wb') out_file.write("#%s\n" % "\t".join(("chr", "start", "end", "pattern name", "score", "strand", "matched sequence", "p-value", "q-value"))) for line in open(args.txt_output): if line.startswith('#'): continue fields = line.rstrip("\n\r").split("\t") start, end = int(fields[2]), int(fields[3]) sequence = fields[7] if start > end: # Flip start and end and set strand. start, end = end, start strand = "-" # We want sequences relative to strand; FIMO always provides + stranded sequence. sequence = dna_reverse_complement(sequence) else: strand = "+" # Make 0-based start position. start -= 1 out_file.write("%s\n" % "\t".join([fields[1], str(start), str(end), fields[0], fields[4], strand, sequence, fields[5], fields[6]])) out_file.close()
ASaiM/tools-iuc
tools/meme/fimo_wrapper.py
Python
mit
6,150
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains utilities for downloading and converting datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import tarfile import zipfile from six.moves import urllib import tensorflow as tf LABELS_FILENAME = 'labels.txt' def int64_feature(values): """Returns a TF-Feature of int64s. Args: values: A scalar or list of values. Returns: A TF-Feature. """ if not isinstance(values, (tuple, list)): values = [values] return tf.train.Feature(int64_list=tf.train.Int64List(value=values)) def bytes_list_feature(values): """Returns a TF-Feature of list of bytes. Args: values: A string or list of strings. Returns: A TF-Feature. """ return tf.train.Feature(bytes_list=tf.train.BytesList(value=values)) def float_list_feature(values): """Returns a TF-Feature of list of floats. Args: values: A float or list of floats. Returns: A TF-Feature. """ return tf.train.Feature(float_list=tf.train.FloatList(value=values)) def bytes_feature(values): """Returns a TF-Feature of bytes. Args: values: A string. Returns: A TF-Feature. """ return tf.train.Feature(bytes_list=tf.train.BytesList(value=[values])) def float_feature(values): """Returns a TF-Feature of floats. Args: values: A scalar of list of values. Returns: A TF-Feature. """ if not isinstance(values, (tuple, list)): values = [values] return tf.train.Feature(float_list=tf.train.FloatList(value=values)) def image_to_tfexample(image_data, image_format, height, width, class_id): return tf.train.Example(features=tf.train.Features(feature={ 'image/encoded': bytes_feature(image_data), 'image/format': bytes_feature(image_format), 'image/class/label': int64_feature(class_id), 'image/height': int64_feature(height), 'image/width': int64_feature(width), })) def download_url(url, dataset_dir): """Downloads the tarball or zip file from url into filepath. Args: url: The URL of a tarball or zip file. dataset_dir: The directory where the temporary files are stored. Returns: filepath: path where the file is downloaded. """ filename = url.split('/')[-1] filepath = os.path.join(dataset_dir, filename) def _progress(count, block_size, total_size): sys.stdout.write('\r>> Downloading %s %.1f%%' % ( filename, float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush() filepath, _ = urllib.request.urlretrieve(url, filepath, _progress) print() statinfo = os.stat(filepath) print('Successfully downloaded', filename, statinfo.st_size, 'bytes.') return filepath def download_and_uncompress_tarball(tarball_url, dataset_dir): """Downloads the `tarball_url` and uncompresses it locally. Args: tarball_url: The URL of a tarball file. dataset_dir: The directory where the temporary files are stored. """ filepath = download_url(tarball_url, dataset_dir) tarfile.open(filepath, 'r:gz').extractall(dataset_dir) def download_and_uncompress_zipfile(zip_url, dataset_dir): """Downloads the `zip_url` and uncompresses it locally. Args: zip_url: The URL of a zip file. dataset_dir: The directory where the temporary files are stored. """ filename = zip_url.split('/')[-1] filepath = os.path.join(dataset_dir, filename) if tf.gfile.Exists(filepath): print('File {filename} has been already downloaded at {filepath}. ' 'Unzipping it....'.format(filename=filename, filepath=filepath)) else: filepath = download_url(zip_url, dataset_dir) with zipfile.ZipFile(filepath, 'r') as zip_file: for member in zip_file.namelist(): memberpath = os.path.join(dataset_dir, member) # extract only if file doesn't exist if not (os.path.exists(memberpath) or os.path.isfile(memberpath)): zip_file.extract(member, dataset_dir) def write_label_file(labels_to_class_names, dataset_dir, filename=LABELS_FILENAME): """Writes a file with the list of class names. Args: labels_to_class_names: A map of (integer) labels to class names. dataset_dir: The directory in which the labels file should be written. filename: The filename where the class names are written. """ labels_filename = os.path.join(dataset_dir, filename) with tf.gfile.Open(labels_filename, 'w') as f: for label in labels_to_class_names: class_name = labels_to_class_names[label] f.write('%d:%s\n' % (label, class_name)) def has_labels(dataset_dir, filename=LABELS_FILENAME): """Specifies whether or not the dataset directory contains a label map file. Args: dataset_dir: The directory in which the labels file is found. filename: The filename where the class names are written. Returns: `True` if the labels file exists and `False` otherwise. """ return tf.gfile.Exists(os.path.join(dataset_dir, filename)) def read_label_file(dataset_dir, filename=LABELS_FILENAME): """Reads the labels file and returns a mapping from ID to class name. Args: dataset_dir: The directory in which the labels file is found. filename: The filename where the class names are written. Returns: A map from a label (integer) to class name. """ labels_filename = os.path.join(dataset_dir, filename) with tf.gfile.Open(labels_filename, 'rb') as f: lines = f.read().decode() lines = lines.split('\n') lines = filter(None, lines) labels_to_class_names = {} for line in lines: index = line.index(':') labels_to_class_names[int(line[:index])] = line[index+1:] return labels_to_class_names def open_sharded_output_tfrecords(exit_stack, base_path, num_shards): """Opens all TFRecord shards for writing and adds them to an exit stack. Args: exit_stack: A context2.ExitStack used to automatically closed the TFRecords opened in this function. base_path: The base path for all shards num_shards: The number of shards Returns: The list of opened TFRecords. Position k in the list corresponds to shard k. """ tf_record_output_filenames = [ '{}-{:05d}-of-{:05d}'.format(base_path, idx, num_shards) for idx in range(num_shards) ] tfrecords = [ exit_stack.enter_context(tf.python_io.TFRecordWriter(file_name)) for file_name in tf_record_output_filenames ] return tfrecords
alexgorban/models
research/slim/datasets/dataset_utils.py
Python
apache-2.0
7,141
import os import pickle import shutil import time from datetime import datetime from os.path import exists, join, relpath from threading import Thread from typing import List, Union, Optional, Dict, Tuple import numpy as np import tensorflow as tf from tensorflow.python.training.adadelta import AdadeltaOptimizer from tensorflow.python.training.adam import AdamOptimizer from docqa import configurable from docqa.configurable import Configurable from docqa.data_processing.preprocessed_corpus import PreprocessedData from docqa.dataset import TrainingData, Dataset from docqa.evaluator import Evaluator, Evaluation, AysncEvaluatorRunner, EvaluatorRunner from docqa.model import Model from docqa.model_dir import ModelDir """ Contains the train-loop and test-loop for our models """ class SerializableOptimizer(Configurable): """ So we can record what tensorflow optimizer we used """ def __init__(self, opt_name, params=None): self.params = params self.opt_name = opt_name def get_params(self): return dict(opt_name=self.opt_name, params=self.params) def get(self, name=None): params = {} if self.params is None else self.params if self.opt_name == "Adam": if name is None: return AdamOptimizer(**params) else: return AdamOptimizer(name=name, **params) elif self.opt_name == "Adadelta": if name is None: return AdadeltaOptimizer(**params) else: return AdadeltaOptimizer(name=name, **params) else: raise NotImplemented() def init(out: ModelDir, model: Model, override=False): """ Save our intial setup into `out` """ for dir in [out.save_dir, out.log_dir]: if os.path.exists(dir): if len(os.listdir(dir)) > 0: if override: print("Clearing %d files/dirs that already existed in %s" % (len(os.listdir(dir)), dir)) shutil.rmtree(dir) os.makedirs(dir) else: raise ValueError() else: os.makedirs(dir) # JSON config just so we always have a human-readable dump of what we are working with with open(join(out.dir, "model.json"), "w") as f: f.write(configurable.config_to_json(model, indent=2)) # Actual model saved via pickle with open(join(out.dir, "model.pkl"), "wb") as f: pickle.dump(model, f) # TODO might be nicer to just have a "Trainer" object class TrainParams(Configurable): """ Parameters related to training """ def __init__(self, opt: SerializableOptimizer, num_epochs: int, eval_period: int, log_period: int, save_period: int, eval_samples: Dict[str, Optional[int]], regularization_weight: Optional[float] = None, async_encoding: Optional[int] = None, max_checkpoints_to_keep: int = 5, loss_ema: Optional[float] = .999, eval_at_zero: bool = False, monitor_ema: float = .999, ema: Optional[float] = None, best_weights: Optional[Tuple[str, str]] = None ): """ :param opt: Optimizer to use :param num_epochs: Number of epochs to train for :param eval_period: How many batches to train on between evaluations :param log_period: How many batches to train on between logging :param save_period: How many batches to train on between checkpointing :param eval_samples: How many samples to draw during evaluation, None of a full epoch :param regularization_weight: How highly to weight regulraization, defaults to 1 :param async_encoding: Encoding batches in a seperate thread, and store in a queue of this size :param max_checkpoints_to_keep: Max number of checkpoints to keep during training :param loss_ema: EMA weights for monitoring the loss during training :param eval_at_zero: Run an evaluation cycle before any training :param monitor_ema: EMA weights for monitor functions :param ema: EMA to use on the trainable parameters :param best_weights: Store the weights with the highest scores on the given eval dataset/metric """ self.async_encoding = async_encoding self.regularization_weight = regularization_weight self.max_checkpoints_to_keep = max_checkpoints_to_keep self.opt = opt self.eval_at_zero = eval_at_zero self.ema = ema self.loss_ema = loss_ema self.monitor_ema = monitor_ema self.num_epochs = num_epochs self.eval_period = eval_period self.log_period = log_period self.save_period = save_period self.eval_samples = eval_samples self.best_weights = best_weights def save_train_start(out, data: TrainingData, global_step: int, evaluators: List[Evaluator], train_params: TrainParams, notes: str): """ Record the training parameters we are about to use into `out` """ if notes is not None: with open(join(out, "train_from_%d_notes.txt" % global_step), "w") as f: f.write(notes) import socket hostname = socket.gethostname() train = dict(train_params=train_params, data=data, start_at=global_step, evaluators=evaluators, date=datetime.now().strftime("%m%d-%H%M%S"), host=hostname) with open(join(out, "train_from_%d.json" % global_step), "w") as f: f.write(configurable.config_to_json(train, indent=2)) with open(join(out, "train_from_%d.pkl" % global_step), "wb") as f: pickle.dump(train, f) def _build_train_ops(train_params): """ Bulid ops we should run during training, including learning, EMA, and summary ops""" global_step = tf.get_variable('global_step', shape=[], dtype='int32', initializer=tf.constant_initializer(0), trainable=False) loss = tf.get_collection(tf.GraphKeys.LOSSES) if len(loss) == 0: raise RuntimeError("No losses found in losses collection") loss = tf.add_n(loss, name="loss") if len(tf.get_collection(tf.GraphKeys.SUMMARIES)) > 0: # Add any summaries client stored in SUMMARIES summary_tensor = tf.summary.merge([[tf.summary.tensor_summary("loss", loss)] + tf.get_collection(tf.GraphKeys.SUMMARIES)]) else: summary_tensor = tf.summary.tensor_summary("loss", loss) train_objective = loss regularizers = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) if len(regularizers) > 0: regularization_loss = tf.add_n(regularizers, name="regularization_loss") if train_params.regularization_weight is not None: train_objective = train_objective + regularization_loss * train_params.regularization_weight else: train_objective = train_objective + regularization_loss else: regularization_loss = None opt = train_params.opt.get() train_opt = opt.apply_gradients(opt.compute_gradients(train_objective), global_step=global_step) if train_params.ema is not None: ema = tf.train.ExponentialMovingAverage(decay=train_params.ema) ema_op = ema.apply(tf.trainable_variables()) with tf.control_dependencies([train_opt]): # Run the old training op, then update the averages. train_opt = tf.group(ema_op) else: ema = None # Any collections starting with "monitor" are also added as summaries to_monitor = {} for col in tf.get_default_graph().get_all_collection_keys(): if col.startswith("monitor"): v = tf.get_collection(col) if len(v) > 0: print("Monitoring: " + col) v = tf.add_n(v) to_monitor[col] = v if len(to_monitor) > 0: monitor_ema = tf.train.ExponentialMovingAverage(decay=train_params.monitor_ema, name="MonitorEMA", zero_debias=True) train_opt = tf.group(train_opt, monitor_ema.apply(list(to_monitor.values()))) summary_tensor = tf.summary.merge( [tf.summary.scalar(col, monitor_ema.average(v)) for col, v in to_monitor.items()] + [summary_tensor]) # EMA for the loss and what we monitoring if train_params.loss_ema is not None: loss_ema = tf.train.ExponentialMovingAverage(decay=train_params.loss_ema, name="LossEMA", zero_debias=True) if regularization_loss is None: ema_op = loss_ema.apply([loss]) train_opt = tf.group(train_opt, ema_op) ema_var = loss_ema.average(loss) summary_tensor = tf.summary.merge([tf.summary.scalar("training-ema/loss", ema_var), summary_tensor]) else: to_track = [loss, train_objective, regularization_loss] ema_op = loss_ema.apply(to_track) train_opt = tf.group(train_opt, ema_op) tensor_vars = [ tf.summary.scalar("training-ema/loss", loss_ema.average(loss)), tf.summary.scalar("training-ema/objective", loss_ema.average(train_objective)), tf.summary.scalar("training-ema/regularization-loss", loss_ema.average(regularization_loss)) ] summary_tensor = tf.summary.merge([tensor_vars, summary_tensor]) return loss, summary_tensor, train_opt, global_step, ema def continue_training( data: TrainingData, model: Model, train_params: TrainParams, evaluators: List[Evaluator], out: ModelDir, notes: str = None, dry_run=False): """ Train an already existing model, or start for scatch """ if not exists(out.dir) or os.listdir(out.dir) == 0: start_training(data, model, train_params, evaluators, out, notes, dry_run) else: print("Files already exist, loading most recent model") resume_training_with(data, out, train_params, evaluators, notes, dry_run) def start_training( data: TrainingData, model: Model, train_params: TrainParams, evaluators: List[Evaluator], out: ModelDir, notes: str = None, initialize_from=None, dry_run=False): """ Train a model from scratch """ if initialize_from is None: print("Initializing model at: " + out.dir) model.init(data.get_train_corpus(), data.get_resource_loader()) # Else we assume the model has already completed its first phase of initialization if not dry_run: init(out, model, False) _train(model, data, None, initialize_from, True, train_params, evaluators, out, notes, dry_run) def resume_training(out: ModelDir, notes: str = None, dry_run=False, start_eval=False): """ Resume training an existing model """ train_params = out.get_last_train_params() model = out.get_model() train_data = train_params["data"] evaluators = train_params["evaluators"] params = train_params["train_params"] params.num_epochs = 24*3 if isinstance(train_data, PreprocessedData): # TODO don't hard code # of processes train_data.preprocess(6, 1000) latest = tf.train.latest_checkpoint(out.save_dir) if latest is None: raise ValueError("No checkpoint to resume from found in " + out.save_dir) _train(model, train_data, latest, None, False, params, evaluators, out, notes, dry_run, start_eval) def resume_training_with( data: TrainingData, out: ModelDir, train_params: TrainParams, evaluators: List[Evaluator], notes: str = None, dry_run: bool = False): """ Resume training an existing model with the specified parameters """ with open(join(out.dir, "model.pkl"), "rb") as f: model = pickle.load(f) latest = out.get_latest_checkpoint() if latest is None: raise ValueError("No checkpoint to resume from found in " + out.save_dir) _train(model, data, latest, None, False, train_params, evaluators, out, notes, dry_run) def _train(model: Model, data: TrainingData, checkpoint: Union[str, None], parameter_checkpoint: Union[str, None], save_start: bool, train_params: TrainParams, evaluators: List[Evaluator], out: ModelDir, notes=None, dry_run=False, start_eval=False): if train_params.async_encoding: _train_async(model, data, checkpoint, parameter_checkpoint, save_start, train_params, evaluators, out, notes, dry_run, start_eval) return if train_params.best_weights is not None: raise NotImplementedError # spec the model for the current voc/input/batching train = data.get_train() eval_datasets = data.get_eval() loader = data.get_resource_loader() evaluator_runner = EvaluatorRunner(evaluators, model) print("Training on %d batches" % len(train)) print("Evaluation datasets: " + " ".join("%s (%d)" % (name, len(data)) for name, data in eval_datasets.items())) print("Init model...") model.set_inputs([train] + list(eval_datasets.values()), loader) print("Setting up model prediction / tf...") sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) with sess.as_default(): pred = model.get_prediction() evaluator_runner.set_input(pred) if parameter_checkpoint is not None: print("Restoring parameters from %s" % parameter_checkpoint) saver = tf.train.Saver(tf.trainable_variables()) saver.restore(sess, parameter_checkpoint) saver = None loss, summary_tensor, train_opt, global_step, _ = _build_train_ops(train_params) # Pre-compute tensors we need at evaluations time eval_tensors = [] for ev in evaluators: eval_tensors.append(ev.tensors_needed(pred)) saver = tf.train.Saver(max_to_keep=train_params.max_checkpoints_to_keep) summary_writer = tf.summary.FileWriter(out.log_dir) # Load or initialize the model parameters if checkpoint is not None: print("Restoring training from checkpoint...") saver.restore(sess, checkpoint) print("Loaded checkpoint: " + str(sess.run(global_step))) return else: if parameter_checkpoint is not None: print("Initializing training variables...") vars = [x for x in tf.global_variables() if x not in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)] sess.run(tf.variables_initializer(vars)) else: print("Initializing parameters...") sess.run(tf.global_variables_initializer()) # Make sure no bugs occur that add to the graph in the train loop, that can cause (eventuall) OOMs tf.get_default_graph().finalize() print("Start training!") on_step = sess.run(global_step) if save_start: summary_writer.add_graph(sess.graph, global_step=on_step) save_train_start(out.dir, data, on_step, evaluators, train_params, notes) if train_params.eval_at_zero: print("Running evaluation...") start_eval = False for name, data in eval_datasets.items(): n_samples = train_params.eval_samples.get(name) evaluation = evaluator_runner.run_evaluators(sess, data, name, n_samples) for s in evaluation.to_summaries(name + "-"): summary_writer.add_summary(s, on_step) batch_time = 0 for epoch in range(train_params.num_epochs): for batch_ix, batch in enumerate(train.get_epoch()): t0 = time.perf_counter() on_step = sess.run(global_step) + 1 # +1 because all calculations are done after step get_summary = on_step % train_params.log_period == 0 encoded = model.encode(batch, True) if get_summary: summary, _, batch_loss = sess.run([summary_tensor, train_opt, loss], feed_dict=encoded) else: summary = None _, batch_loss = sess.run([train_opt, loss], feed_dict=encoded) if np.isnan(batch_loss): raise RuntimeError("NaN loss!") batch_time += time.perf_counter() - t0 if get_summary: print("on epoch=%d batch=%d step=%d time=%.3f" % (epoch, batch_ix + 1, on_step, batch_time)) summary_writer.add_summary(tf.Summary(value=[tf.Summary.Value(tag="time", simple_value=batch_time)]), on_step) summary_writer.add_summary(summary, on_step) batch_time = 0 # occasional saving if on_step % train_params.save_period == 0: print("Checkpointing") saver.save(sess, join(out.save_dir, "checkpoint-" + str(on_step)), global_step=global_step) # Occasional evaluation if (on_step % train_params.eval_period == 0) or start_eval: print("Running evaluation...") start_eval = False t0 = time.perf_counter() for name, data in eval_datasets.items(): n_samples = train_params.eval_samples.get(name) evaluation = evaluator_runner.run_evaluators(sess, data, name, n_samples) for s in evaluation.to_summaries(name + "-"): summary_writer.add_summary(s, on_step) print("Evaluation took: %.3f seconds" % (time.perf_counter() - t0)) saver.save(sess, relpath(join(out.save_dir, "checkpoint-" + str(on_step))), global_step=global_step) sess.close() def _train_async(model: Model, data: TrainingData, checkpoint: Union[str, None], parameter_checkpoint: Union[str, None], save_start: bool, train_params: TrainParams, evaluators: List[Evaluator], out: ModelDir, notes=None, dry_run=False, start_eval=False): """ Train while encoding batches on a seperate thread and storing them in a tensorflow Queue, can be much faster then using the feed_dict approach """ train = data.get_train() eval_datasets = data.get_eval() loader = data.get_resource_loader() print("Training on %d batches" % len(train)) print("Evaluation datasets: " + " ".join("%s (%d)" % (name, len(data)) for name, data in eval_datasets.items())) # spec the model for the given datasets model.set_inputs([train] + list(eval_datasets.values()), loader) placeholders = model.get_placeholders() train_queue = tf.FIFOQueue(train_params.async_encoding, [x.dtype for x in placeholders], name="train_queue") evaluator_runner = AysncEvaluatorRunner(evaluators, model, train_params.async_encoding) train_enqeue = train_queue.enqueue(placeholders) train_close = train_queue.close(True) is_train = tf.placeholder(tf.bool, ()) input_tensors = tf.cond(is_train, lambda: train_queue.dequeue(), lambda: evaluator_runner.eval_queue.dequeue()) # tensorfow can't infer the shape for an unsized queue, so set it manually for input_tensor, pl in zip(input_tensors, placeholders): input_tensor.set_shape(pl.shape) print("Init model...") sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) with sess.as_default(): pred = model.get_predictions_for(dict(zip(placeholders, input_tensors))) evaluator_runner.set_input(pred) if parameter_checkpoint is not None: print("Restoring parameters from %s" % parameter_checkpoint) saver = tf.train.Saver() saver.restore(sess, checkpoint) saver = None print("Setting up model prediction / tf...") all_vars = tf.global_variables() loss, summary_tensor, train_opt, global_step, weight_ema = _build_train_ops(train_params) # Pre-compute tensors we need at evaluations time eval_tensors = [] for ev in evaluators: eval_tensors.append(ev.tensors_needed(pred)) if train_params.best_weights is not None: lst = all_vars if weight_ema is not None: for x in lst: v = weight_ema.average(x) if v is not None: lst.append(v) best_weight_saver = tf.train.Saver(var_list=lst, max_to_keep=1) cur_best = None else: best_weight_saver = None cur_best = None saver = tf.train.Saver(max_to_keep=train_params.max_checkpoints_to_keep) summary_writer = tf.summary.FileWriter(out.log_dir) # Load or initialize the model parameters if checkpoint is not None: print("Restoring from checkpoint...") saver.restore(sess, checkpoint) print("Loaded checkpoint: " + str(sess.run(global_step))) else: print("Initializing parameters...") sess.run(tf.global_variables_initializer()) # Make sure no bugs occur that add to the graph in the train loop, that can cause (eventuall) OOMs tf.get_default_graph().finalize() if dry_run: return on_step = sess.run(global_step) if save_start: # summary_writer.add_graph(sess.graph, global_step=on_step) save_train_start(out.dir, data, sess.run(global_step), evaluators, train_params, notes) def enqueue_train(): try: # feed data from the dataset iterator -> encoder -> queue for epoch in range(train_params.num_epochs): for batch in train.get_epoch(): feed_dict = model.encode(batch, True) sess.run(train_enqeue, feed_dict) except tf.errors.CancelledError: # The queue_close operator has been called, exit gracefully return except Exception as e: # Crashes the main thread with a queue exception sess.run(train_close) raise e train_enqueue_thread = Thread(target=enqueue_train) train_enqueue_thread.daemon = True # Ensure we exit the program on an excpetion print("Start training!") batch_time = 0 train_dict = {is_train: True} eval_dict = {is_train: False} try: train_enqueue_thread.start() for epoch in range(train_params.num_epochs): for batch_ix in range(len(train)): t0 = time.perf_counter() on_step = sess.run(global_step) + 1 get_summary = on_step % train_params.log_period == 0 if get_summary: summary, _, batch_loss = sess.run([summary_tensor, train_opt, loss], feed_dict=train_dict) else: summary = None _, batch_loss = sess.run([train_opt, loss], feed_dict=train_dict) if np.isnan(batch_loss): raise RuntimeError("NaN loss!") batch_time += time.perf_counter() - t0 if summary is not None: print("on epoch=%d batch=%d step=%d, time=%.3f" % (epoch, batch_ix + 1, on_step, batch_time)) summary_writer.add_summary( tf.Summary(value=[tf.Summary.Value(tag="time", simple_value=batch_time)]), on_step) summary_writer.add_summary(summary, on_step) batch_time = 0 # occasional saving if on_step % train_params.save_period == 0: print("Checkpointing") saver.save(sess, join(out.save_dir, "checkpoint-" + str(on_step)), global_step=global_step) # Occasional evaluation if (on_step % train_params.eval_period == 0) or start_eval: print("Running evaluation...") start_eval = False t0 = time.perf_counter() for name, data in eval_datasets.items(): n_samples = train_params.eval_samples.get(name) evaluation = evaluator_runner.run_evaluators(sess, data, name, n_samples, eval_dict) for s in evaluation.to_summaries(name + "-"): summary_writer.add_summary(s, on_step) # Maybe save as the best weights if train_params.best_weights is not None and name == train_params.best_weights[0]: val = evaluation.scalars[train_params.best_weights[1]] if cur_best is None or val > cur_best: print("Save weights with current best weights (%s vs %.5f)" % ( "None" if cur_best is None else ("%.5f" % cur_best), val)) best_weight_saver.save(sess, join(out.best_weight_dir, "best"), global_step=global_step) cur_best = val print("Evaluation took: %.3f seconds" % (time.perf_counter() - t0)) finally: sess.run(train_close) # terminates the enqueue thread with an exception train_enqueue_thread.join() saver.save(sess, relpath(join(out.save_dir, "checkpoint-" + str(on_step))), global_step=global_step) sess.close() def test(model: Model, evaluators, datasets: Dict[str, Dataset], loader, checkpoint, ema=True, aysnc_encoding=None, sample=None) -> Dict[str, Evaluation]: print("Setting up model") model.set_inputs(list(datasets.values()), loader) if aysnc_encoding: evaluator_runner = AysncEvaluatorRunner(evaluators, model, aysnc_encoding) inputs = evaluator_runner.dequeue_op else: evaluator_runner = EvaluatorRunner(evaluators, model) inputs = model.get_placeholders() input_dict = {p: x for p, x in zip(model.get_placeholders(), inputs)} sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) with sess.as_default(): pred = model.get_predictions_for(input_dict) evaluator_runner.set_input(pred) print("Restoring variables") saver = tf.train.Saver() saver.restore(sess, checkpoint) if ema: # FIXME This is a bit stupid, since we are loading variables twice, but I found it # a bit fiddly to load the variables directly.... ema = tf.train.ExponentialMovingAverage(0) reader = tf.train.NewCheckpointReader(checkpoint) expected_ema_names = {ema.average_name(x): x for x in tf.trainable_variables() if reader.has_tensor(ema.average_name(x))} if len(expected_ema_names) > 0: print("Restoring EMA variables") saver = tf.train.Saver(expected_ema_names) saver.restore(sess, checkpoint) tf.get_default_graph().finalize() print("Begin evaluation") dataset_outputs = {} for name, dataset in datasets.items(): dataset_outputs[name] = evaluator_runner.run_evaluators(sess, dataset, name, sample, {}) return dataset_outputs
allenai/document-qa
docqa/trainer.py
Python
apache-2.0
27,581
# corpus.views # Views for the corpus application # # Author: Benjamin Bengfort <bbengfort@districtdatalabs.com> # Created: Sun Jul 17 19:33:46 2016 -0400 # # Copyright (C) 2016 District Data Labs # For license information, see LICENSE.txt # # ID: views.py [2de4867] benjamin@bengfort.com $ """ Views for the corpus application """ ########################################################################## ## Imports ########################################################################## from django.views.generic import DetailView from rest_framework import status from rest_framework import viewsets from rest_framework.response import Response from rest_framework.decorators import detail_route from rest_framework.exceptions import ValidationError from rest_framework.permissions import IsAuthenticated from corpus.models import Document, Annotation, Label from corpus.serializers import DocumentSerializer from corpus.serializers import AnnotationSerializer from corpus.exceptions import CorpusException ########################################################################## ## Views ########################################################################## class DocumentDetail(DetailView): model = Document template_name = 'corpus/document.html' context_object_name = 'document' labels_parent_name = 'USA Political Parties' def get_context_data(self, **kwargs): context = super(DocumentDetail, self).get_context_data(**kwargs) # Add user-specific parameters document = context['document'] annotation = document.annotations.filter(user=self.request.user).first() context['annotation'] = annotation # Add label-specific parameters # TODO Do not hard code the parent into the class! context['labels'] = Label.objects.filter( parent__name = self.labels_parent_name ) return context ########################################################################## ## API HTTP/JSON Views ########################################################################## class DocumentViewSet(viewsets.ModelViewSet): queryset = Document.objects.all() serializer_class = DocumentSerializer permission_classes = [IsAuthenticated] def create(self, request, *args, **kwargs): """ Create both the document and the annotation (user-association). """ # Deserialize and validate the data from the user. serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) # Execute the document and annotation creation self.perform_create(serializer) # Get the headers and return a response headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): """ Excepts any thing that might happen in the signals and raises a validation error in order to send back the right status code. """ try: # Create the document object long_url = serializer.validated_data['long_url'] document, _ = Document.objects.get_or_create(long_url=long_url) serializer.instance = document # Create the annotation object annotate, _ = Annotation.objects.get_or_create( user = self.request.user, document = document ) except CorpusException as e: raise ValidationError(str(e)) @detail_route(methods=['post'], permission_classes=[IsAuthenticated]) def annotate(self, request, pk=None): """ Allows the specification of an annotation (label) for the given document. Note that a user can only have one label associated with one document, for the time being. """ # Get the document of the detail view and deserialize data document = self.get_object() serializer = AnnotationSerializer( data=request.data, context={'request': request, 'document': document} ) # Validate the serializer and save the annotation serializer.is_valid(raise_exception=True) serializer.save() # Return the response return Response(serializer.data)
DistrictDataLabs/partisan-discourse
corpus/views.py
Python
apache-2.0
4,376
""" helloworld.py Author: E Dennison Credit: I figured this out on my own Assignment: Write and submit a Python program that prints the following: Hello, world! """ print("Hello, world!")
tiggerntatie/Hello-world
helloworld.py
Python
mit
192
# vim: set et ts=4 sw=4 sts=4 ai: from distutils.core import setup import dispass.dispass long_desc = '''DisPass is a passphrase generator for GNU/Linux, \*BSD, MacOS X and Windows. It enables you to generate unique passphrases formed from a master password and a label, helping you get rid of the bad habit of using a single password for multiple websites. When using a different passphrase for every website, the chance of abuse of your password on other sites (when a website leaks it) is eliminated. Dispass is a console application, but also has a simple graphical interface. ''' setup( name='DisPass', version=dispass.dispass.__version__, description=dispass.dispass.__doc__, author=dispass.dispass.__author__, author_email='benjamin@babab.nl', url='http://dispass.babab.nl/', download_url='http://pypi.python.org/pypi/DisPass/', packages = ['dispass'], license='ISC', long_description=long_desc, platforms='any', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Environment :: MacOS X', 'Environment :: Win32 (MS Windows)', 'Environment :: X11 Applications', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: ISC License (ISCL)', 'Natural Language :: Dutch', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Communications', 'Topic :: Internet', 'Topic :: Office/Business', 'Topic :: Security :: Cryptography', 'Topic :: Utilities', ], scripts=['scripts/dispass', 'scripts/gdispass', 'scripts/dispass-label'], )
ryuslash/DisPass
setup.py
Python
isc
1,721
""" flcliapi - Freelance Pattern agent class Model 3: uses ROUTER socket to address specific services Author: Min RK <benjaminrk@gmail.com> """ import threading import time import zmq from zhelpers import zpipe # If no server replies within this time, abandon request GLOBAL_TIMEOUT = 3000 # msecs # PING interval for servers we think are alivecp PING_INTERVAL = 2000 # msecs # Server considered dead if silent for this long SERVER_TTL = 6000 # msecs def flciapi_agent(peer): """This is the thread that handles our real flcliapi class """ pass # ===================================================================== # Synchronous part, works in our application thread class FreelanceClient(object): ctx = None # Our Context pipe = None # Pipe through to flciapi agent agent = None # agent in a thread def __init__(self): self.ctx = zmq.Context() self.pipe, peer = zpipe(self.ctx) self.agent = threading.Thread(target=agent_task, args=(self.ctx,peer)) self.agent.daemon = True self.agent.start() def connect(self, endpoint): """Connect to new server endpoint Sends [CONNECT][endpoint] to the agent """ self.pipe.send_multipart(["CONNECT", endpoint]) time.sleep(0.1) # Allow connection to come up def request(self, msg): "Send request, get reply" request = ["REQUEST"] + msg self.pipe.send_multipart(request) reply = self.pipe.recv_multipart() status = reply.pop(0) if status != "FAILED": return reply # ===================================================================== # Asynchronous part, works in the background # --------------------------------------------------------------------- # Simple class for one server we talk to class FreelanceServer(object): endpoint = None # Server identity/endpoint alive = True # 1 if known to be alive ping_at = 0 # Next ping at this time expires = 0 # Expires at this time def __init__(self, endpoint): self.endpoint = endpoint self.alive = True self.ping_at = time.time() + 1e-3*PING_INTERVAL self.expires = time.time() + 1e-3*SERVER_TTL def ping(self, socket): if time.time() > self.ping_at: socket.send_multipart([self.endpoint, 'PING']) self.ping_at = time.time() + 1e-3*PING_INTERVAL def tickless(self, tickless): if tickless > self.ping_at: tickless = self.ping_at return tickless # --------------------------------------------------------------------- # Simple class for one background agent class FreelanceAgent(object): ctx = None # Own context pipe = None # Socket to talk back to application router = None # Socket to talk to servers servers = None # Servers we've connected to actives = None # Servers we know are alive sequence = 0 # Number of requests ever sent request = None # Current request if any reply = None # Current reply if any expires = 0 # Timeout for request/reply def __init__(self, ctx, pipe): self.ctx = ctx self.pipe = pipe self.router = ctx.socket(zmq.ROUTER) self.servers = {} self.actives = [] def control_message (self): msg = self.pipe.recv_multipart() command = msg.pop(0) if command == "CONNECT": endpoint = msg.pop(0) print "I: connecting to %s...\n" % endpoint, self.router.connect(endpoint) server = FreelanceServer(endpoint) self.servers[endpoint] = server self.actives.append(server) # these are in the C case, but seem redundant: server.ping_at = time.time() + 1e-3*PING_INTERVAL server.expires = time.time() + 1e-3*SERVER_TTL elif command == "REQUEST": assert not self.request # Strict request-reply cycle # Prefix request with sequence number and empty envelope self.request = [str(self.sequence), ''] + msg # Request expires after global timeout self.expires = time.time() + 1e-3*GLOBAL_TIMEOUT def router_message (self): reply = self.router.recv_multipart() # Frame 0 is server that replied endpoint = reply.pop(0) server = self.servers[endpoint] if not server.alive: self.actives.append(server) server.alive = 1 server.ping_at = time.time() + 1e-3*PING_INTERVAL server.expires = time.time() + 1e-3*SERVER_TTL; # Frame 1 may be sequence number for reply sequence = reply.pop(0) if int(sequence) == self.sequence: self.sequence += 1 reply = ["OK"] + reply self.pipe.send_multipart(reply) self.request = None # --------------------------------------------------------------------- # Asynchronous agent manages server pool and handles request/reply # dialog when the application asks for it. def agent_task(ctx, pipe): agent = FreelanceAgent(ctx, pipe) poller = zmq.Poller() poller.register(agent.pipe, zmq.POLLIN) poller.register(agent.router, zmq.POLLIN) while True: # Calculate tickless timer, up to 1 hour tickless = time.time() + 3600 if (agent.request and tickless > agent.expires): tickless = agent.expires for server in agent.servers.values(): tickless = server.tickless(tickless) try: items = dict(poller.poll(1000 * (tickless - time.time()))) except: break # Context has been shut down if agent.pipe in items: agent.control_message() if agent.router in items: agent.router_message() # If we're processing a request, dispatch to next server if (agent.request): if (time.time() >= agent.expires): # Request expired, kill it agent.pipe.send("FAILED") agent.request = None else: # Find server to talk to, remove any expired ones while agent.actives: server = agent.actives[0] if time.time() >= server.expires: server.alive = 0 agent.actives.pop(0) else: request = [server.endpoint] + agent.request agent.router.send_multipart(request) break # Disconnect and delete any expired servers # Send heartbeats to idle servers if needed for server in agent.servers.values(): server.ping(agent.router)
soscpd/bee
root/tests/zguide/examples/Python/flcliapi.py
Python
mit
6,939
import tensorflow as tf import numpy as np class rec(object): def __init__(self, sentence_length,num_classes, vocab_size, embedding_size, filter_sizes,num_filters): # Placeholders for input, output, and dropout self.input_x = tf.placeholder(tf.int32, [None, paragraph_length], name = "input_x") self.input_y = tf.placeholder(tf.float32, [None, num_classes], name = "input_y") self.dropout_keep_prob = tf.placeholder(tf.float32,name="dropout_keep_prob") with tf.device('/cpu:0)', tf.name_scope("embedding"): W = tf.Variable(tf.random_uniform([vocab_size,embedding_size],-1.0,1.0),name="W") self.embedded_chars = tf.nn.embedding_lookup(W,self.input_x) self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars,-1)a pooled_outputs = [] for i, filter_size in enumerate(filter_size): with tf.name_scope("conv-maxpool-%s" % filter_size): # Convolution Layer filter_shape = [filter_size,embedding_size, 1, num_filters] W = tf.Variable(tf.truncated_normal(filter_shape,stddev=0.1),name = "W")
xXDavidHuangXx/reccomendation
main/rec.py
Python
apache-2.0
1,031
import collections import unittest from typing import List import utils class Solution: def minJumps(self, arr: List[int]) -> int: n = len(arr) d = collections.defaultdict(list) for i, num in enumerate(arr): d[num].append(i) q = collections.deque() q.append((0, 0)) visited, visited_groups = set(), set() while q: steps, index = q.popleft() if index == n - 1: return steps for neighbor in (index - 1, index + 1): if 0 <= neighbor < n and neighbor not in visited: visited.add(neighbor) q.append((steps + 1, neighbor)) if arr[index] not in visited_groups: for neighbor in d[arr[index]]: if neighbor not in visited: visited.add(neighbor) q.append((steps + 1, neighbor)) visited_groups.add(arr[index]) class Test(unittest.TestCase): def test(self): utils.test(self, __file__, Solution) if __name__ == '__main__': unittest.main()
chrisxue815/leetcode_python
problems/test_1345.py
Python
unlicense
1,144
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'chart_format19.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_filename = test_dir + '_test_' + filename self.exp_filename = test_dir + 'xlsx_files/' + filename self.ignore_files = [] self.ignore_elements = {} def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({ 'type': 'column', 'subtype': 'stacked', }) chart.axis_ids = [56127488, 57455360] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column('A1', data[0]) worksheet.write_column('B1', data[1]) worksheet.write_column('C1', data[2]) chart.add_series({'values': '=Sheet1!$A$1:$A$5'}) chart.add_series({'values': '=Sheet1!$B$1:$B$5'}) chart.add_series({'values': '=Sheet1!$C$1:$C$5', 'data_labels': {'value': 1, 'position': 'inside_base'}, }) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
jvrsantacruz/XlsxWriter
xlsxwriter/test/comparison/test_chart_format19.py
Python
bsd-2-clause
1,761
# -*- coding: utf-8 -*- """ Created on Tue Feb 14 14:49:00 2017 @author: camacho """ import Kernel;reload(Kernel);kl=Kernel import Kernel_likelihood;reload(Kernel_likelihood);lk=Kernel_likelihood import Kernel_optimization;reload(Kernel_optimization);opt=Kernel_optimization import RV_function;reload(RV_function);RVfunc=RV_function import numpy as np import matplotlib.pylab as pl import sys f=open("Test01_ESS.txt","w") sys.stdout = f #### INITIAL DATA #pl.close() #to close old plots np.random.seed(12345) x = 10 * np.sort(np.random.rand(50)) y0 = np.cos(x) yerr=np.array([np.random.uniform(0.2,0.5) for n in y0]) y=np.array([n + m for n,m in zip(y0,yerr)]) #pl.plot(x,y,'.') #pl.errorbar(x,y0,yerr,fmt='.') #pl.xlabel('x') #pl.ylabel('y') ### START TESTS print '##### Lets test the ExpSineSquared Kernel #####' print '' print '### looking at the plot the parameters seem to be amp=1.5 , period=7.0 ###' print '' kernel_ESS1=kl.ExpSineSquared(1.5, 0.1, 7.0) likelihood_ESS1=lk.likelihood(kernel_ESS1,x,x,y,yerr) print 'Kernel ESS1 ->', kernel_ESS1 print 'likelihood ESS1 ->', likelihood_ESS1 optimization1=opt.committed_optimization(kernel_ESS1,x,x,y,yerr) print 'kernel 1 final ->',optimization1[1] print 'likelihood 1 final ->', optimization1[0] print '' print '### lets test with different decreasing values to see how it behave ###' kernel_ESS2=kl.ExpSineSquared(1.2, 0.1, 6.0) likelihood_ESS2=lk.likelihood(kernel_ESS2,x,x,y,yerr) print 'Kernel ESS2 ->', kernel_ESS2 print 'likelihood ESS2 ->', likelihood_ESS2 optimization2=opt.committed_optimization(kernel_ESS2,x,x,y,yerr) print 'kernel ESS2 final ->',optimization2[1] print 'likelihood ESS2 final ->', optimization2[0] print '' kernel_ESS3=kl.ExpSineSquared(1.0, 0.1, 5.0) likelihood_ESS3=lk.likelihood(kernel_ESS3,x,x,y,yerr) print 'Kernel ESS3 ->', kernel_ESS3 print 'likelihood ESS3 ->', likelihood_ESS3 optimization3=opt.committed_optimization(kernel_ESS3,x,x,y,yerr) print 'kernel ESS3 final ->',optimization3[1] print 'likelihood ESS3 final ->', optimization3[0] print '' kernel_ESS4=kl.ExpSineSquared(0.5, 0.1, 1.0) likelihood_ESS4=lk.likelihood(kernel_ESS4,x,x,y,yerr) print 'Kernel ESS4 ->', kernel_ESS4 print 'likelihood ESS4 ->', likelihood_ESS4 optimization4=opt.committed_optimization(kernel_ESS4,x,x,y,yerr) print 'kernel ESS4 final ->',optimization4[1] print 'likelihood ESS4 final ->', optimization4[0] print '' kernel_ESS5=kl.ExpSineSquared(0.1, 0.1, 0.5) likelihood_ESS5=lk.likelihood(kernel_ESS5,x,x,y,yerr) print 'Kernel ESS5 ->', kernel_ESS5 print 'likelihood ESS5 ->', likelihood_ESS5 optimization5=opt.committed_optimization(kernel_ESS5,x,x,y,yerr) print 'kernel ESS5 final ->',optimization5[1] print 'likelihood ESS5 final ->', optimization5[0] print '' kernel_ESS6=kl.ExpSineSquared(0.1, 0.1, 0.1) likelihood_ESS6=lk.likelihood(kernel_ESS6,x,x,y,yerr) print 'Kernel ESS6 ->', kernel_ESS6 print 'likelihood ESS6 ->', likelihood_ESS6 optimization6=opt.committed_optimization(kernel_ESS6,x,x,y,yerr) print 'kernel ESS6 final ->',optimization6[1] print 'likelihood ESS6 final ->', optimization6[0] print '' print '### lets test with different increasing values to see how it behaves ###' print '' kernel_ESS7=kl.ExpSineSquared(1.7, 0.1, 7.5) likelihood_ESS7=lk.likelihood(kernel_ESS7,x,x,y,yerr) print 'Kernel ESS7 ->', kernel_ESS7 print 'likelihood ESS7 ->', likelihood_ESS7 optimization7=opt.committed_optimization(kernel_ESS7,x,x,y,yerr) print 'kernel ESS7 final ->',optimization7[1] print 'likelihood ESS7 final ->', optimization7[0] print '' kernel_ESS8=kl.ExpSineSquared(2.0, 0.1, 10.0) likelihood_ESS8=lk.likelihood(kernel_ESS8,x,x,y,yerr) print 'Kernel ESS8 ->', kernel_ESS8 print 'likelihood ESS8 ->', likelihood_ESS8 optimization8=opt.committed_optimization(kernel_ESS8,x,x,y,yerr) print 'kernel ESS8 final ->',optimization8[1] print 'likelihood ESS8 final ->', optimization8[0] print '' kernel_ESS9=kl.ExpSineSquared(3.0, 0.1, 12.0) likelihood_ESS9=lk.likelihood(kernel_ESS9,x,x,y,yerr) print 'Kernel ESS9 ->', kernel_ESS9 print 'likelihood ESS9 ->', likelihood_ESS9 optimization9=opt.committed_optimization(kernel_ESS9,x,x,y,yerr) print 'kernel ESS9 final ->',optimization9[1] print 'likelihood ESS9 final ->', optimization9[0] print '' kernel_ESS10=kl.ExpSineSquared(4.0, 0.1, 15.0) likelihood_ESS10=lk.likelihood(kernel_ESS10,x,x,y,yerr) print 'Kernel ESS10 ->', kernel_ESS10 print 'likelihood ESS10 ->', likelihood_ESS10 optimization10=opt.committed_optimization(kernel_ESS10,x,x,y,yerr) print 'kernel ESS10 final ->',optimization10[1] print 'likelihood ESS10 final ->', optimization10[0] print '' kernel_ESS11=kl.ExpSineSquared(5.0, 0.1, 20.0) likelihood_ESS11=lk.likelihood(kernel_ESS11,x,x,y,yerr) print 'Kernel ESS11 ->', kernel_ESS11 print 'likelihood ESS11 ->', likelihood_ESS11 optimization11=opt.committed_optimization(kernel_ESS11,x,x,y,yerr) print 'kernel ESS11 final ->',optimization11[1] print 'likelihood ESS11 final ->', optimization11[0] print '' print '### lets test the ExpSineSquared Kernel + White Noise ###' print '' kernel_ESS12=kl.ExpSineSquared(1.5, 0.1, 7.0) + kl.WhiteNoise(0.1) likelihood_ESS12=lk.likelihood(kernel_ESS12,x,x,y,yerr) print 'Kernel ESS12 ->', kernel_ESS12 print 'likelihood ESS12 ->', likelihood_ESS12 optimization12=opt.committed_optimization(kernel_ESS12,x,x,y,yerr) print 'kernel 12 final ->',optimization12[1] print 'likelihood 12 final ->', optimization12[0] print '' kernel_ESS13=kl.ExpSineSquared(1.5, 0.1, 7.0) + kl.WhiteNoise(0.2) likelihood_ESS13=lk.likelihood(kernel_ESS13,x,x,y,yerr) print 'Kernel ESS13 ->', kernel_ESS13 print 'likelihood ESS13 ->', likelihood_ESS13 optimization13=opt.committed_optimization(kernel_ESS13,x,x,y,yerr) print 'kernel 13 final ->',optimization13[1] print 'likelihood 13 final ->', optimization13[0] print '' kernel_ESS14=kl.ExpSineSquared(1.5, 0.1, 7.0) + kl.WhiteNoise(0.4) likelihood_ESS14=lk.likelihood(kernel_ESS14,x,x,y,yerr) print 'Kernel ESS14 ->', kernel_ESS14 print 'likelihood ESS14 ->', likelihood_ESS14 optimization14=opt.committed_optimization(kernel_ESS14,x,x,y,yerr) print 'kernel 14 final ->',optimization14[1] print 'likelihood 14 final ->', optimization14[0] print '' kernel_ESS15=kl.ExpSineSquared(1.5, 0.1, 7.0) + kl.WhiteNoise(0.8) likelihood_ESS15=lk.likelihood(kernel_ESS15,x,x,y,yerr) print 'Kernel ESS15 ->', kernel_ESS15 print 'likelihood ESS15 ->', likelihood_ESS15 optimization15=opt.committed_optimization(kernel_ESS15,x,x,y,yerr) print 'kernel 15 final ->',optimization15[1] print 'likelihood 15 final ->', optimization15[0] print '' kernel_ESS16=kl.ExpSineSquared(1.5, 0.1, 7.0) + kl.WhiteNoise(1.0) likelihood_ESS16=lk.likelihood(kernel_ESS16,x,x,y,yerr) print 'Kernel ESS16 ->', kernel_ESS16 print 'likelihood ESS16 ->', likelihood_ESS16 optimization16=opt.committed_optimization(kernel_ESS16,x,x,y,yerr) print 'kernel 16 final ->',optimization16[1] print 'likelihood 16 final ->', optimization16[0] print '' kernel_ESS17=kl.ExpSineSquared(1.5, 0.1, 7.0) + kl.WhiteNoise(1.25) likelihood_ESS17=lk.likelihood(kernel_ESS17,x,x,y,yerr) print 'Kernel ESS17 ->', kernel_ESS17 print 'likelihood ESS17 ->', likelihood_ESS17 optimization17=opt.committed_optimization(kernel_ESS17,x,x,y,yerr) print 'kernel 17 final ->',optimization17[1] print 'likelihood 17 final ->', optimization17[0] print '' kernel_ESS18=kl.ExpSineSquared(1.5, 0.1, 7.0) + kl.WhiteNoise(1.5) likelihood_ESS18=lk.likelihood(kernel_ESS18,x,x,y,yerr) print 'Kernel ESS18 ->', kernel_ESS18 print 'likelihood ESS18 ->', likelihood_ESS18 optimization18=opt.committed_optimization(kernel_ESS18,x,x,y,yerr) print 'kernel 18 final ->',optimization18[1] print 'likelihood 18 final ->', optimization18[0] print '' kernel_ESS19=kl.ExpSineSquared(1.5, 0.1, 7.0) + kl.WhiteNoise(1.6) likelihood_ESS19=lk.likelihood(kernel_ESS19,x,x,y,yerr) print 'Kernel ESS19 ->', kernel_ESS19 print 'likelihood ESS19 ->', likelihood_ESS19 optimization19=opt.committed_optimization(kernel_ESS19,x,x,y,yerr) print 'kernel 19 final ->',optimization19[1] print 'likelihood 19 final ->', optimization19[0] print '' kernel_ESS20=kl.ExpSineSquared(1.5, 0.1, 7.0) + kl.WhiteNoise(2.0) likelihood_ESS20=lk.likelihood(kernel_ESS20,x,x,y,yerr) print 'Kernel ESS20 ->', kernel_ESS20 print 'likelihood ESS20 ->', likelihood_ESS20 optimization20=opt.committed_optimization(kernel_ESS20,x,x,y,yerr) print 'kernel 20 final ->',optimization20[1] print 'likelihood 20 final ->', optimization20[0] print '' #for when everything ends f.close()
jdavidrcamacho/Tests_GP
02 - Programs being tested/05 - opt initial tests/Tests1_Kernel_opt.py
Python
mit
8,509
from . import EVE_BASE_URL from . xml import EveXml from . general import skilltree import urllib from urllib2 import urlopen import lxml EVE_ACCOUNT = EVE_BASE_URL + 'account/Characters.xml.aspx' EVE_CHARSHEET = EVE_BASE_URL + 'char/CharacterSheet.xml.aspx' EVE_INDUSTRY = EVE_BASE_URL + 'char/IndustryJobs.xml.aspx' EVE_ORDERS = EVE_BASE_URL + 'char/MarketOrders.xml.aspx' class EveAccount(EveXml): """ Contains character list; creates the EveCharacters, but does not refresh() them. """ def __init__(self, key_id, vcode): super(EveAccount,self).__init__() self.key_id = key_id self.vcode = vcode self.characters = list() self.url = EVE_ACCOUNT self.args = {'keyID':self.key_id,'vCode':self.vcode} def parse_xml(self): super(EveAccount,self).parse_xml() xmlroot = self.xmlroot rows = xmlroot.xpath("/eveapi/result/rowset[@name=\"characters\"]/row") self.characters = list() for charentry in rows: charid = charentry.attrib['characterID'] charname = charentry.attrib['name'] corpname = charentry.attrib['corporationName'] newchar = EveCharacter(self, charid, charname, corpname) self.characters.append(newchar) def __str__(self): result = "KeyID %s\n" % self.key_id result += "\n".join(map(str, self.characters)) return result class EveCharacter(EveXml): """ Contains character sheet information, excluding assets and industry info; those can be acquired from properties of this. """ def __init__(self, account, charid, name=None, corpname=None): super(EveCharacter,self).__init__() self.name = name self.corpname = corpname self.account = account self.charid = charid self.url = EVE_CHARSHEET self.args = {'characterID':charid} self.args.update(self.account.args) def parse_xml(self): super(EveCharacter,self).parse_xml() xmlroot = self.xmlroot xmlroot = xmlroot.xpath("/eveapi/result")[0] # Fluff getmacro = lambda x: xmlroot.xpath(x)[0].text self.name = getmacro("name") self.race = getmacro("race") self.bloodline = getmacro("bloodLine") self.gender = getmacro("gender") self.corpname = getmacro("corporationName") self.corpid = getmacro("corporationID") self.clonetype = getmacro("cloneName") self.cloneSP = int(getmacro("cloneSkillPoints")) self.iskbalance = float(getmacro("balance")) # Attributes getmacro = lambda x: xmlroot.xpath("/attributes/"+x) self.intelligence = getmacro("intelligence") self.memory = getmacro("memory") self.charisma = getmacro("charisma") self.perception = getmacro("perception") self.willpower = getmacro("willpower") # Skills self.skills = list() for x in xmlroot.xpath("/eveapi/result/rowset[@name='skills']")[0]: skillid = int(x.attrib['typeID']) skillpoints = int(x.attrib['skillpoints']) level = int(x.attrib['level']) self.skills.append( (skilltree.skills[skillid], skillpoints, level) ) self.certs = list() for x in xmlroot.xpath("/eveapi/result/rowset[@name='certificates']")[0]: certid = int(x.attrib['certificateID']) self.certs.append(certid) return def __str__(self): return "%s of %s" % (self.name, self.corpname)
pkovac/evedustrial
eve/character.py
Python
mit
3,543
# coding=utf-8 import os import tempfile import traceback import pytest import h2 from mitmproxy import options from mitmproxy.proxy.config import ProxyConfig import mitmproxy.net from ....mitmproxy.net import tservers as net_tservers from mitmproxy import exceptions from mitmproxy.net.http import http1, http2 from ... import tservers from ....conftest import requires_alpn import logging logging.getLogger("hyper.packages.hpack.hpack").setLevel(logging.WARNING) logging.getLogger("requests.packages.urllib3.connectionpool").setLevel(logging.WARNING) logging.getLogger("passlib.utils.compat").setLevel(logging.WARNING) logging.getLogger("passlib.registry").setLevel(logging.WARNING) # inspect the log: # for msg in self.proxy.tmaster.tlog: # print(msg) class _Http2ServerBase(net_tservers.ServerTestBase): ssl = dict(alpn_select=b'h2') class handler(mitmproxy.net.tcp.BaseHandler): def handle(self): config = h2.config.H2Configuration( client_side=False, validate_outbound_headers=False, validate_inbound_headers=False) h2_conn = h2.connection.H2Connection(config) preamble = self.rfile.read(24) h2_conn.initiate_connection() h2_conn.receive_data(preamble) self.wfile.write(h2_conn.data_to_send()) self.wfile.flush() if 'h2_server_settings' in self.kwargs: h2_conn.update_settings(self.kwargs['h2_server_settings']) self.wfile.write(h2_conn.data_to_send()) self.wfile.flush() done = False while not done: try: raw = b''.join(http2.read_raw_frame(self.rfile)) events = h2_conn.receive_data(raw) except exceptions.HttpException: print(traceback.format_exc()) assert False except exceptions.TcpDisconnect: break except: print(traceback.format_exc()) break self.wfile.write(h2_conn.data_to_send()) self.wfile.flush() for event in events: try: if not self.server.handle_server_event(event, h2_conn, self.rfile, self.wfile): done = True break except exceptions.TcpDisconnect: done = True except: done = True print(traceback.format_exc()) break def handle_server_event(self, event, h2_conn, rfile, wfile): raise NotImplementedError() class _Http2TestBase: @classmethod def setup_class(cls): opts = cls.get_options() cls.config = ProxyConfig(opts) tmaster = tservers.TestMaster(opts, cls.config) cls.proxy = tservers.ProxyThread(tmaster) cls.proxy.start() @classmethod def teardown_class(cls): cls.proxy.shutdown() @classmethod def get_options(cls): opts = options.Options( listen_port=0, upstream_cert=True, ssl_insecure=True ) opts.cadir = os.path.join(tempfile.gettempdir(), "mitmproxy") return opts @property def master(self): return self.proxy.tmaster def setup(self): self.master.reset([]) self.server.server.handle_server_event = self.handle_server_event def _setup_connection(self): client = mitmproxy.net.tcp.TCPClient(("127.0.0.1", self.proxy.port)) client.connect() # send CONNECT request client.wfile.write(http1.assemble_request(mitmproxy.net.http.Request( 'authority', b'CONNECT', b'', b'localhost', self.server.server.address[1], b'/', b'HTTP/1.1', [(b'host', b'localhost:%d' % self.server.server.address[1])], b'', ))) client.wfile.flush() # read CONNECT response while client.rfile.readline() != b"\r\n": pass client.convert_to_ssl(alpn_protos=[b'h2']) config = h2.config.H2Configuration( client_side=True, validate_outbound_headers=False, validate_inbound_headers=False) h2_conn = h2.connection.H2Connection(config) h2_conn.initiate_connection() client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() return client, h2_conn def _send_request(self, wfile, h2_conn, stream_id=1, headers=None, body=b'', end_stream=None, priority_exclusive=None, priority_depends_on=None, priority_weight=None): if headers is None: headers = [] if end_stream is None: end_stream = (len(body) == 0) h2_conn.send_headers( stream_id=stream_id, headers=headers, end_stream=end_stream, priority_exclusive=priority_exclusive, priority_depends_on=priority_depends_on, priority_weight=priority_weight, ) if body: h2_conn.send_data(stream_id, body) h2_conn.end_stream(stream_id) wfile.write(h2_conn.data_to_send()) wfile.flush() class _Http2Test(_Http2TestBase, _Http2ServerBase): @classmethod def setup_class(cls): _Http2TestBase.setup_class() _Http2ServerBase.setup_class() @classmethod def teardown_class(cls): _Http2TestBase.teardown_class() _Http2ServerBase.teardown_class() @requires_alpn class TestSimple(_Http2Test): request_body_buffer = b'' @classmethod def handle_server_event(cls, event, h2_conn, rfile, wfile): if isinstance(event, h2.events.ConnectionTerminated): return False elif isinstance(event, h2.events.RequestReceived): assert (b'client-foo', b'client-bar-1') in event.headers assert (b'client-foo', b'client-bar-2') in event.headers elif isinstance(event, h2.events.StreamEnded): import warnings with warnings.catch_warnings(): # Ignore UnicodeWarning: # h2/utilities.py:64: UnicodeWarning: Unicode equal comparison # failed to convert both arguments to Unicode - interpreting # them as being unequal. # elif header[0] in (b'cookie', u'cookie') and len(header[1]) < 20: warnings.simplefilter("ignore") h2_conn.send_headers(event.stream_id, [ (':status', '200'), ('server-foo', 'server-bar'), ('föo', 'bär'), ('X-Stream-ID', str(event.stream_id)), ]) h2_conn.send_data(event.stream_id, b'response body') h2_conn.end_stream(event.stream_id) wfile.write(h2_conn.data_to_send()) wfile.flush() elif isinstance(event, h2.events.DataReceived): cls.request_body_buffer += event.data return True def test_simple(self): response_body_buffer = b'' client, h2_conn = self._setup_connection() self._send_request( client.wfile, h2_conn, headers=[ (':authority', "127.0.0.1:{}".format(self.server.server.address[1])), (':method', 'GET'), (':scheme', 'https'), (':path', '/'), ('ClIeNt-FoO', 'client-bar-1'), ('ClIeNt-FoO', 'client-bar-2'), ], body=b'request body') done = False while not done: try: raw = b''.join(http2.read_raw_frame(client.rfile)) events = h2_conn.receive_data(raw) except exceptions.HttpException: print(traceback.format_exc()) assert False client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() for event in events: if isinstance(event, h2.events.DataReceived): response_body_buffer += event.data elif isinstance(event, h2.events.StreamEnded): done = True h2_conn.close_connection() client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() assert len(self.master.state.flows) == 1 assert self.master.state.flows[0].response.status_code == 200 assert self.master.state.flows[0].response.headers['server-foo'] == 'server-bar' assert self.master.state.flows[0].response.headers['föo'] == 'bär' assert self.master.state.flows[0].response.content == b'response body' assert self.request_body_buffer == b'request body' assert response_body_buffer == b'response body' @requires_alpn class TestRequestWithPriority(_Http2Test): @classmethod def handle_server_event(cls, event, h2_conn, rfile, wfile): if isinstance(event, h2.events.ConnectionTerminated): return False elif isinstance(event, h2.events.RequestReceived): import warnings with warnings.catch_warnings(): # Ignore UnicodeWarning: # h2/utilities.py:64: UnicodeWarning: Unicode equal comparison # failed to convert both arguments to Unicode - interpreting # them as being unequal. # elif header[0] in (b'cookie', u'cookie') and len(header[1]) < 20: warnings.simplefilter("ignore") headers = [(':status', '200')] if event.priority_updated: headers.append(('priority_exclusive', str(event.priority_updated.exclusive).encode())) headers.append(('priority_depends_on', str(event.priority_updated.depends_on).encode())) headers.append(('priority_weight', str(event.priority_updated.weight).encode())) h2_conn.send_headers(event.stream_id, headers) h2_conn.end_stream(event.stream_id) wfile.write(h2_conn.data_to_send()) wfile.flush() return True @pytest.mark.parametrize("http2_priority_enabled, priority, expected_priority", [ (True, (True, 42424242, 42), ('True', '42424242', '42')), (False, (True, 42424242, 42), (None, None, None)), (True, (None, None, None), (None, None, None)), (False, (None, None, None), (None, None, None)), ]) def test_request_with_priority(self, http2_priority_enabled, priority, expected_priority): self.config.options.http2_priority = http2_priority_enabled client, h2_conn = self._setup_connection() self._send_request( client.wfile, h2_conn, headers=[ (':authority', "127.0.0.1:{}".format(self.server.server.address[1])), (':method', 'GET'), (':scheme', 'https'), (':path', '/'), ], priority_exclusive=priority[0], priority_depends_on=priority[1], priority_weight=priority[2], ) done = False while not done: try: raw = b''.join(http2.read_raw_frame(client.rfile)) events = h2_conn.receive_data(raw) except exceptions.HttpException: print(traceback.format_exc()) assert False client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() for event in events: if isinstance(event, h2.events.StreamEnded): done = True h2_conn.close_connection() client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() assert len(self.master.state.flows) == 1 resp = self.master.state.flows[0].response assert resp.headers.get('priority_exclusive', None) == expected_priority[0] assert resp.headers.get('priority_depends_on', None) == expected_priority[1] assert resp.headers.get('priority_weight', None) == expected_priority[2] @requires_alpn class TestPriority(_Http2Test): @classmethod def handle_server_event(cls, event, h2_conn, rfile, wfile): if isinstance(event, h2.events.ConnectionTerminated): return False elif isinstance(event, h2.events.PriorityUpdated): cls.priority_data.append((event.exclusive, event.depends_on, event.weight)) elif isinstance(event, h2.events.RequestReceived): import warnings with warnings.catch_warnings(): # Ignore UnicodeWarning: # h2/utilities.py:64: UnicodeWarning: Unicode equal comparison # failed to convert both arguments to Unicode - interpreting # them as being unequal. # elif header[0] in (b'cookie', u'cookie') and len(header[1]) < 20: warnings.simplefilter("ignore") headers = [(':status', '200')] h2_conn.send_headers(event.stream_id, headers) h2_conn.end_stream(event.stream_id) wfile.write(h2_conn.data_to_send()) wfile.flush() return True @pytest.mark.parametrize("prioritize_before", [True, False]) @pytest.mark.parametrize("http2_priority_enabled, priority, expected_priority", [ (True, (True, 42424242, 42), [(True, 42424242, 42)]), (False, (True, 42424242, 42), []), ]) def test_priority(self, prioritize_before, http2_priority_enabled, priority, expected_priority): self.config.options.http2_priority = http2_priority_enabled self.__class__.priority_data = [] client, h2_conn = self._setup_connection() if prioritize_before: h2_conn.prioritize(1, exclusive=priority[0], depends_on=priority[1], weight=priority[2]) client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() self._send_request( client.wfile, h2_conn, headers=[ (':authority', "127.0.0.1:{}".format(self.server.server.address[1])), (':method', 'GET'), (':scheme', 'https'), (':path', '/'), ], end_stream=prioritize_before, ) if not prioritize_before: h2_conn.prioritize(1, exclusive=priority[0], depends_on=priority[1], weight=priority[2]) h2_conn.end_stream(1) client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() done = False while not done: try: raw = b''.join(http2.read_raw_frame(client.rfile)) events = h2_conn.receive_data(raw) except exceptions.HttpException: print(traceback.format_exc()) assert False client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() for event in events: if isinstance(event, h2.events.StreamEnded): done = True h2_conn.close_connection() client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() assert len(self.master.state.flows) == 1 assert self.priority_data == expected_priority @requires_alpn class TestStreamResetFromServer(_Http2Test): @classmethod def handle_server_event(cls, event, h2_conn, rfile, wfile): if isinstance(event, h2.events.ConnectionTerminated): return False elif isinstance(event, h2.events.RequestReceived): h2_conn.reset_stream(event.stream_id, 0x8) wfile.write(h2_conn.data_to_send()) wfile.flush() return True def test_request_with_priority(self): client, h2_conn = self._setup_connection() self._send_request( client.wfile, h2_conn, headers=[ (':authority', "127.0.0.1:{}".format(self.server.server.address[1])), (':method', 'GET'), (':scheme', 'https'), (':path', '/'), ], ) done = False while not done: try: raw = b''.join(http2.read_raw_frame(client.rfile)) events = h2_conn.receive_data(raw) except exceptions.HttpException: print(traceback.format_exc()) assert False client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() for event in events: if isinstance(event, h2.events.StreamReset): done = True h2_conn.close_connection() client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() assert len(self.master.state.flows) == 1 assert self.master.state.flows[0].response is None @requires_alpn class TestBodySizeLimit(_Http2Test): @classmethod def handle_server_event(cls, event, h2_conn, rfile, wfile): if isinstance(event, h2.events.ConnectionTerminated): return False return True def test_body_size_limit(self): self.config.options.body_size_limit = "20" self.config.options._processed["body_size_limit"] = 20 client, h2_conn = self._setup_connection() self._send_request( client.wfile, h2_conn, headers=[ (':authority', "127.0.0.1:{}".format(self.server.server.address[1])), (':method', 'GET'), (':scheme', 'https'), (':path', '/'), ], body=b'very long body over 20 characters long', ) done = False while not done: try: raw = b''.join(http2.read_raw_frame(client.rfile)) events = h2_conn.receive_data(raw) except exceptions.HttpException: print(traceback.format_exc()) assert False client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() for event in events: if isinstance(event, h2.events.StreamReset): done = True h2_conn.close_connection() client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() assert len(self.master.state.flows) == 0 @requires_alpn class TestPushPromise(_Http2Test): @classmethod def handle_server_event(cls, event, h2_conn, rfile, wfile): if isinstance(event, h2.events.ConnectionTerminated): return False elif isinstance(event, h2.events.RequestReceived): if event.stream_id != 1: # ignore requests initiated by push promises return True h2_conn.send_headers(1, [(':status', '200')]) wfile.write(h2_conn.data_to_send()) wfile.flush() h2_conn.push_stream(1, 2, [ (':authority', "127.0.0.1:{}".format(cls.port)), (':method', 'GET'), (':scheme', 'https'), (':path', '/pushed_stream_foo'), ('foo', 'bar') ]) wfile.write(h2_conn.data_to_send()) wfile.flush() h2_conn.push_stream(1, 4, [ (':authority', "127.0.0.1:{}".format(cls.port)), (':method', 'GET'), (':scheme', 'https'), (':path', '/pushed_stream_bar'), ('foo', 'bar') ]) wfile.write(h2_conn.data_to_send()) wfile.flush() h2_conn.send_headers(2, [(':status', '200')]) h2_conn.send_headers(4, [(':status', '200')]) wfile.write(h2_conn.data_to_send()) wfile.flush() h2_conn.send_data(1, b'regular_stream') wfile.write(h2_conn.data_to_send()) wfile.flush() h2_conn.end_stream(1) wfile.write(h2_conn.data_to_send()) wfile.flush() h2_conn.send_data(2, b'pushed_stream_foo') h2_conn.end_stream(2) wfile.write(h2_conn.data_to_send()) wfile.flush() h2_conn.send_data(4, b'pushed_stream_bar') h2_conn.end_stream(4) wfile.write(h2_conn.data_to_send()) wfile.flush() return True def test_push_promise(self): client, h2_conn = self._setup_connection() self._send_request(client.wfile, h2_conn, stream_id=1, headers=[ (':authority', "127.0.0.1:{}".format(self.server.server.address[1])), (':method', 'GET'), (':scheme', 'https'), (':path', '/'), ('foo', 'bar') ]) done = False ended_streams = 0 pushed_streams = 0 responses = 0 while not done: try: raw = b''.join(http2.read_raw_frame(client.rfile)) events = h2_conn.receive_data(raw) except exceptions.HttpException: print(traceback.format_exc()) assert False except: break client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() for event in events: if isinstance(event, h2.events.StreamEnded): ended_streams += 1 elif isinstance(event, h2.events.PushedStreamReceived): pushed_streams += 1 elif isinstance(event, h2.events.ResponseReceived): responses += 1 if isinstance(event, h2.events.ConnectionTerminated): done = True if responses == 3 and ended_streams == 3 and pushed_streams == 2: done = True h2_conn.close_connection() client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() assert ended_streams == 3 assert pushed_streams == 2 bodies = [flow.response.content for flow in self.master.state.flows] assert len(bodies) == 3 assert b'regular_stream' in bodies assert b'pushed_stream_foo' in bodies assert b'pushed_stream_bar' in bodies pushed_flows = [flow for flow in self.master.state.flows if 'h2-pushed-stream' in flow.metadata] assert len(pushed_flows) == 2 def test_push_promise_reset(self): client, h2_conn = self._setup_connection() self._send_request(client.wfile, h2_conn, stream_id=1, headers=[ (':authority', "127.0.0.1:{}".format(self.server.server.address[1])), (':method', 'GET'), (':scheme', 'https'), (':path', '/'), ('foo', 'bar') ]) done = False ended_streams = 0 pushed_streams = 0 responses = 0 while not done: try: raw = b''.join(http2.read_raw_frame(client.rfile)) events = h2_conn.receive_data(raw) except exceptions.HttpException: print(traceback.format_exc()) assert False client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() for event in events: if isinstance(event, h2.events.StreamEnded) and event.stream_id == 1: ended_streams += 1 elif isinstance(event, h2.events.PushedStreamReceived): pushed_streams += 1 h2_conn.reset_stream(event.pushed_stream_id, error_code=0x8) client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() elif isinstance(event, h2.events.ResponseReceived): responses += 1 if isinstance(event, h2.events.ConnectionTerminated): done = True if responses >= 1 and ended_streams >= 1 and pushed_streams == 2: done = True h2_conn.close_connection() client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() bodies = [flow.response.content for flow in self.master.state.flows if flow.response] assert len(bodies) >= 1 assert b'regular_stream' in bodies # the other two bodies might not be transmitted before the reset @requires_alpn class TestConnectionLost(_Http2Test): @classmethod def handle_server_event(cls, event, h2_conn, rfile, wfile): if isinstance(event, h2.events.RequestReceived): h2_conn.send_headers(1, [(':status', '200')]) wfile.write(h2_conn.data_to_send()) wfile.flush() return False def test_connection_lost(self): client, h2_conn = self._setup_connection() self._send_request(client.wfile, h2_conn, stream_id=1, headers=[ (':authority', "127.0.0.1:{}".format(self.server.server.address[1])), (':method', 'GET'), (':scheme', 'https'), (':path', '/'), ('foo', 'bar') ]) done = False while not done: try: raw = b''.join(http2.read_raw_frame(client.rfile)) h2_conn.receive_data(raw) except exceptions.HttpException: print(traceback.format_exc()) assert False except: break try: client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() except: break if len(self.master.state.flows) == 1: assert self.master.state.flows[0].response is None @requires_alpn class TestMaxConcurrentStreams(_Http2Test): @classmethod def setup_class(cls): _Http2TestBase.setup_class() _Http2ServerBase.setup_class(h2_server_settings={h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 2}) @classmethod def handle_server_event(cls, event, h2_conn, rfile, wfile): if isinstance(event, h2.events.ConnectionTerminated): return False elif isinstance(event, h2.events.RequestReceived): h2_conn.send_headers(event.stream_id, [ (':status', '200'), ('X-Stream-ID', str(event.stream_id)), ]) h2_conn.send_data(event.stream_id, 'Stream-ID {}'.format(event.stream_id).encode()) h2_conn.end_stream(event.stream_id) wfile.write(h2_conn.data_to_send()) wfile.flush() return True def test_max_concurrent_streams(self): client, h2_conn = self._setup_connection() new_streams = [1, 3, 5, 7, 9, 11] for stream_id in new_streams: # this will exceed MAX_CONCURRENT_STREAMS on the server connection # and cause mitmproxy to throttle stream creation to the server self._send_request(client.wfile, h2_conn, stream_id=stream_id, headers=[ (':authority', "127.0.0.1:{}".format(self.server.server.address[1])), (':method', 'GET'), (':scheme', 'https'), (':path', '/'), ('X-Stream-ID', str(stream_id)), ]) ended_streams = 0 while ended_streams != len(new_streams): try: header, body = http2.read_raw_frame(client.rfile) events = h2_conn.receive_data(b''.join([header, body])) except: break client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() for event in events: if isinstance(event, h2.events.StreamEnded): ended_streams += 1 h2_conn.close_connection() client.wfile.write(h2_conn.data_to_send()) client.wfile.flush() assert len(self.master.state.flows) == len(new_streams) for flow in self.master.state.flows: assert flow.response.status_code == 200 assert b"Stream-ID " in flow.response.content @requires_alpn class TestConnectionTerminated(_Http2Test): @classmethod def handle_server_event(cls, event, h2_conn, rfile, wfile): if isinstance(event, h2.events.RequestReceived): h2_conn.close_connection(error_code=5, last_stream_id=42, additional_data=b'foobar') wfile.write(h2_conn.data_to_send()) wfile.flush() return True def test_connection_terminated(self): client, h2_conn = self._setup_connection() self._send_request(client.wfile, h2_conn, headers=[ (':authority', "127.0.0.1:{}".format(self.server.server.address[1])), (':method', 'GET'), (':scheme', 'https'), (':path', '/'), ]) done = False connection_terminated_event = None while not done: try: raw = b''.join(http2.read_raw_frame(client.rfile)) events = h2_conn.receive_data(raw) for event in events: if isinstance(event, h2.events.ConnectionTerminated): connection_terminated_event = event done = True except: break assert len(self.master.state.flows) == 1 assert connection_terminated_event is not None assert connection_terminated_event.error_code == 5 assert connection_terminated_event.last_stream_id == 42 assert connection_terminated_event.additional_data == b'foobar'
xaxa89/mitmproxy
test/mitmproxy/proxy/protocol/test_http2.py
Python
mit
30,081
"""The tests for the Demo vacuum platform.""" import unittest from homeassistant.components import vacuum from homeassistant.components.vacuum import ( ATTR_BATTERY_LEVEL, ATTR_BATTERY_ICON, ATTR_STATUS, ATTR_FAN_SPEED, mqtt) from homeassistant.components.mqtt import CONF_COMMAND_TOPIC from homeassistant.const import CONF_PLATFORM, STATE_OFF, STATE_ON, CONF_NAME from homeassistant.setup import setup_component from tests.common import ( fire_mqtt_message, get_test_home_assistant, mock_mqtt_component) class TestVacuumMQTT(unittest.TestCase): """MQTT vacuum component test class.""" def setUp(self): # pylint: disable=invalid-name """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.mock_publish = mock_mqtt_component(self.hass) self.default_config = { CONF_PLATFORM: 'mqtt', CONF_NAME: 'mqtttest', CONF_COMMAND_TOPIC: 'vacuum/command', mqtt.CONF_SEND_COMMAND_TOPIC: 'vacuum/send_command', mqtt.CONF_BATTERY_LEVEL_TOPIC: 'vacuum/state', mqtt.CONF_BATTERY_LEVEL_TEMPLATE: '{{ value_json.battery_level }}', mqtt.CONF_CHARGING_TOPIC: 'vacuum/state', mqtt.CONF_CHARGING_TEMPLATE: '{{ value_json.charging }}', mqtt.CONF_CLEANING_TOPIC: 'vacuum/state', mqtt.CONF_CLEANING_TEMPLATE: '{{ value_json.cleaning }}', mqtt.CONF_DOCKED_TOPIC: 'vacuum/state', mqtt.CONF_DOCKED_TEMPLATE: '{{ value_json.docked }}', mqtt.CONF_STATE_TOPIC: 'vacuum/state', mqtt.CONF_STATE_TEMPLATE: '{{ value_json.state }}', mqtt.CONF_FAN_SPEED_TOPIC: 'vacuum/state', mqtt.CONF_FAN_SPEED_TEMPLATE: '{{ value_json.fan_speed }}', mqtt.CONF_SET_FAN_SPEED_TOPIC: 'vacuum/set_fan_speed', mqtt.CONF_FAN_SPEED_LIST: ['min', 'medium', 'high', 'max'], } def tearDown(self): # pylint: disable=invalid-name """Stop down everything that was started.""" self.hass.stop() def test_default_supported_features(self): """Test that the correct supported features.""" self.assertTrue(setup_component(self.hass, vacuum.DOMAIN, { vacuum.DOMAIN: self.default_config, })) entity = self.hass.states.get('vacuum.mqtttest') entity_features = \ entity.attributes.get(mqtt.CONF_SUPPORTED_FEATURES, 0) self.assertListEqual(sorted(mqtt.services_to_strings(entity_features)), sorted(['turn_on', 'turn_off', 'stop', 'return_home', 'battery', 'status', 'clean_spot'])) def test_all_commands(self): """Test simple commands to the vacuum.""" self.default_config[mqtt.CONF_SUPPORTED_FEATURES] = \ mqtt.services_to_strings(mqtt.ALL_SERVICES) self.assertTrue(setup_component(self.hass, vacuum.DOMAIN, { vacuum.DOMAIN: self.default_config, })) vacuum.turn_on(self.hass, 'vacuum.mqtttest') self.hass.block_till_done() self.assertEqual(('vacuum/command', 'turn_on', 0, False), self.mock_publish.mock_calls[-2][1]) vacuum.turn_off(self.hass, 'vacuum.mqtttest') self.hass.block_till_done() self.assertEqual(('vacuum/command', 'turn_off', 0, False), self.mock_publish.mock_calls[-2][1]) vacuum.stop(self.hass, 'vacuum.mqtttest') self.hass.block_till_done() self.assertEqual(('vacuum/command', 'stop', 0, False), self.mock_publish.mock_calls[-2][1]) vacuum.clean_spot(self.hass, 'vacuum.mqtttest') self.hass.block_till_done() self.assertEqual(('vacuum/command', 'clean_spot', 0, False), self.mock_publish.mock_calls[-2][1]) vacuum.locate(self.hass, 'vacuum.mqtttest') self.hass.block_till_done() self.assertEqual(('vacuum/command', 'locate', 0, False), self.mock_publish.mock_calls[-2][1]) vacuum.start_pause(self.hass, 'vacuum.mqtttest') self.hass.block_till_done() self.assertEqual(('vacuum/command', 'start_pause', 0, False), self.mock_publish.mock_calls[-2][1]) vacuum.return_to_base(self.hass, 'vacuum.mqtttest') self.hass.block_till_done() self.assertEqual(('vacuum/command', 'return_to_base', 0, False), self.mock_publish.mock_calls[-2][1]) vacuum.set_fan_speed(self.hass, 'high', 'vacuum.mqtttest') self.hass.block_till_done() self.assertEqual( ('vacuum/set_fan_speed', 'high', 0, False), self.mock_publish.mock_calls[-2][1] ) vacuum.send_command(self.hass, '44 FE 93', entity_id='vacuum.mqtttest') self.hass.block_till_done() self.assertEqual( ('vacuum/send_command', '44 FE 93', 0, False), self.mock_publish.mock_calls[-2][1] ) def test_status(self): """Test status updates from the vacuum.""" self.default_config[mqtt.CONF_SUPPORTED_FEATURES] = \ mqtt.services_to_strings(mqtt.ALL_SERVICES) self.assertTrue(setup_component(self.hass, vacuum.DOMAIN, { vacuum.DOMAIN: self.default_config, })) message = """{ "battery_level": 54, "cleaning": true, "docked": false, "charging": false, "fan_speed": "max" }""" fire_mqtt_message(self.hass, 'vacuum/state', message) self.hass.block_till_done() state = self.hass.states.get('vacuum.mqtttest') self.assertEqual(STATE_ON, state.state) self.assertEqual( 'mdi:battery-50', state.attributes.get(ATTR_BATTERY_ICON) ) self.assertEqual(54, state.attributes.get(ATTR_BATTERY_LEVEL)) self.assertEqual('max', state.attributes.get(ATTR_FAN_SPEED)) message = """{ "battery_level": 61, "docked": true, "cleaning": false, "charging": true, "fan_speed": "min" }""" fire_mqtt_message(self.hass, 'vacuum/state', message) self.hass.block_till_done() state = self.hass.states.get('vacuum.mqtttest') self.assertEqual(STATE_OFF, state.state) self.assertEqual( 'mdi:battery-charging-60', state.attributes.get(ATTR_BATTERY_ICON) ) self.assertEqual(61, state.attributes.get(ATTR_BATTERY_LEVEL)) self.assertEqual('min', state.attributes.get(ATTR_FAN_SPEED)) def test_battery_template(self): """Test that you can use non-default templates for battery_level.""" self.default_config.update({ mqtt.CONF_SUPPORTED_FEATURES: mqtt.services_to_strings(mqtt.ALL_SERVICES), mqtt.CONF_BATTERY_LEVEL_TOPIC: "retroroomba/battery_level", mqtt.CONF_BATTERY_LEVEL_TEMPLATE: "{{ value }}" }) self.assertTrue(setup_component(self.hass, vacuum.DOMAIN, { vacuum.DOMAIN: self.default_config, })) fire_mqtt_message(self.hass, 'retroroomba/battery_level', '54') self.hass.block_till_done() state = self.hass.states.get('vacuum.mqtttest') self.assertEqual(54, state.attributes.get(ATTR_BATTERY_LEVEL)) self.assertEqual(state.attributes.get(ATTR_BATTERY_ICON), 'mdi:battery-50') def test_status_invalid_json(self): """Test to make sure nothing breaks if the vacuum sends bad JSON.""" self.default_config[mqtt.CONF_SUPPORTED_FEATURES] = \ mqtt.services_to_strings(mqtt.ALL_SERVICES) self.assertTrue(setup_component(self.hass, vacuum.DOMAIN, { vacuum.DOMAIN: self.default_config, })) fire_mqtt_message(self.hass, 'vacuum/state', '{"asdfasas false}') self.hass.block_till_done() state = self.hass.states.get('vacuum.mqtttest') self.assertEqual(STATE_OFF, state.state) self.assertEqual("Stopped", state.attributes.get(ATTR_STATUS))
ewandor/home-assistant
tests/components/vacuum/test_mqtt.py
Python
apache-2.0
8,296
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0014_verbose_name_for_group'), ] operations = [ migrations.AddField( model_name='person', name='ldap_user_password', field=models.CharField(max_length=200, null=True, verbose_name='Contrase\xf1a', blank=True), ), ]
efornal/mollys
app/migrations/0015_add_field_person_ldap_user_password.py
Python
gpl-3.0
466
#!/usr/bin/env python import os import mako from mako.lookup import TemplateLookup from circuits.web import Server, Controller, Static DEFAULTS = {} templates = TemplateLookup( directories=[os.path.join(os.path.dirname(__file__), "tpl")], module_directory="/tmp", output_encoding="utf-8" ) def render(name, **d): try: d.update(DEFAULTS) tpl = templates.get_template(name) return tpl.render(**d) except: return mako.exceptions.html_error_template().render() class Root(Controller): tpl = "index.html" def index(self): return render(self.tpl) def submit(self, firstName, lastName): msg = "Thank you %s %s" % (firstName, lastName) return render(self.tpl, message=msg) app = Server(("0.0.0.0", 8000)) Static().register(app) Root().register(app) app.run()
eriol/circuits
examples/web/makotemplates.py
Python
mit
852
# Status: ported, except for tests and --abbreviate-paths. # Base revision: 64070 # # Copyright 2001, 2002, 2003 Dave Abrahams # Copyright 2006 Rene Rivera # Copyright 2002, 2003, 2004, 2005, 2006 Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) import re from b2.util.utility import * from b2.build import feature from b2.util import sequence, qualify_jam_action import b2.util.set from b2.manager import get_manager __re_two_ampersands = re.compile ('&&') __re_comma = re.compile (',') __re_split_condition = re.compile ('(.*):(<.*)') __re_split_conditional = re.compile (r'(.+):<(.+)') __re_colon = re.compile (':') __re_has_condition = re.compile (r':<') __re_separate_condition_and_property = re.compile (r'(.*):(<.*)') __not_applicable_feature='not-applicable-in-this-context' feature.feature(__not_applicable_feature, [], ['free']) class Property(object): __slots__ = ('_feature', '_value', '_condition') def __init__(self, f, value, condition = []): if type(f) == type(""): f = feature.get(f) # At present, single property has a single value. assert type(value) != type([]) assert(f.free() or value.find(':') == -1) self._feature = f self._value = value self._condition = condition def feature(self): return self._feature def value(self): return self._value def condition(self): return self._condition def to_raw(self): result = "<" + self._feature.name() + ">" + str(self._value) if self._condition: result = ",".join(str(p) for p in self._condition) + ':' + result return result def __str__(self): return self.to_raw() def __hash__(self): # FIXME: consider if this class should be value-is-identity one return hash((self._feature, self._value, tuple(self._condition))) def __cmp__(self, other): return cmp((self._feature, self._value, self._condition), (other._feature, other._value, other._condition)) def create_from_string(s, allow_condition=False,allow_missing_value=False): condition = [] import types if not isinstance(s, types.StringType): print type(s) if __re_has_condition.search(s): if not allow_condition: raise BaseException("Conditional property is not allowed in this context") m = __re_separate_condition_and_property.match(s) condition = m.group(1) s = m.group(2) # FIXME: break dependency cycle from b2.manager import get_manager feature_name = get_grist(s) if not feature_name: if feature.is_implicit_value(s): f = feature.implied_feature(s) value = s else: raise get_manager().errors()("Invalid property '%s' -- unknown feature" % s) else: if feature.valid(feature_name): f = feature.get(feature_name) value = get_value(s) else: # In case feature name is not known, it is wrong to do a hard error. # Feature sets change depending on the toolset. So e.g. # <toolset-X:version> is an unknown feature when using toolset Y. # # Ideally we would like to ignore this value, but most of # Boost.Build code expects that we return a valid Property. For this # reason we use a sentinel <not-applicable-in-this-context> feature. # # The underlying cause for this problem is that python port Property # is more strict than its Jam counterpart and must always reference # a valid feature. f = feature.get(__not_applicable_feature) value = s if not value and not allow_missing_value: get_manager().errors()("Invalid property '%s' -- no value specified" % s) if condition: condition = [create_from_string(x) for x in condition.split(',')] return Property(f, value, condition) def create_from_strings(string_list, allow_condition=False): return [create_from_string(s, allow_condition) for s in string_list] def reset (): """ Clear the module state. This is mainly for testing purposes. """ global __results # A cache of results from as_path __results = {} reset () def path_order (x, y): """ Helper for as_path, below. Orders properties with the implicit ones first, and within the two sections in alphabetical order of feature name. """ if x == y: return 0 xg = get_grist (x) yg = get_grist (y) if yg and not xg: return -1 elif xg and not yg: return 1 else: if not xg: x = feature.expand_subfeatures([x]) y = feature.expand_subfeatures([y]) if x < y: return -1 elif x > y: return 1 else: return 0 def identify(string): return string # Uses Property def refine (properties, requirements): """ Refines 'properties' by overriding any non-free properties for which a different value is specified in 'requirements'. Conditional requirements are just added without modification. Returns the resulting list of properties. """ # The result has no duplicates, so we store it in a set result = set() # Records all requirements. required = {} # All the elements of requirements should be present in the result # Record them so that we can handle 'properties'. for r in requirements: # Don't consider conditional requirements. if not r.condition(): required[r.feature()] = r for p in properties: # Skip conditional properties if p.condition(): result.add(p) # No processing for free properties elif p.feature().free(): result.add(p) else: if required.has_key(p.feature()): result.add(required[p.feature()]) else: result.add(p) return sequence.unique(list(result) + requirements) def translate_paths (properties, path): """ Interpret all path properties in 'properties' as relative to 'path' The property values are assumed to be in system-specific form, and will be translated into normalized form. """ result = [] for p in properties: if p.feature().path(): values = __re_two_ampersands.split(p.value()) new_value = "&&".join(os.path.join(path, v) for v in values) if new_value != p.value(): result.append(Property(p.feature(), new_value, p.condition())) else: result.append(p) else: result.append (p) return result def translate_indirect(properties, context_module): """Assumes that all feature values that start with '@' are names of rules, used in 'context-module'. Such rules can be either local to the module or global. Qualified local rules with the name of the module.""" result = [] for p in properties: if p.value()[0] == '@': q = qualify_jam_action(p.value()[1:], context_module) get_manager().engine().register_bjam_action(q) result.append(Property(p.feature(), '@' + q, p.condition())) else: result.append(p) return result def validate (properties): """ Exit with error if any of the properties is not valid. properties may be a single property or a sequence of properties. """ if isinstance (properties, str): __validate1 (properties) else: for p in properties: __validate1 (p) def expand_subfeatures_in_conditions (properties): result = [] for p in properties: if not p.condition(): result.append(p) else: expanded = [] for c in p.condition(): if c.feature().name().startswith("toolset") or c.feature().name() == "os": # It common that condition includes a toolset which # was never defined, or mentiones subfeatures which # were never defined. In that case, validation will # only produce an spirious error, so don't validate. expanded.extend(feature.expand_subfeatures ([c], True)) else: expanded.extend(feature.expand_subfeatures([c])) result.append(Property(p.feature(), p.value(), expanded)) return result # FIXME: this should go def split_conditional (property): """ If 'property' is conditional property, returns condition and the property, e.g <variant>debug,<toolset>gcc:<inlining>full will become <variant>debug,<toolset>gcc <inlining>full. Otherwise, returns empty string. """ m = __re_split_conditional.match (property) if m: return (m.group (1), '<' + m.group (2)) return None def select (features, properties): """ Selects properties which correspond to any of the given features. """ result = [] # add any missing angle brackets features = add_grist (features) return [p for p in properties if get_grist(p) in features] def validate_property_sets (sets): for s in sets: validate(s.all()) def evaluate_conditionals_in_context (properties, context): """ Removes all conditional properties which conditions are not met For those with met conditions, removes the condition. Properies in conditions are looked up in 'context' """ base = [] conditional = [] for p in properties: if p.condition(): conditional.append (p) else: base.append (p) result = base[:] for p in conditional: # Evaluate condition # FIXME: probably inefficient if all(x in context for x in p.condition()): result.append(Property(p.feature(), p.value())) return result def change (properties, feature, value = None): """ Returns a modified version of properties with all values of the given feature replaced by the given value. If 'value' is None the feature will be removed. """ result = [] feature = add_grist (feature) for p in properties: if get_grist (p) == feature: if value: result.append (replace_grist (value, feature)) else: result.append (p) return result ################################################################ # Private functions def __validate1 (property): """ Exit with error if property is not valid. """ msg = None if not property.feature().free(): feature.validate_value_string (property.feature(), property.value()) ################################################################### # Still to port. # Original lines are prefixed with "# " # # # import utility : ungrist ; # import sequence : unique ; # import errors : error ; # import feature ; # import regex ; # import sequence ; # import set ; # import path ; # import assert ; # # # rule validate-property-sets ( property-sets * ) # { # for local s in $(property-sets) # { # validate [ feature.split $(s) ] ; # } # } # def remove(attributes, properties): """Returns a property sets which include all the elements in 'properties' that do not have attributes listed in 'attributes'.""" result = [] for e in properties: attributes_new = feature.attributes(get_grist(e)) has_common_features = 0 for a in attributes_new: if a in attributes: has_common_features = 1 break if not has_common_features: result += e return result def take(attributes, properties): """Returns a property set which include all properties in 'properties' that have any of 'attributes'.""" result = [] for e in properties: if b2.util.set.intersection(attributes, feature.attributes(get_grist(e))): result.append(e) return result def translate_dependencies(properties, project_id, location): result = [] for p in properties: if not p.feature().dependency(): result.append(p) else: v = p.value() m = re.match("(.*)//(.*)", v) if m: rooted = m.group(1) if rooted[0] == '/': # Either project id or absolute Linux path, do nothing. pass else: rooted = os.path.join(os.getcwd(), location, rooted) result.append(Property(p.feature(), rooted + "//" + m.group(2), p.condition())) elif os.path.isabs(v): result.append(p) else: result.append(Property(p.feature(), project_id + "//" + v, p.condition())) return result class PropertyMap: """ Class which maintains a property set -> string mapping. """ def __init__ (self): self.__properties = [] self.__values = [] def insert (self, properties, value): """ Associate value with properties. """ self.__properties.append(properties) self.__values.append(value) def find (self, properties): """ Return the value associated with properties or any subset of it. If more than one subset has value assigned to it, return the value for the longest subset, if it's unique. """ return self.find_replace (properties) def find_replace(self, properties, value=None): matches = [] match_ranks = [] for i in range(0, len(self.__properties)): p = self.__properties[i] if b2.util.set.contains (p, properties): matches.append (i) match_ranks.append(len(p)) best = sequence.select_highest_ranked (matches, match_ranks) if not best: return None if len (best) > 1: raise NoBestMatchingAlternative () best = best [0] original = self.__values[best] if value: self.__values[best] = value return original # local rule __test__ ( ) # { # import errors : try catch ; # import feature ; # import feature : feature subfeature compose ; # # # local rules must be explicitly re-imported # import property : path-order ; # # feature.prepare-test property-test-temp ; # # feature toolset : gcc : implicit symmetric ; # subfeature toolset gcc : version : 2.95.2 2.95.3 2.95.4 # 3.0 3.0.1 3.0.2 : optional ; # feature define : : free ; # feature runtime-link : dynamic static : symmetric link-incompatible ; # feature optimization : on off ; # feature variant : debug release : implicit composite symmetric ; # feature rtti : on off : link-incompatible ; # # compose <variant>debug : <define>_DEBUG <optimization>off ; # compose <variant>release : <define>NDEBUG <optimization>on ; # # import assert ; # import "class" : new ; # # validate <toolset>gcc <toolset>gcc-3.0.1 : $(test-space) ; # # assert.result <toolset>gcc <rtti>off <define>FOO # : refine <toolset>gcc <rtti>off # : <define>FOO # : $(test-space) # ; # # assert.result <toolset>gcc <optimization>on # : refine <toolset>gcc <optimization>off # : <optimization>on # : $(test-space) # ; # # assert.result <toolset>gcc <rtti>off # : refine <toolset>gcc : <rtti>off : $(test-space) # ; # # assert.result <toolset>gcc <rtti>off <rtti>off:<define>FOO # : refine <toolset>gcc : <rtti>off <rtti>off:<define>FOO # : $(test-space) # ; # # assert.result <toolset>gcc:<define>foo <toolset>gcc:<define>bar # : refine <toolset>gcc:<define>foo : <toolset>gcc:<define>bar # : $(test-space) # ; # # assert.result <define>MY_RELEASE # : evaluate-conditionals-in-context # <variant>release,<rtti>off:<define>MY_RELEASE # : <toolset>gcc <variant>release <rtti>off # # ; # # try ; # validate <feature>value : $(test-space) ; # catch "Invalid property '<feature>value': unknown feature 'feature'." ; # # try ; # validate <rtti>default : $(test-space) ; # catch \"default\" is not a known value of feature <rtti> ; # # validate <define>WHATEVER : $(test-space) ; # # try ; # validate <rtti> : $(test-space) ; # catch "Invalid property '<rtti>': No value specified for feature 'rtti'." ; # # try ; # validate value : $(test-space) ; # catch "value" is not a value of an implicit feature ; # # # assert.result <rtti>on # : remove free implicit : <toolset>gcc <define>foo <rtti>on : $(test-space) ; # # assert.result <include>a # : select include : <include>a <toolset>gcc ; # # assert.result <include>a # : select include bar : <include>a <toolset>gcc ; # # assert.result <include>a <toolset>gcc # : select include <bar> <toolset> : <include>a <toolset>gcc ; # # assert.result <toolset>kylix <include>a # : change <toolset>gcc <include>a : <toolset> kylix ; # # # Test ordinary properties # assert.result # : split-conditional <toolset>gcc # ; # # # Test properties with ":" # assert.result # : split-conditional <define>FOO=A::B # ; # # # Test conditional feature # assert.result <toolset>gcc,<toolset-gcc:version>3.0 <define>FOO # : split-conditional <toolset>gcc,<toolset-gcc:version>3.0:<define>FOO # ; # # feature.finish-test property-test-temp ; # } #
flingone/frameworks_base_cmds_remoted
libs/boost/tools/build/src/build/property.py
Python
apache-2.0
19,263
import time import json import requests from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from bs4 import BeautifulSoup as BS from pymongo import MongoClient client = MongoClient() db = client.temp5 ## database that we are using r=requests.get("http://mtcbus.org/Routes.asp?cboRouteCode=&submit=Search") soup=BS(r.text,'html.parser') browser= webdriver.Chrome(executable_path="/home/vinay/Downloads/chromedriver") browser.get("http://mtcbus.org/BusTimeSchedule.asp") time.sleep(1) busnumfile=open("super_busno.txt","r") ## final busnumber list minifile=open("minibusinfo.txt","w") mynewbusnolist=[] for val in busnumfile: num=val.rstrip('\n') mynewbusnolist.append(num) selectbusnum= Select(browser.find_element_by_name('cboRNO')) ## selects the busnumber field in browser counter=0 suc_counter=0 for p in range(25,len(mynewbusnolist)): a=db.masterbus.find({"busNo" :mynewbusnolist[p]}) points=[] for document in a: stoplist=document['busStopList'] points.append(document['source']) points.append(document['destination']) ## gets the src and dest from database selectbusnum= Select(browser.find_element_by_name('cboRNO')) selectbusnum.select_by_visible_text(mynewbusnolist[p]) k=0 for j in range(0,2): z=0 elem0 = browser.find_element_by_xpath("//*") source_code0 = elem0.get_attribute("outerHTML") ## gets the html document soup=BS(source_code0,'html.parser') selectstop = Select(browser.find_element_by_name('cboFR')) selectstop.select_by_visible_text(points[j]) searchbutton=browser.find_element_by_xpath("//input[@type='submit']") searchbutton.click() elem = browser.find_element_by_xpath("//*") source_code = elem.get_attribute("outerHTML") soup=BS(source_code,'html.parser') tables=soup.findAll('table') ## gets all tables if(j==0): src=points[0] dest=points[1] if(j==1): src=points[1] dest=points[0] num_tables=(len(tables)-6)/2 pval=-1 for k in range(0,num_tables): tnum=6+(k*2) main_rows=tables[tnum].findAll('tr') main_tds=main_rows[0].findAll('td') z1=main_tds[1].text z2=main_tds[3].text if((src in z1) and (dest in z2)): suc_counter=suc_counter+1 pval=k break if(pval==-1): continue mynum=6+(pval*2) trs=tables[mynum+1].findAll('tr') timelist=[] gs=0 for row in trs: tds=row.findAll('td') for td in tds: gs=gs+1 finaldata={} finaldata['id']=gs finaldata['busNo']=mynewbusnolist[p] finaldata['source']=src finaldata['destination']=dest finaldata['averageSpeed']=30 finaldata['startTime']=td.text finaldata['Timings']=[] timelist.append(td.text) finaldata_md={ "id" : gs, "busNo" : mynewbusnolist[p], "source" : src, "destination" : dest, "averageSpeed" : 30, "startTime" : td.text, "Timings" : [] } result=db.minibus1.insert_one(finaldata_md) json.dump(finaldata,minifile) minifile.write('\n')
arjun-krishna/WhenBus
server/data/MTCData/Data_Scrapping/MasterBusInfoScrapper.py
Python
mit
3,141
# 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 versionutils from oslo_policy import policy from manila.policies import base BASE_POLICY_NAME = 'share_server:%s' DEPRECATED_REASON = """ The share server API now supports system scope and default roles. """ deprecated_server_index = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'index', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) deprecated_server_show = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'show', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) deprecated_server_details = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'details', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) deprecated_server_delete = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'delete', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) deprecated_manage_server = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'manage_share_server', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) deprecated_unmanage_server = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'unmanage_share_server', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) deprecated_server_reset_status = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'reset_status', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) deprecated_server_migration_start = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'share_server_migration_start', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) deprecated_server_migration_check = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'share_server_migration_check', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) deprecated_server_migration_complete = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'share_server_migration_complete', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) deprecated_server_migration_cancel = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'share_server_migration_cancel', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) deprecated_server_migration_get_progress = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'share_server_migration_get_progress', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) deprecated_server_reset_task_state = policy.DeprecatedRule( name=BASE_POLICY_NAME % 'share_server_reset_task_state', check_str=base.RULE_ADMIN_API, deprecated_reason=DEPRECATED_REASON, deprecated_since=versionutils.deprecated.WALLABY ) share_server_policies = [ policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'index', check_str=base.SYSTEM_READER, scope_types=['system'], description="Get share servers.", operations=[ { 'method': 'GET', 'path': '/share-servers', }, { 'method': 'GET', 'path': '/share-servers?{query}', } ], deprecated_rule=deprecated_server_index ), policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'show', check_str=base.SYSTEM_READER, scope_types=['system'], description="Show share server.", operations=[ { 'method': 'GET', 'path': '/share-servers/{server_id}', } ], deprecated_rule=deprecated_server_show ), policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'details', check_str=base.SYSTEM_READER, scope_types=['system'], description="Get share server details.", operations=[ { 'method': 'GET', 'path': '/share-servers/{server_id}/details', } ], deprecated_rule=deprecated_server_details ), policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'delete', check_str=base.SYSTEM_ADMIN, scope_types=['system'], description="Delete share server.", operations=[ { 'method': 'DELETE', 'path': '/share-servers/{server_id}', } ], deprecated_rule=deprecated_server_delete ), policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'manage_share_server', check_str=base.SYSTEM_ADMIN, scope_types=['system'], description="Manage share server.", operations=[ { 'method': 'POST', 'path': '/share-servers/manage' } ], deprecated_rule=deprecated_manage_server ), policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'unmanage_share_server', check_str=base.SYSTEM_ADMIN, scope_types=['system'], description="Unmanage share server.", operations=[ { 'method': 'POST', 'path': '/share-servers/{share_server_id}/action' } ], deprecated_rule=deprecated_unmanage_server ), policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'reset_status', check_str=base.SYSTEM_ADMIN, scope_types=['system'], description="Reset the status of a share server.", operations=[ { 'method': 'POST', 'path': '/share-servers/{share_server_id}/action' } ], deprecated_rule=deprecated_server_reset_status ), policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'share_server_migration_start', check_str=base.SYSTEM_ADMIN, scope_types=['system'], description="Migrates a share server to the specified host.", operations=[ { 'method': 'POST', 'path': '/share-servers/{share_server_id}/action', } ], deprecated_rule=deprecated_server_migration_start ), policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'share_server_migration_check', check_str=base.SYSTEM_READER, scope_types=['system'], description="Check if can migrates a share server to the specified " "host.", operations=[ { 'method': 'POST', 'path': '/share-servers/{share_server_id}/action', } ], deprecated_rule=deprecated_server_migration_check ), policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'share_server_migration_complete', check_str=base.SYSTEM_ADMIN, scope_types=['system'], description="Invokes the 2nd phase of share server migration.", operations=[ { 'method': 'POST', 'path': '/share-servers/{share_server_id}/action', } ], deprecated_rule=deprecated_server_migration_complete ), policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'share_server_migration_cancel', check_str=base.SYSTEM_ADMIN, scope_types=['system'], description="Attempts to cancel share server migration.", operations=[ { 'method': 'POST', 'path': '/share-servers/{share_server_id}/action', } ], deprecated_rule=deprecated_server_migration_cancel ), policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'share_server_migration_get_progress', check_str=base.SYSTEM_READER, scope_types=['system'], description=("Retrieves the share server migration progress for a " "given share server."), operations=[ { 'method': 'POST', 'path': '/share-servers/{share_server_id}/action', } ], deprecated_rule=deprecated_server_migration_get_progress ), policy.DocumentedRuleDefault( name=BASE_POLICY_NAME % 'share_server_reset_task_state', check_str=base.SYSTEM_ADMIN, scope_types=['system'], description=("Resets task state."), operations=[ { 'method': 'POST', 'path': '/share-servers/{share_server_id}/action', } ], deprecated_rule=deprecated_server_reset_task_state ), ] def list_rules(): return share_server_policies
openstack/manila
manila/policies/share_server.py
Python
apache-2.0
9,783
from __future__ import unicode_literals from netmiko.base_connection import BaseConnection class CheckPointGaiaSSH(BaseConnection): """ Implements methods for communicating with Check Point Gaia firewalls. """ def session_preparation(self): """ Prepare the session after the connection has been established. Set the base prompt for interaction ('>'). """ self._test_channel_read() self.set_base_prompt() self.disable_paging(command="set clienv rows 0\n") def config_mode(self, config_command=''): """No config mode for Check Point devices.""" return '' def exit_config_mode(self, exit_config=''): """No config mode for Check Point devices.""" return ''
michaelrosejr/pyaos6
netmiko/checkpoint/checkpoint_gaia_ssh.py
Python
mit
774
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class VirtualNetworkGatewaySku(Model): """VirtualNetworkGatewaySku details. :param name: Gateway SKU name. Possible values are: 'Basic', 'HighPerformance','Standard', and 'UltraPerformance'. Possible values include: 'Basic', 'HighPerformance', 'Standard', 'UltraPerformance' :type name: str or ~azure.mgmt.network.v2016_09_01.models.VirtualNetworkGatewaySkuName :param tier: Gateway SKU tier. Possible values are: 'Basic', 'HighPerformance','Standard', and 'UltraPerformance'. Possible values include: 'Basic', 'HighPerformance', 'Standard', 'UltraPerformance' :type tier: str or ~azure.mgmt.network.v2016_09_01.models.VirtualNetworkGatewaySkuTier :param capacity: The capacity. :type capacity: int """ _validation = { 'name': {'required': True}, 'tier': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'tier': {'key': 'tier', 'type': 'str'}, 'capacity': {'key': 'capacity', 'type': 'int'}, } def __init__(self, name, tier, capacity=None): super(VirtualNetworkGatewaySku, self).__init__() self.name = name self.tier = tier self.capacity = capacity
AutorestCI/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2016_09_01/models/virtual_network_gateway_sku.py
Python
mit
1,754
# MajorMajor - Collaborative Document Editing Library # Copyright (C) 2013 Ritchie Wilson # # 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 majormajor.document import Document from majormajor.ops.op import Op from majormajor.changeset import Changeset class TestDocumentHelpers: def setup_method(self, method): self.doc0 = Document(snapshot={}) self.doc0.HAS_EVENT_LOOP = False s1 = {'first': 'some string', 'second': {'third':'more string', 'fourth':{'numb':55}}, 'fifth': [55,66,{'sixth': 'deep string'}, 'rw']} self.doc1 = Document(snapshot=s1) self.doc1.HAS_EVENT_LOOP = False s2 = [{'name':'value'}, [1,2,3,4], 'normal, ol string', [['multi'],['dimen'],['array']], True, None, 42] self.doc2 = Document(snapshot=s2) self.doc2.HAS_EVENT_LOOP = False self.doc3 = Document(snapshot = "ABCDEFG") self.doc3.HAS_EVENT_LOOP = False def test_get_id(self): doc = Document('abc456') assert doc.get_id() == 'abc456' # Testing that Document can tell if a path is valid in its # snapshot without throwing any exceptions def test_contains_path(self): doc0 = self.doc0 doc1 = self.doc1 doc2 = self.doc2 doc3 = self.doc3 # all documents have a root (empty path) path1 = [] assert doc0.contains_path(path1) assert doc1.contains_path(path1) assert doc2.contains_path(path1) path2 = ['first'] assert doc0.contains_path(path2) == False assert doc1.contains_path(path2) path3 = ['second','fourth','numb'] assert doc1.contains_path(path3) path4 = ['fifth',2,'sixth'] assert doc1.contains_path(path4) # final key is not valid path5 = ['fifth',2,'deep string'] assert doc1.contains_path(path5) == False # middle key is not valid path6 = ['second','first','numb'] assert doc1.contains_path(path6) == False # 4 is one out of path path7 = ['second','fifth',4] assert doc1.contains_path(path7) == False # path can only be number when looking at list path8 = [0] assert doc0.contains_path(path8) == False assert doc1.contains_path(path8) == False assert doc2.contains_path(path8) == True path9 = [3,2] assert doc2.contains_path(path9) # This snapshot is just a string. Should have no path but # root. path10 = [3] assert doc3.contains_path(path10) == False # Testing the a document can get the value at the given # path. First some tests on deep nesting, then testing weirder # values like True or None (null in json) def test_get_value(self): doc0 = self.doc0 doc1 = self.doc1 doc2 = self.doc2 path1 = [] assert doc0.get_node(path1) == {} assert doc1.get_node(path1) == doc1.get_snapshot() assert doc2.get_node(path1) == doc2.get_snapshot() path2 = ['first'] assert doc1.get_value(path2) == 'some string' path3 = ['second'] assert doc1.get_value(path3) == \ {'third':'more string', 'fourth':{'numb':55}} path4 = ['second','fourth','numb'] assert doc1.get_value(path4) == 55 path5 = ['fifth',2,'sixth'] assert doc1.get_value(path5) == 'deep string' path6 = [0, 'name'] assert doc2.get_value(path6) == 'value' path7 = [3,1,0] assert doc2.get_value(path7) == 'dimen' path8 = [1,3] assert doc2.get_value(path8) == 4 path9 = [4] assert doc2.get_value(path9) == True path10 = [5] assert doc2.get_value(path10) == None def test_has_needed_dependencies(self): doc = self.doc0 cs1 = Changeset(doc.get_id(), 'user', [doc.get_root_changeset()]) assert doc.has_needed_dependencies(cs1) cs2 = Changeset(doc.get_id(), 'user', [cs1]) assert not doc.has_needed_dependencies(cs2) doc.receive_changeset(cs1) assert doc.has_needed_dependencies(cs2) cs3 = Changeset(doc.get_id(), 'user', [cs1, cs2]) assert not doc.has_needed_dependencies(cs3) doc.receive_changeset(cs2) assert doc.has_needed_dependencies(cs3) cs4 = Changeset(doc.get_id(), 'user', [cs3, "555"]) assert not doc.has_needed_dependencies(cs4) doc.receive_changeset(cs3) assert not doc.has_needed_dependencies(cs4) cs5 = Changeset(doc.get_id(), 'user', [cs1]) cs5.set_id("555") doc.receive_changeset(cs5) cs4.relink_changesets(doc.all_known_changesets) assert cs5 in cs4.get_parents() assert cs4.has_full_dependency_info() assert doc.has_needed_dependencies(cs4)
ritchiewilson/majormajor
tests/document/test_document_helpers.py
Python
gpl-3.0
5,647
# Copyright (c) 2014 Greg James, Visual6502.org # # 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. #------------------------------------------------------------------------------ # # nmosFet.py # NMOS Field-effect transistor # class NmosFet: GATE_LOW = 0 GATE_HIGH = 1 << 0 def __init__(self, idIndex, side1WireIndex, side2WireIndex, gateWireIndex): # Wires switched together when this transistor is on self.side1WireIndex = side1WireIndex self.side2WireIndex = side2WireIndex self.gateWireIndex = gateWireIndex self.gateState = NmosFet.GATE_LOW self.index = idIndex def __repr__(self): rstr = 'NFET %d: %d gate %d [%d, %d]'%(self.index, self.state, self.gateWireIndex, self.size1WireIndex, self.side2WireIndex) return rstr
ericmjonas/Sim2600
sim2600/nmosFet.py
Python
cc0-1.0
1,841
#!/usr/bin/python # -*- coding: utf-8 -*- # Distributed under the terms of the CC-BY-SA 3.0 . # Reza (User:Reza1615) Code structure + Developing the code import re,codecs,os,wikipedia,query bot_address=u'/home/reza/compat/' faSite = wikipedia.getSite('fa') #---------------- SimilarPersianCharacters=ur'\u0643\uFB91\uFB90\uFB8F\uFB8E\uFEDC\uFEDB\uFEDA\uFED9\u0649\uFEEF\u064A\u06C1\u06D5\u06BE\uFEF0-\uFEF4' vowels = ur'\u064B-\u0650\u0652\u0654-\u0670' persianCharacters = ur'\u0621-\u0655\u067E\u0686\u0698\u06AF\u06A9\u0643\u06AA\uFED9\uFEDA\u06CC\uFEF1\uFEF2'+SimilarPersianCharacters #---------------- persianGlyphs = { # these two are for visually available ZWNJ #visualZwnj u'‌ه': u'ﻫ',u'ی‌': u'ﻰﻲ', u'ﺃ': u'ﺄﺃ',u'ﺁ': u'ﺁﺂ',u'ﺇ': u'ﺇﺈ',u'ا': u'ﺎا', u'ب': u'ﺏﺐﺑﺒ',u'پ': u'ﭖﭗﭘﭙ',u'ت': u'ﺕﺖﺗﺘ',u'ث': u'ﺙﺚﺛﺜ', u'ج': u'ﺝﺞﺟﺠ',u'چ': u'ﭺﭻﭼﭽ',u'ح': u'ﺡﺢﺣﺤ',u'خ': u'ﺥﺦﺧﺨ', u'د': u'ﺩﺪ',u'ذ': u'ﺫﺬ',u'ر': u'ﺭﺮ',u'ز': u'ﺯﺰ', u'ژ': u'ﮊﮋ',u'س': u'ﺱﺲﺳﺴ',u'ش': u'ﺵﺶﺷﺸ',u'ص': u'ﺹﺺﺻﺼ', u'ض': u'ﺽﺾﺿﻀ',u'ط': u'ﻁﻂﻃﻄ',u'ظ': u'ﻅﻆﻇﻈ',u'ع': u'ﻉﻊﻋﻌ', u'غ': u'ﻍﻎﻏﻐ',u'ف': u'ﻑﻒﻓﻔ',u'ق': u'ﻕﻖﻗﻘ',u'ک': u'ﮎﮏﮐﮑﻙﻚﻛﻜ', u'گ': u'ﮒﮓﮔﮕ',u'ل': u'ﻝﻞﻟﻠ',u'م': u'ﻡﻢﻣﻤ',u'ن': u'ﻥﻦﻧﻨ', u'ه': u'ﻩﻪﻫﻬ',u'هٔ': u'ﮤﮥ',u'و': u'ﻭﻮ',u'ﺅ': u'ﺅﺆ', u'ی': u'ﯼﯽﯾﯿﻯﻰﻱﻲﻳﻴ',u'ئ': u'ﺉﺊﺋﺌ',u'لا': u'ﻼ',u'ﻹ': u'ﻺ', u'ﻷ': u'ﻸ',u'ﻵ': u'ﻶ' } #----------------- def Check_Page_Exists(page_link): page_link=page_link.replace(u' ',u'_') params = { 'action': 'query', 'prop':'info', 'titles': page_link } query_page = query.GetData(params,faSite) try: for i in query_page[u'query'][u'pages']: redirect_link=query_page[u'query'][u'pages'][i]['pageid'] return False# page existed except: return True# page not existed def getlinks(BadLink,correctLink): site = wikipedia.getSite('fa') try: page = wikipedia.Page(site,BadLink) linktos=page.getReferences() except: return True for page in linktos: try: text=page.get() except: continue wikipedia.output(u'checking '+page.title()+u' .....') text2=text if text.find(BadLink)!=-1: text2=text2.replace(u'[['+BadLink+u']]',u'[['+correctLink+u']]').replace(u'[['+BadLink+u'|',u'[['+correctLink+u'|').replace(u'\r',u'') text2=text2.replace(u'[[ '+BadLink+u']]',u'[['+correctLink+u']]').replace(u'[[ '+BadLink+u'|',u'[['+correctLink+u'|') text2=text2.replace(u'[[ '+BadLink+u' ]]',u'[['+correctLink+u']]').replace(u'[[ '+BadLink+u' |',u'[['+correctLink+u'|') text2=text2.replace(u'[['+BadLink+u' ]]',u'[['+correctLink+u']]').replace(u'[['+BadLink+u' |',u'[['+correctLink+u'|') text2=text2.replace(u'[[ '+BadLink+u' ]]',u'[['+correctLink+u']]').replace(u'[[ '+BadLink+u' |',u'[['+correctLink+u'|') #-------------------------------------------for cats----------------------------------- text2=text2.replace(u'[[:'+BadLink+u']]',u'[[:'+correctLink+u']]').replace(u'[[:'+BadLink+u'|',u'[[:'+correctLink+u'|') text2=text2.replace(u'[[: '+BadLink+u']]',u'[[:'+correctLink+u']]').replace(u'[[: '+BadLink+u'|',u'[[:'+correctLink+u'|') text2=text2.replace(u'[[: '+BadLink+u' ]]',u'[[:'+correctLink+u']]').replace(u'[[: '+BadLink+u' |',u'[[:'+correctLink+u'|') text2=text2.replace(u'[[:'+BadLink+u' ]]',u'[[:'+correctLink+u']]').replace(u'[[:'+BadLink+u' |',u'[[:'+correctLink+u'|') text2=text2.replace(u'[[ :'+BadLink+u' ]]',u'[[:'+correctLink+u']]').replace(u'[[ :'+BadLink+u' |',u'[[:'+correctLink+u'|') text2=text2.replace(u'[[ : '+BadLink+u' ]]',u'[[:'+correctLink+u']]').replace(u'[[ : '+BadLink+u' |',u'[[:'+correctLink+u'|') if text2.find(correctLink)==-1: wikipedia.output(u'\03{lightblue}could not find any link\03{default}') if text!=text2: try: page.put(text2,u'ربات:اصلاح پیوند به تغییرمسیر نامحتمل (دارای کارکترهای نادرست)') wikipedia.output(u'\03{lightgreen}the page '+page.title()+u' had replcae item [['+BadLink+u']] > [['+correctLink+u']]\03{default}') except: wikipedia.output(u'\03{lightred}the page '+page.title()+u' could not replaced so it passed\03{default}') continue else: wikipedia.output(u'\03{lightred}could not find andy link\03{default}') return True def NoneFarsi_to_Farsi(txt): old_txt=txt # Function for removing incorrect ZWNJs txt =re.sub(ur"([\u200c\u200e])([\s\n])", ur'\2',txt) txt =re.sub(ur"([\s\n])([\u200c\u200e])", ur'\1',txt) #واکه‌های کوتاه پشت سرهم نمی‌آیند و یک حرف باید بینشان فاصله باشد txt = re.sub(ur'([' + vowels + ur']){2,}', ur"\1",txt) #تبدیل نویسه‌های منقطع به نویسه‌های استاندارد for i in persianGlyphs: txt =re.sub(ur'[' + persianGlyphs[i] + ur']', i,txt) return txt def ZWNJ_cleaning(text): old_text=text #تمیزکاری فاصلهٔ مجازی text = re.sub(u'(\u202A|\u202B|\u202C|\u202D|\u202E|\u200F)',u'\u200C', text)#حذف کارکترهای تغییرجهت text = re.sub(ur'‌{2,}', ur'‌', text) # پشت‌سرهم text = re.sub(ur'‌(?!['+persianCharacters+u']|[\u0900-\u097F]|ֹ)', ur'', text) # در پس DEVANAGARI text = re.sub(ur'(?<![['+persianCharacters+u']|[\u0900-\u097F]|f|ֹ)‌', ur'', text) # در پیش DEVANAGARI # Clean ZWNJs after characters that don't conncet to the next letter text = re.sub(ur'([۰-۹0-9إأةؤورزژاآدذ،؛,\:«»\\\/@#$٪×\*\(\)ـ\-=\|])\u200c', ur"\1", text) # Clean ZWNJs before and after English characters text = re.sub(ur'\u200c([\w])', u"\1", text) text = re.sub(ur'([\w])\u200c', u"\1", text) # Clean ZWNJs after and before punctuation text = re.sub(ur'\u200c([\n\s\[\]\.،«»\:\(\)\؛\؟\?\;\$\!\@\-\=\+\\\|])', ur"\1", text) text = re.sub(ur'([\n\s\[\.،«»\:\(\)\؛\؟\?\;\$\!\@\-\=\+\\\|])\u200c', ur"\1", text) # Clean ZWNJs before brakets which have sapce after\before them text = re.sub(ur'\u200c(\]\][\s\n])', ur"\1", text) text = re.sub(ur'([\n\s]\[\[)\u200c', ur"\1", text) return text def main(): os.system(u'sql fawiki_p "SELECT page_title FROM page WHERE page_namespace = 0 AND page_is_redirect = 1;" >'+bot_address+u'fa_redirect_list.txt') print 'Qury is got!' text = codecs.open(bot_address+u"fa_redirect_list.txt",'r' ,'utf8' ) text = text.read() text=text.replace(u'\r',u'').replace(u'_',u' ') list1,list2=u'\n',u'\n' for line in text.split(u'\n'): line=u' '+line+u' ' old_line=line line=NoneFarsi_to_Farsi(line) line=ZWNJ_cleaning(line) if line!=old_line and len(old_line[1:-1])>1: if Check_Page_Exists(line[1:-1]): list1+=u'\n* [['+old_line[1:-1]+u']]' else: list2+=u'\n* [['+old_line[1:-1]+u']]> [['+line[1:-1]+u']]' wikipedia.output(u'Orginal='+old_line+u'|'+line+u'|') wikipedia.output(u'Second='+old_line[1:-1]+u'|'+line[1:-1]+u'|') result= getlinks(old_line[1:-1],line[1:-1]) fapage=wikipedia.Page(faSite,u'ویکی‌پدیا:گزارش دیتابیس/تغییرمسیرهای دارای نویسنه نادرست') fapage.put(u'== برای حذف ==\nموارد زیر در مقالات و صفحات با موارد درست جایگزین شدهاند و فقط باید آنها را حذف کرد.\n'+list1+u'\n== برای انتقال ==\nموارد زیر بعد از انتقال ستون اول را میتوان حذف کرد\n'+list2,u'ربات:به‌روزرسانی گزارش') main()
PersianWikipedia/Database-reports
zzcleaning_redirects.py
Python
mit
8,870
# # 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. # """Unit tests for the http_client module.""" # pytype: skip-file import os import unittest import mock from httplib2 import ProxyInfo from apache_beam.internal.http_client import DEFAULT_HTTP_TIMEOUT_SECONDS from apache_beam.internal.http_client import get_new_http from apache_beam.internal.http_client import proxy_info_from_environment_var class HttpClientTest(unittest.TestCase): def test_proxy_from_env_http_with_port(self): with mock.patch.dict(os.environ, http_proxy='http://localhost:9000'): proxy_info = proxy_info_from_environment_var('http_proxy') expected = ProxyInfo(3, 'localhost', 9000) self.assertEqual(str(expected), str(proxy_info)) def test_proxy_from_env_https_with_port(self): with mock.patch.dict(os.environ, https_proxy='https://localhost:9000'): proxy_info = proxy_info_from_environment_var('https_proxy') expected = ProxyInfo(3, 'localhost', 9000) self.assertEqual(str(expected), str(proxy_info)) def test_proxy_from_env_http_without_port(self): with mock.patch.dict(os.environ, http_proxy='http://localhost'): proxy_info = proxy_info_from_environment_var('http_proxy') expected = ProxyInfo(3, 'localhost', 80) self.assertEqual(str(expected), str(proxy_info)) def test_proxy_from_env_https_without_port(self): with mock.patch.dict(os.environ, https_proxy='https://localhost'): proxy_info = proxy_info_from_environment_var('https_proxy') expected = ProxyInfo(3, 'localhost', 443) self.assertEqual(str(expected), str(proxy_info)) def test_proxy_from_env_http_without_method(self): with mock.patch.dict(os.environ, http_proxy='localhost:8000'): proxy_info = proxy_info_from_environment_var('http_proxy') expected = ProxyInfo(3, 'localhost', 8000) self.assertEqual(str(expected), str(proxy_info)) def test_proxy_from_env_https_without_method(self): with mock.patch.dict(os.environ, https_proxy='localhost:8000'): proxy_info = proxy_info_from_environment_var('https_proxy') expected = ProxyInfo(3, 'localhost', 8000) self.assertEqual(str(expected), str(proxy_info)) def test_proxy_from_env_http_without_port_without_method(self): with mock.patch.dict(os.environ, http_proxy='localhost'): proxy_info = proxy_info_from_environment_var('http_proxy') expected = ProxyInfo(3, 'localhost', 80) self.assertEqual(str(expected), str(proxy_info)) def test_proxy_from_env_https_without_port_without_method(self): with mock.patch.dict(os.environ, https_proxy='localhost'): proxy_info = proxy_info_from_environment_var('https_proxy') expected = ProxyInfo(3, 'localhost', 443) self.assertEqual(str(expected), str(proxy_info)) def test_proxy_from_env_invalid_var(self): proxy_info = proxy_info_from_environment_var('http_proxy_host') expected = None self.assertEqual(str(expected), str(proxy_info)) def test_proxy_from_env_wrong_method_in_var_name(self): with mock.patch.dict(os.environ, smtp_proxy='localhost'): with self.assertRaises(KeyError): proxy_info_from_environment_var('smtp_proxy') def test_proxy_from_env_wrong_method_in_url(self): with mock.patch.dict(os.environ, http_proxy='smtp://localhost:8000'): proxy_info = proxy_info_from_environment_var('http_proxy') expected = ProxyInfo(3, 'smtp', 80) # wrong proxy info generated self.assertEqual(str(expected), str(proxy_info)) def test_get_new_http_proxy_info(self): with mock.patch.dict(os.environ, http_proxy='localhost'): http = get_new_http() expected = ProxyInfo(3, 'localhost', 80) self.assertEqual(str(http.proxy_info), str(expected)) def test_get_new_http_timeout(self): http = get_new_http() self.assertEqual(http.timeout, DEFAULT_HTTP_TIMEOUT_SECONDS) if __name__ == '__main__': unittest.main()
lukecwik/incubator-beam
sdks/python/apache_beam/internal/http_client_test.py
Python
apache-2.0
4,661
import os import requests # pip install requests # The authentication key (API Key). # Get your own by registering at https://app.pdf.co API_KEY = "******************************************" # Base URL for PDF.co Web API requests BASE_URL = "https://api.pdf.co/v1" # Source PDF file SourceFile = ".\\sample.pdf" # Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'. Pages = "" # PDF document password. Leave empty for unprotected documents. Password = "" def main(args = None): uploadedFileUrl = uploadFile(SourceFile) if (uploadedFileUrl != None): searchTableInPDF(uploadedFileUrl) def searchTableInPDF(uploadedFileUrl): """Search Text using PDF.co Web API""" # Prepare requests params as JSON # See documentation: https://apidocs.pdf.co parameters = {} parameters["password"] = Password parameters["pages"] = Pages parameters["url"] = uploadedFileUrl # Prepare URL for 'PDF Table Search' API request url = "{}/pdf/find/table".format(BASE_URL) # Execute request and get response as JSON response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY }) if (response.status_code == 200): json = response.json() if json["error"] == False: # Display found information print(json["body"]) else: # Show service reported error print(json["message"]) else: print(f"Request error: {response.status_code} {response.reason}") def uploadFile(fileName): """Uploads file to the cloud""" # 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE. # Prepare URL for 'Get Presigned URL' API request url = "{}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={}".format( BASE_URL, os.path.basename(fileName)) # Execute request and get response as JSON response = requests.get(url, headers={ "x-api-key": API_KEY }) if (response.status_code == 200): json = response.json() if json["error"] == False: # URL to use for file upload uploadUrl = json["presignedUrl"] # URL for future reference uploadedFileUrl = json["url"] # 2. UPLOAD FILE TO CLOUD. with open(fileName, 'rb') as file: requests.put(uploadUrl, data=file, headers={ "x-api-key": API_KEY, "content-type": "application/octet-stream" }) return uploadedFileUrl else: # Show service reported error print(json["message"]) else: print(f"Request error: {response.status_code} {response.reason}") return None if __name__ == '__main__': main()
bytescout/ByteScout-SDK-SourceCode
PDF.co Web API/PDF Search Tables/Python/PDF Table Search from Uploaded File/PdfTableSearchFromUploadedFile.py
Python
apache-2.0
2,752
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Test mixed layer, projections and operators. ''' from paddle.trainer_config_helpers import * settings(batch_size=1000, learning_rate=1e-4) din = data_layer(name='test', size=100) din = embedding_layer(input=din, size=256) with mixed_layer(size=100) as m1: m1 += full_matrix_projection(input=din) with mixed_layer(size=100) as m2: m2 += table_projection(input=m1) with mixed_layer(size=100) as m3: m3 += identity_projection(input=m2) with mixed_layer(size=100) as m4: m4 += dotmul_projection(input=m3) with mixed_layer() as m5: m5 += context_projection(input=m4, context_len=3) with mixed_layer() as m6: m6 += dotmul_operator(a=m3, b=m4) m6 += scaling_projection(m3) img = data_layer(name='img', size=32 * 32) flt = data_layer(name='filter', size=3 * 3 * 1 * 64) with mixed_layer() as m7: m7 += conv_operator( img=img, filter=flt, num_filters=64, num_channels=1, filter_size=3) m7 += conv_projection(img, filter_size=3, num_filters=64, num_channels=1) with mixed_layer() as m8: m8 += conv_operator( img=img, filter=flt, num_filters=64, num_channels=1, filter_size=3, stride=2, padding=1, trans=True) m8 += conv_projection( img, filter_size=3, num_filters=64, num_channels=1, stride=2, padding=1, trans=True) end = mixed_layer( input=[ full_matrix_projection(input=m5), trans_full_matrix_projection(input=m6), full_matrix_projection(input=m7), full_matrix_projection(input=m8) ], size=100, layer_attr=ExtraAttr( drop_rate=0.5, error_clipping_threshold=40)) outputs(end)
QiJune/Paddle
python/paddle/trainer_config_helpers/tests/configs/projections.py
Python
apache-2.0
2,317
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('billing', '0004_auto_20150204_2042'), ] operations = [ migrations.AddField( model_name='usermerchantid', name='plan_id', field=models.CharField(max_length=220, null=True, blank=True), preserve_default=True, ), migrations.AddField( model_name='usermerchantid', name='subscription_id', field=models.CharField(max_length=400, null=True, blank=True), preserve_default=True, ), migrations.AlterField( model_name='membership', name='date_end', field=models.DateTimeField(default=datetime.datetime(2015, 2, 6, 22, 1, 49, 533942, tzinfo=utc), verbose_name=b'End Date'), preserve_default=True, ), migrations.AlterField( model_name='membership', name='date_start', field=models.DateTimeField(default=datetime.datetime(2015, 2, 6, 22, 1, 49, 534124, tzinfo=utc), verbose_name=b'Start Date'), preserve_default=True, ), ]
pombredanne/srvup-rest-framework
src/billing/migrations/0005_auto_20150206_2201.py
Python
apache-2.0
1,311
""" Descriptive HTTP status codes, for code readability. See RFC 2616 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html And RFC 6585 - http://tools.ietf.org/html/rfc6585 """ from __future__ import unicode_literals def is_informational(code): return code >= 100 and code <= 199 def is_success(code): return code >= 200 and code <= 299 def is_redirect(code): return code >= 300 and code <= 399 def is_client_error(code): return code >= 400 and code <= 499 def is_server_error(code): return code >= 500 and code <= 599 """ Statuses """ HTTP_100_CONTINUE = 100 HTTP_101_SWITCHING_PROTOCOLS = 101 HTTP_200_OK = 200 HTTP_201_CREATED = 201 HTTP_202_ACCEPTED = 202 HTTP_203_NON_AUTHORITATIVE_INFORMATION = 203 HTTP_204_NO_CONTENT = 204 HTTP_205_RESET_CONTENT = 205 HTTP_206_PARTIAL_CONTENT = 206 HTTP_300_MULTIPLE_CHOICES = 300 HTTP_301_MOVED_PERMANENTLY = 301 HTTP_302_FOUND = 302 HTTP_303_SEE_OTHER = 303 HTTP_304_NOT_MODIFIED = 304 HTTP_305_USE_PROXY = 305 HTTP_306_RESERVED = 306 HTTP_307_TEMPORARY_REDIRECT = 307 HTTP_400_BAD_REQUEST = 400 HTTP_401_UNAUTHORIZED = 401 HTTP_402_PAYMENT_REQUIRED = 402 HTTP_403_FORBIDDEN = 403 HTTP_404_NOT_FOUND = 404 HTTP_405_METHOD_NOT_ALLOWED = 405 HTTP_406_NOT_ACCEPTABLE = 406 HTTP_407_PROXY_AUTHENTICATION_REQUIRED = 407 HTTP_408_REQUEST_TIMEOUT = 408 HTTP_409_CONFLICT = 409 HTTP_410_GONE = 410 HTTP_411_LENGTH_REQUIRED = 411 HTTP_412_PRECONDITION_FAILED = 412 HTTP_413_REQUEST_ENTITY_TOO_LARGE = 413 HTTP_414_REQUEST_URI_TOO_LONG = 414 HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415 HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE = 416 HTTP_417_EXPECTATION_FAILED = 417 HTTP_428_PRECONDITION_REQUIRED = 428 HTTP_429_TOO_MANY_REQUESTS = 429 HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431 HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS = 451 HTTP_500_INTERNAL_SERVER_ERROR = 500 HTTP_501_NOT_IMPLEMENTED = 501 HTTP_502_BAD_GATEWAY = 502 HTTP_503_SERVICE_UNAVAILABLE = 503 HTTP_504_GATEWAY_TIMEOUT = 504 HTTP_505_HTTP_VERSION_NOT_SUPPORTED = 505 HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511 """ Status messages """ msg = { '100': 'CONTINUE', '101': 'SWITCHING_PROTOCOLS', '200': 'OK', '201': 'CREATED', '202': 'ACCEPTED', '203': 'NON_AUTHORITATIVE_INFORMATION', '204': 'NO_CONTENT', '205': 'RESET_CONTENT', '206': 'PARTIAL_CONTENT', '300': 'MULTIPLE_CHOICES', '301': 'MOVED_PERMANENTLY', '302': 'FOUND', '303': 'SEE_OTHER', '304': 'NOT_MODIFIED', '305': 'USE_PROXY', '306': 'RESERVED', '307': 'TEMPORARY_REDIRECT', '400': 'BAD_REQUEST', '401': 'UNAUTHORIZED', '402': 'PAYMENT_REQUIRED', '403': 'FORBIDDEN', '404': 'NOT_FOUND', '405': 'METHOD_NOT_ALLOWED', '406': 'NOT_ACCEPTABLE', '407': 'PROXY_AUTHENTICATION_REQUIRED', '408': 'REQUEST_TIMEOUT', '409': 'CONFLICT', '410': 'GONE', '411': 'LENGTH_REQUIRED', '412': 'PRECONDITION_FAILED', '413': 'REQUEST_ENTITY_TOO_LARGE', '414': 'REQUEST_URI_TOO_LONG', '415': 'UNSUPPORTED_MEDIA_TYPE', '416': 'REQUESTED_RANGE_NOT_SATISFIABLE', '417': 'EXPECTATION_FAILED', '428': 'PRECONDITION_REQUIRED', '429': 'TOO_MANY_REQUESTS', '431': 'REQUEST_HEADER_FIELDS_TOO_LARGE', '451': 'UNAVAILABLE_FOR_LEGAL_REASONS', '500': 'INTERNAL_SERVER_ERROR', '501': 'NOT_IMPLEMENTED', '502': 'BAD_GATEWAY', '503': 'SERVICE_UNAVAILABLE', '504': 'GATEWAY_TIMEOUT', '505': 'HTTP_VERSION_NOT_SUPPORTED', '511': 'NETWORK_AUTHENTICATION_REQUIRED', }
Max201/cleave
cleave/http/status.py
Python
apache-2.0
3,504
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging import django from django.core import signals from django.core.cache.backends.base import BaseCache logging.basicConfig() logger = logging.getLogger(__name__) def get_cache(backend, **kwargs): from django.core import cache as dj_cache if django.VERSION <= (1, 6): cache = dj_cache.get_cache(backend, **kwargs) elif django.VERSION >= (3, 2): cache = dj_cache.caches.create_connection(backend) else: # Django 1.7 to 3.1 cache = dj_cache._create_cache(backend, **kwargs) # Some caches -- python-memcached in particular -- need to do a cleanup at the # end of a request cycle. If not implemented in a particular backend # cache.close is a no-op. Not available in Django 1.5 if hasattr(cache, "close"): signals.request_finished.connect(cache.close) return cache class FallbackCache(BaseCache): _cache = None _cache_fallback = None def __init__(self, params=None, *args, **kwargs): BaseCache.__init__(self, *args, **kwargs) self._cache = get_cache("main_cache") self._cache_fallback = get_cache("fallback_cache") def add(self, key, value, timeout=None, version=None): return self._call_with_fallback( "add", key, value, timeout=timeout, version=version ) def get(self, key, default=None, version=None): return self._call_with_fallback("get", key, default=default, version=version) def set(self, key, value, timeout=None, version=None, client=None): return self._call_with_fallback( "set", key, value, timeout=timeout, version=version ) def delete(self, key, version=None): return self._call_with_fallback("delete", key, version=version) def clear(self): return self._call_with_fallback("clear") def _call_with_fallback(self, method, *args, **kwargs): try: return self._call_main_cache(args, kwargs, method) except Exception as e: logger.warning("Switch to fallback cache") logger.exception(e) return self._call_fallback_cache(args, kwargs, method) def _call_main_cache(self, args, kwargs, method): return getattr(self._cache, method)(*args, **kwargs) def _call_fallback_cache(self, args, kwargs, method): return getattr(self._cache_fallback, method)(*args, **kwargs)
Kub-AT/django-cache-fallback
cache_fallback/cache.py
Python
mit
2,454
#Calculating with dictionaries prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } print(zip(prices.keys(),prices.values())) for elem in zip(prices.keys(),prices.values()): print(elem) min_price = min(zip(prices.values(),prices.keys())) print("Min Price: ",min_price) max_price = max(zip(prices.values(),prices.keys())) print("Max Price: ",max_price) #If you try to perform common data reductions on a dictionary, you’ll find that they only process the keys, not the values print(min(prices)) print(max(prices)) #You can get the key corresponding to the min or max value if you supply a key function to min() and max(). print(min(prices,key=lambda k : prices[k])) print(max(prices,key=lambda k : prices[k])) #TO get min,max value we have to perform extra lookup step print(prices[min(prices,key=lambda k : prices[k])]) print(prices[max(prices,key=lambda k : prices[k])])
ishank296/python-cookbook
Chapter_1/calculating_with_dict.py
Python
gpl-3.0
929
# Copyright 2012 OpenStack Foundation # # 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. """ An in memory implementation of the trusts API. only to be used for testing purposes """ import copy from oslo.utils import timeutils from keystone.common import kvs from keystone import exception from keystone import trust as keystone_trust def _filter_trust(ref): if ref['deleted']: return None if ref.get('expires_at') and timeutils.utcnow() > ref['expires_at']: return None remaining_uses = ref.get('remaining_uses') # Do not return trusts that can't be used anymore if remaining_uses is not None: if remaining_uses <= 0: return None ref = copy.deepcopy(ref) return ref class Trust(kvs.Base, keystone_trust.Driver): def create_trust(self, trust_id, trust, roles): trust_ref = copy.deepcopy(trust) trust_ref['id'] = trust_id trust_ref['deleted'] = False trust_ref['roles'] = roles if (trust_ref.get('expires_at') and trust_ref['expires_at'].tzinfo is not None): trust_ref['expires_at'] = (timeutils.normalize_time (trust_ref['expires_at'])) self.db.set('trust-%s' % trust_id, trust_ref) trustee_user_id = trust_ref['trustee_user_id'] trustee_list = self.db.get('trustee-%s' % trustee_user_id, []) trustee_list.append(trust_id) self.db.set('trustee-%s' % trustee_user_id, trustee_list) trustor_user_id = trust_ref['trustor_user_id'] trustor_list = self.db.get('trustor-%s' % trustor_user_id, []) trustor_list.append(trust_id) self.db.set('trustor-%s' % trustor_user_id, trustor_list) return trust_ref def consume_use(self, trust_id): try: orig_ref = self.db.get('trust-%s' % trust_id) except exception.NotFound: raise exception.TrustNotFound(trust_id=trust_id) remaining_uses = orig_ref.get('remaining_uses') if remaining_uses is None: # unlimited uses, do nothing return elif remaining_uses > 0: ref = copy.deepcopy(orig_ref) ref['remaining_uses'] -= 1 self.db.set('trust-%s' % trust_id, ref) else: raise exception.TrustUseLimitReached(trust_id=trust_id) def get_trust(self, trust_id): try: ref = self.db.get('trust-%s' % trust_id) return _filter_trust(ref) except exception.NotFound: return None def delete_trust(self, trust_id): try: ref = self.db.get('trust-%s' % trust_id) except exception.NotFound: raise exception.TrustNotFound(trust_id=trust_id) ref['deleted'] = True self.db.set('trust-%s' % trust_id, ref) def list_trusts(self): trusts = [] for key, value in self.db.items(): if key.startswith("trust-") and not value['deleted']: trusts.append(value) return trusts def list_trusts_for_trustee(self, trustee_user_id): trusts = [] for trust in self.db.get('trustee-%s' % trustee_user_id, []): trusts.append(self.get_trust(trust)) return trusts def list_trusts_for_trustor(self, trustor_user_id): trusts = [] for trust in self.db.get('trustor-%s' % trustor_user_id, []): trusts.append(self.get_trust(trust)) return trusts
scrapinghub/keystone
keystone/trust/backends/kvs.py
Python
apache-2.0
4,003
#! /usr/bin/env python # Copyright (C) 2014 Mikael Arguedas # # 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. # # run_blender_script.py # Authors: Mikael Arguedas [mikael.arguedas@gmail.com] # This script is a launcher for every blender script available in naoqi_tools # It defines a set of parameter and format them to sned the right bash commands # to Launch blender with the chosen script and the right arguments from __future__ import print_function import os import argparse import subprocess parser = argparse.ArgumentParser(usage='Export meshes and convert them') parser.add_argument('-s', '--scriptfile', default='io_export_collision.py', help='name of the blender script to Launch') parser.add_argument('-b', '--blenderdir', default='/usr/bin', help='location of your blender directory') parser.add_argument('-i', '--inputmeshdir', default=None, help='directory where collada meshes are located') parser.add_argument('-o', '--outputdir', default=None, help='directory to export the meshes to') parser.add_argument('-r', '--ratio', default=0.1, help='float value, ratio used to decimate meshes', type=float) parser.add_argument('-t', '--threshold', default=50, help='integer: minimum number of vertices for decimation', type=int) parser.add_argument('--scale', default=1, help='scale to resize the collada meshes to', type=float) parser.add_argument('-n', '--outputfilename', default=None, help='name of the output file (for material file)') parser.add_argument('-f', '--blenderfile', default=None, help='path of the blender file to process') args = parser.parse_args() clean = False def check_output_dir(out): if not os.path.isdir(out): print('creating the output folder because it does not exist') os.makedirs(out) return out # Create path to script script_path = subprocess.check_output('rospack find naoqi_tools', stderr=subprocess.STDOUT, shell=True)[:-1] script_path = os.path.join(script_path, 'scripts', 'blender', args.scriptfile) # Check script existence if(not os.path.isfile(script_path)): print("script doesn't exist\nExiting now") exit(1) # Check if args.outputdir is valid if args.scriptfile != 'io_export_visual.py': if args.outputdir is None: print('\nno valid output directory: using ' + str(args.inputmeshdir) + ' as destination folder') output_dir = args.inputmeshdir else: output_dir = check_output_dir(args.outputdir) # Check existence of the input directory if args.inputmeshdir is None or not os.path.isdir(args.inputmeshdir): print('Invalid mesh folder provided\nExiting now') exit(1) else: if args.outputdir is None: output_dir = os.path.dirname(args.blenderfile) print('\nno valid output directory: using ' + output_dir + ' as destination folder') else: output_dir = check_output_dir(args.outputdir) # Set the parameters and bash command for each script if(args.scriptfile == 'normalize_meshes.py'): cmd = (script_path + ' -i ' + args.inputmeshdir + ' -s ' + str(args.scale) + ' -o ' + output_dir) elif(args.scriptfile == 'io_export_collision.py'): cmd = (args.blenderdir + '/blender --background -P ' + script_path + ' -- ' + args.inputmeshdir + ' ' + str(args.ratio) + ' ' + str(args.threshold) + ' ' + output_dir) elif(args.scriptfile == 'io_export_visual.py'): if(args.blenderfile is None or not os.path.isfile(args.blenderfile)): print('invalid blender file provided\nExiting now') exit(1) if(args.outputfilename is None): basename = os.path.basename(args.blenderfile) print('no name specified for output material file. unsing: ' + basename) else: basename = os.path.basename(args.outputfilename) if(basename.rfind('.') != -1): basename = basename[0:basename.rfind('.')] print('exporting material to ' + basename + '.material') cmd = (os.path.join(args.blenderdir, 'blender') + ' ' + args.blenderfile + ' -P ' + script_path + ' -- ' + output_dir + ' ' + basename) elif(args.scriptfile == 'io_export_ogre.py'): cmd = ((os.path.join(args.blenderdir, 'blender')) + ' -P ' + script_path + ' -- ' + args.inputmeshdir + ' ' + output_dir) clean = True os.system(cmd) # If ogre exporter called # Remove files left behind by the OGRE exporter if clean is True: file_list = sorted(os.listdir(output_dir)) for file in file_list: if file.endswith('.mesh.xml'): print('removing ' + file) os.remove(os.path.join(output_dir, file))
LCAS/spqrel_tools
ros_ws/src/naoqi_bridge/naoqi_tools/scripts/run_blender_script.py
Python
mit
5,418
import torch import torch.nn.functional as F from .abstract_metrics import AverageMetric from ..registry import register_metric class Accuracy(AverageMetric): """ Computes the accuracy over predictions Args: None Returns: An accuracy metric that can maintain its own internal state. Inputs: y_pred (torch.FloatTensor): A 2D Float Tensor with the predicted probabilites for each class. y_true (torch.LongTensor): A 1D torch LongTensor of the correct classes Outputs: A scalar tensor equal to the accuracy of the y_pred """ def score(self, y_pred, y_true): # Expect output and target to be B x 1 or B x C or target can be # B (with ints from 0 to C-1) assert y_pred.dim() == 2, "y_pred should be a 2-dimensional tensor" total = y_true.size(0) # Turn it into a 1d class encoding if y_true.dim() == 2: if y_true.size(1) > 1: raise NotImplementedError( "Multiclass with 2d targets is not impelemented yet") y_true = y_true.squeeze(1).long() # Change the y_pred to have two cols if it only has 1 if y_pred.size(1) == 1: # Want to consider the 0.5 case y_pred = (y_pred >= 0.5).float() y_pred = torch.cat([1 - y_pred, y_pred], dim=1) # Compute the accuracy _, predicted = torch.max(y_pred, 1) correct = (predicted == y_true).float().sum(0) return (correct / total) * 100. class AccuracyWithLogits(Accuracy): """An accuracy metric that takes as input the logits. See `Accuracy` for more details. """ def score(self, y_pred, y_true): if y_pred.dim() == 2 and y_pred.size(1) > 1: y_pred = F.softmax(y_pred, dim=1) else: y_pred = torch.sigmoid(y_pred) return super().score(y_pred, y_true) class TopKAccuracy(Accuracy): """Computes the precision@k for the specified values of k Args: k (int): The k to calculate precision@k (topk accuracy) Returns: A TopKAccuracy metric that can maintain its own internal state. Inputs: y_pred (torch.FloatTensor) A 2D Float Tensor with the predicted probabilites for each class. y_true (torch.LongTensor) A 1D torch LongTensor of the correct classes Outputs: A scalar tensor equal to the topk accuracy of the y_pred """ def __init__(self, k=3): super().__init__() self.k = k def score(self, y_pred, y_true): assert y_true.dim() == y_pred.dim() - 1 == 1 channel_dim = 1 batch_size = y_true.size(0) # Check to see if there's only 1 channel (then its binary # classification) if y_pred.size(channel_dim) == 1: y_pred = y_pred.squeeze(channel_dim) # B x ... # 2 x B x ... -> B x 2 x ... y_pred = y_pred.stack([1 - y_pred, y_pred]).t() # Get the indicies of the topk along the channel dim _, pred = y_pred.topk(self.k, channel_dim, True, True) # B x k x ... pred = pred.t() # k x B x ... # target: B -> 1 x B -> k x B x ... correct = pred.eq(y_true.view(1, -1).expand_as(pred)) correct_k = correct[:self.k].view(-1).float().sum(0) # Accumulate results return 100. * correct_k / batch_size accuracy = Accuracy() accuracy_with_logits = AccuracyWithLogits() top2_accuracy = TopKAccuracy(2) top3_accuracy = TopKAccuracy(3) top5_accuracy = TopKAccuracy(5) register_metric('accuracy', accuracy) register_metric('accuracy_with_logits', accuracy_with_logits) register_metric('top2_accuracy', top2_accuracy) register_metric('top3_accuracy', top3_accuracy) register_metric('top5_accuracy', top5_accuracy)
abhmul/PyJet
pyjet/metrics/accuracy_metrics.py
Python
mit
3,831
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 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, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ Template file used by ExpGenerator to generate the actual permutations.py file by replacing $XXXXXXXX tokens with desired values. This permutations.py file was generated by: '/Users/Chetan/Dropbox/Development/nupic/nupic/frameworks/opf/exp_generator/ExpGenerator.pyc' """ import os from nupic.swarming.permutationhelpers import * # The name of the field being predicted. Any allowed permutation MUST contain # the prediction field. # (generated from PREDICTION_FIELD) predictedField = 'y' permutations = { 'aggregationInfo': { 'days': 0, 'fields': [], 'hours': 0, 'microseconds': 0, 'milliseconds': 0, 'minutes': 0, 'months': 0, 'seconds': 0, 'weeks': 0, 'years': 0}, 'modelParams': { 'sensorParams': { 'encoders': { u'y': PermuteEncoder(maxval=1.34, fieldName='y', w=21, clipInput=True, minval=0.39, encoderClass='ScalarEncoder', n=PermuteInt(22, 521), ), '_classifierInput': dict(maxval=1.34, classifierOnly=True, clipInput=True, minval=0.39, n=PermuteInt(28, 521), fieldname='y', w=21, type='ScalarEncoder', ), }, }, 'spParams': { 'synPermInactiveDec': PermuteFloat(0.0003, 0.1), }, 'tpParams': { 'activationThreshold': PermuteInt(12, 16), 'minThreshold': PermuteInt(9, 12), 'pamLength': PermuteInt(1, 5), }, 'clParams': { 'alpha': PermuteFloat(0.0001, 0.1), }, } } # Fields selected for final hypersearch report; # NOTE: These values are used as regular expressions by RunPermutations.py's # report generator # (fieldname values generated from PERM_PREDICTED_FIELD_NAME) report = [ '.*y.*', ] # Permutation optimization setting: either minimize or maximize metric # used by RunPermutations. # NOTE: The value is used as a regular expressions by RunPermutations.py's # report generator # (generated from minimize = "multiStepBestPredictions:multiStep:errorMetric='nrmse':steps=\[1\]:window=1000000:field=y") minimize = "multiStepBestPredictions:multiStep:errorMetric='nrmse':steps=\[1\]:window=1000000:field=y" minParticlesPerSwarm = 5 inputPredictedField = 'auto' maxModels = 200 def permutationFilter(perm): """ This function can be used to selectively filter out specific permutation combinations. It is called by RunPermutations for every possible permutation of the variables in the permutations dict. It should return True for valid a combination of permutation values and False for an invalid one. Parameters: --------------------------------------------------------- perm: dict of one possible combination of name:value pairs chosen from permutations. """ # An example of how to use this #if perm['__consumption_encoder']['maxval'] > 300: # return False; # return True
akhilaananthram/nupic.research
sequence_prediction/mackey_glass/swarm/permutations.py
Python
gpl-3.0
3,797
#!/usr/bin/env python3 # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import pbr.version import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../../playbooks/inventory/')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'openstackdocstheme', 'sphinx.ext.autodoc', 'sphinx.ext.extlinks', 'sphinxmark' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. author = 'OpenStack-Ansible Contributors' category = 'Miscellaneous' copyright = '2014-2017, OpenStack-Ansible Contributors' description = 'OpenStack-Ansible deploys OpenStack environments using Ansible.' project = 'OpenStack-Ansible' target_name = 'openstack-ansible' title = 'OpenStack-Ansible Documentation' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version_info = pbr.version.VersionInfo(target_name) # The full version, including alpha/beta/rc tags. release = version_info.version_string_with_vcs() # The short X.Y version. version = version_info.canonical_version_string() # openstackdocstheme options repository_name = 'openstack/' + target_name bug_project = project.lower() bug_tag = '' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'openstackdocs' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%Y-%m-%d %H:%M' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = target_name + '-docs' # If true, publish source files html_copy_source = False # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, target_name + '.tex', title, author, 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, target_name, title, [author], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, target_name, title, author, project, description, category), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # -- Options for PDF output -------------------------------------------------- pdf_documents = [ (master_doc, target_name, title, author) ] # Used for the developer documentation latest_tag = os.popen('git describe --abbrev=0 --tags').read().strip('\n') # Used for the upgrade documentation previous_release_branch_name = 'ocata' current_release_branch_name = 'pike' # dev docs have no branch specified on master; for stable braches it's "/branch/" watermark = os.popen("git branch --contains $(git rev-parse HEAD) | awk -F/ '/stable/ {print $2}'").read().strip(' \n\t').capitalize() if watermark == "": watermark = "Pre-release" deploy_branch_link_name = "latest" dev_branch_link_name = "" current_release_git_branch_name = "master" else: deploy_branch_link_name = current_release_branch_name dev_branch_link_name = "{}/".format(current_release_branch_name) current_release_branch_name = watermark current_release_git_branch_name = 'stable/' + current_release_branch_name previous_release_capital_name = previous_release_branch_name.upper() previous_release_formal_name = previous_release_branch_name.capitalize() current_release_capital_name = current_release_branch_name.upper() current_release_formal_name = current_release_branch_name.capitalize() upgrade_backup_dir = "``/etc/openstack_deploy."+previous_release_capital_name+"``" # Used to reference the deploy guide deploy_guide_prefix = "http://docs.openstack.org/project-deploy-guide/openstack-ansible/{}/%s".format(deploy_branch_link_name) dev_docs_prefix = "http://docs.openstack.org/developer/openstack-ansible/{}%s".format(dev_branch_link_name) rst_epilog = """ .. |previous_release_branch_name| replace:: %s .. |current_release_branch_name| replace:: %s .. |current_release_git_branch_name| replace:: %s .. |previous_release_capital_name| replace:: %s .. |previous_release_formal_name| replace:: %s .. |current_release_capital_name| replace:: %s .. |current_release_formal_name| replace:: %s .. |upgrade_backup_dir| replace:: %s .. |latest_tag| replace:: %s """ % (previous_release_branch_name, current_release_branch_name, current_release_git_branch_name, previous_release_capital_name, previous_release_formal_name, current_release_capital_name, current_release_formal_name, upgrade_backup_dir, latest_tag) extlinks = {'deploy_guide': (deploy_guide_prefix, ''), 'dev_docs': (dev_docs_prefix, '') } # -- Options for sphinxmark ----------------------------------------------- sphinxmark_enable = True sphinxmark_div = 'docs-body' sphinxmark_image = 'text' sphinxmark_text = watermark sphinxmark_text_color = (128, 128, 128) sphinxmark_text_size = 70
cloudnull/os-ansible-deployment
doc/source/conf.py
Python
apache-2.0
12,114
# Copyright 2017-present Adtran, 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. from voltha.extensions.alarms.adapter_alarms import AlarmBase from voltha.protos.events_pb2 import AlarmEventType, AlarmEventSeverity, AlarmEventCategory class OnuActiveAlarm(AlarmBase): def __init__(self, alarm_mgr, device_id, pon_id, onu_serial_number, reg_id, olt_serial_number, ipv4_address=None, onu_id=None, datapath_id=None): super(OnuActiveAlarm, self).__init__(alarm_mgr, object_type='ONU', alarm='ONU_ACTIVATED', alarm_category=AlarmEventCategory.PON, resource_id=pon_id, alarm_type=AlarmEventType.EQUIPMENT, alarm_severity=AlarmEventSeverity.CRITICAL) self._pon_id = pon_id self._onu_id = onu_id self._onu_serial_number = onu_serial_number self._device_id = device_id self._olt_serial_number = olt_serial_number self._host = ipv4_address self._reg_id = reg_id self._datapath_id = datapath_id def get_context_data(self): data = { 'pon_id': self._pon_id, 'onu_id': self._onu_id, 'serial_number': self._onu_serial_number, 'olt_serial_number': self._olt_serial_number, 'device_id': self._device_id, 'registration_id': self._reg_id, 'datapath_id': self._datapath_id } if self._host is not None: data['host'] = self._host return data def clear_alarm(self): raise NotImplementedError('ONU Active Alarms are auto-clear')
opencord/voltha
voltha/extensions/alarms/onu/onu_active_alarm.py
Python
apache-2.0
2,273
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings from opaque_keys.edx.django.models import CourseKeyField class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('credo_modules', '0001_initial'), ] operations = [ migrations.CreateModel( name='CredoStudentProperties', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('course_id', CourseKeyField(db_index=True, max_length=255, null=True, blank=True)), ('name', models.CharField(max_length=255, db_index=True)), ('value', models.CharField(max_length=255)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('user', 'course_id', 'name'), 'db_table': 'credo_student_properties', }, ), ]
CredoReference/edx-platform
common/djangoapps/credo_modules/migrations/0002_credostudentproperties.py
Python
agpl-3.0
1,101
#!/usr/bin/env python3 # -*- mode:python; tab-width:4; c-basic-offset:4; intent-tabs-mode:nil; -*- # ex: filetype=python tabstop=4 softtabstop=4 shiftwidth=4 expandtab autoindent smartindent # # Universal Password Changer (UPwdChg) # Copyright (C) 2014-2018 Cedric Dufour <http://cedric.dufour.name> # Author: Cedric Dufour <http://cedric.dufour.name> # # The Universal Password Changer (UPwdChg) 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, Version 3. # # The Universal Password Changer (UPwdChg) 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. # # SPDX-License-Identifier: GPL-3.0 # License-Filename: LICENSE/GPL-3.0.txt # #------------------------------------------------------------------------------ # DEPENDENCIES #------------------------------------------------------------------------------ # UPwdChg from UPwdChg import \ TokenReader # Standard import unittest as UT import sys #------------------------------------------------------------------------------ # CLASSES #------------------------------------------------------------------------------ class testTokenReader_ReadToken(UT.TestCase): def setUp(self): self.oToken = TokenReader() def testPasswordNonceRequest(self): self.oToken.config('./resources/backend-private.pem', './resources/frontend-public.pem') self.assertEqual(self.oToken.readToken('./tmp/password-nonce-request.token'), 0) def testPasswordChange(self): self.oToken.config('./resources/backend-private.pem', './resources/frontend-public.pem') self.assertEqual(self.oToken.readToken('./tmp/password-change.token'), 0) def testPasswordReset(self): self.oToken.config('./resources/backend-private.pem', './resources/frontend-public.pem') self.assertEqual(self.oToken.readToken('./tmp/password-reset.token'), 0) def testPasswordNonce(self): self.oToken.config('./resources/frontend-private.pem', './resources/backend-public.pem') self.assertEqual(self.oToken.readToken('./tmp/password-nonce.token'), 0) class testTokenReader_PasswordNonceRequest(UT.TestCase): def setUp(self): self.oToken = TokenReader() self.oToken.config('./resources/backend-private.pem', './resources/frontend-public.pem') if(self.oToken.readToken('./tmp/password-nonce-request.token')): self.skipTest('Failed to read token') def testType(self): self.assertIn('type', self.oToken.keys()) self.assertEqual(self.oToken['type'], 'password-nonce-request') def testTimestamp(self): self.assertIn('timestamp', self.oToken.keys()) self.assertRegex(self.oToken['timestamp'], '^20[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]Z$') def testUsername(self): self.assertIn('username', self.oToken.keys()) self.assertEqual(self.oToken['username'], 'test-Benützername') class testTokenReader_PasswordChange(UT.TestCase): def setUp(self): self.oToken = TokenReader() self.oToken.config('./resources/backend-private.pem', './resources/frontend-public.pem') if(self.oToken.readToken('./tmp/password-change.token')): self.skipTest('Failed to read token') def testType(self): self.assertIn('type', self.oToken.keys()) self.assertEqual(self.oToken['type'], 'password-change') def testTimestamp(self): self.assertIn('timestamp', self.oToken.keys()) self.assertRegex(self.oToken['timestamp'], '^20[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]Z$') def testUsername(self): self.assertIn('username', self.oToken.keys()) self.assertEqual(self.oToken['username'], 'test-Benützername') def testPasswordNew(self): self.assertIn('password-new', self.oToken.keys()) self.assertEqual(self.oToken['password-new'], 'test-Paßw0rt_new') def testPasswordOld(self): self.assertIn('password-old', self.oToken.keys()) self.assertEqual(self.oToken['password-old'], 'test-Paßw0rt_old') def testPasswordNonce(self): self.assertIn('password-nonce', self.oToken.keys()) self.assertEqual(self.oToken['password-nonce'], 'test-Paßw0rt_nonce') class testTokenReader_PasswordReset(UT.TestCase): def setUp(self): self.oToken = TokenReader() self.oToken.config('./resources/backend-private.pem', './resources/frontend-public.pem') if(self.oToken.readToken('./tmp/password-reset.token')): self.skipTest('Failed to read token') def testType(self): self.assertIn('type', self.oToken.keys()) self.assertEqual(self.oToken['type'], 'password-reset') def testTimestamp(self): self.assertIn('timestamp', self.oToken.keys()) self.assertRegex(self.oToken['timestamp'], '^20[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]Z$') def testUsername(self): self.assertIn('username', self.oToken.keys()) self.assertEqual(self.oToken['username'], 'test-Benützername') def testPasswordNew(self): self.assertIn('password-new', self.oToken.keys()) self.assertEqual(self.oToken['password-new'], 'test-Paßw0rt_new') def testPasswordNonce(self): self.assertIn('password-nonce', self.oToken.keys()) self.assertEqual(self.oToken['password-nonce'], 'test-Paßw0rt_nonce') class testTokenReader_PasswordNonce(UT.TestCase): def setUp(self): self.oToken = TokenReader() self.oToken.config('./resources/frontend-private.pem', './resources/backend-public.pem') if(self.oToken.readToken('./tmp/password-nonce.token')): self.skipTest('Failed to read token') def testType(self): self.assertIn('type', self.oToken.keys()) self.assertEqual(self.oToken['type'], 'password-nonce') def testTimestamp(self): self.assertIn('timestamp', self.oToken.keys()) self.assertRegex(self.oToken['timestamp'], '^20[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]Z$') def testExpiration(self): self.assertIn('expiration', self.oToken.keys()) self.assertRegex(self.oToken['expiration'], '^20[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]Z$') def testUsername(self): self.assertIn('username', self.oToken.keys()) self.assertEqual(self.oToken['username'], 'test-Benützername') def testPasswordNonceId(self): self.assertIn('password-nonce-id', self.oToken.keys()) self.assertEqual(self.oToken['password-nonce-id'], 'test') def testPasswordNonceSecret(self): self.assertIn('password-nonce-secret', self.oToken.keys()) #------------------------------------------------------------------------------ # MAIN #------------------------------------------------------------------------------ if __name__ == '__main__': #UT.main() oTestSuite = UT.TestSuite() oTestSuite.addTest(UT.makeSuite(testTokenReader_ReadToken)) oTestSuite.addTest(UT.makeSuite(testTokenReader_PasswordNonceRequest)) oTestSuite.addTest(UT.makeSuite(testTokenReader_PasswordChange)) oTestSuite.addTest(UT.makeSuite(testTokenReader_PasswordReset)) oTestSuite.addTest(UT.makeSuite(testTokenReader_PasswordNonce)) oTestResult = UT.TextTestRunner(verbosity=2).run(oTestSuite) sys.exit(0 if oTestResult.wasSuccessful() else 1)
alex-dot/upwdchg
tests/python-tokenreader-test.py
Python
gpl-3.0
7,822
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Chinmaya Pancholi <chinmayapancholi13@gmail.com> # Copyright (C) 2017 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """Scikit learn interface for :class:`~gensim.models.atmodel.AuthorTopicModel`. Follows scikit-learn API conventions to facilitate using gensim along with scikit-learn. Examples -------- .. sourcecode:: pycon >>> from gensim.test.utils import common_dictionary, common_corpus >>> from gensim.sklearn_api.atmodel import AuthorTopicTransformer >>> >>> # Pass a mapping from authors to the documents they contributed to. >>> author2doc = { ... 'john': [0, 1, 2, 3, 4, 5, 6], ... 'jane': [2, 3, 4, 5, 6, 7, 8], ... 'jack': [0, 2, 4, 6, 8] ... } >>> >>> # Lets use the model to discover 2 different topics. >>> model = AuthorTopicTransformer(id2word=common_dictionary, author2doc=author2doc, num_topics=2, passes=100) >>> >>> # In which of those 2 topics does jack mostly contribute to? >>> topic_dist = model.fit(common_corpus).transform('jack') """ import numpy as np from sklearn.base import TransformerMixin, BaseEstimator from sklearn.exceptions import NotFittedError from gensim import models from gensim import matutils class AuthorTopicTransformer(TransformerMixin, BaseEstimator): """Base Author Topic module, wraps :class:`~gensim.models.atmodel.AuthorTopicModel`. The model's internal workings are heavily based on `"The Author-Topic Model for Authors and Documents", Osen-Zvi et. al 2004 <https://mimno.infosci.cornell.edu/info6150/readings/398.pdf>`_. """ def __init__(self, num_topics=100, id2word=None, author2doc=None, doc2author=None, chunksize=2000, passes=1, iterations=50, decay=0.5, offset=1.0, alpha='symmetric', eta='symmetric', update_every=1, eval_every=10, gamma_threshold=0.001, serialized=False, serialization_path=None, minimum_probability=0.01, random_state=None): """ Parameters ---------- num_topics : int, optional Number of requested latent topics to be extracted from the training corpus. id2word : :class:`~gensim.corpora.dictionary.Dictionary`, optional Mapping from a words' ID to the word itself. Used to determine the vocabulary size, as well as for debugging and topic printing. author2doc : dict of (str, list of int), optional Maps an authors name to a list of document IDs where has has contributed. Either `author2doc` or `doc2author` **must be supplied**. doc2author : dict of (int, list of str) Maps a document (using its ID) to a list of author names that contributed to it. Either `author2doc` or `doc2author` **must be supplied**. chunksize : int, optional Number of documents to be processed by the model in each mini-batch. passes : int, optional Number of times the model can make a pass over the corpus during training. iterations : int, optional Maximum number of times the model before convergence during the M step of the EM algorithm. decay : float, optional A number between (0.5, 1] to weight what percentage of the previous lambda value is forgotten when each new document is examined. Corresponds to Kappa from `"The Author-Topic Model for Authors and Documents", Osen-Zvi et. al 2004 <https://mimno.infosci.cornell.edu/info6150/readings/398.pdf>`_. offset : float, optional Hyper-parameter that controls how much we will slow down the first steps the first few iterations. Corresponds to Tau_0 from `"The Author-Topic Model for Authors and Documents", Osen-Zvi et. al 2004 <https://mimno.infosci.cornell.edu/info6150/readings/398.pdf>`_. alpha : {np.ndarray, str}, optional Can be set to an 1D array of length equal to the number of expected topics that expresses our a-priori belief for the each topics' probability. Alternatively default prior selecting strategies can be employed by supplying a string: * 'asymmetric': Uses a fixed normalized asymmetric prior of `1.0 / topicno`. * 'auto': Learns an asymmetric prior from the corpus. eta : {float, np.array, str}, optional A-priori belief on word probability, this can be: * scalar for a symmetric prior over topic/word probability, * vector of length num_words to denote an asymmetric user defined probability for each word, * matrix of shape (num_topics, num_words) to assign a probability for each word-topic combination, * the string 'auto' to learn the asymmetric prior from the data. update_every : int, optional Number of mini-batches between each model update. eval_every : int, optional Number of updates between two log perplexity estimates. Set to None to disable perplexity estimation. gamma_threshold : float, optional Minimum change in the value of the gamma parameters to continue iterating. serialized : bool, optional Indicates whether the input corpora to the model are simple in-memory lists (`serialized = False`) or saved to the hard-drive (`serialized = True`). Note that this behaviour is quite different from other Gensim models. If your data is too large to fit in to memory, use this functionality. serialization_path : str, optional Path to file that used for storing the serialized object, **must be supplied if `serialized = True`**. An existing file *cannot* be overwritten, either delete the old file or choose a different name. minimum_probability : float, optional Topics with a probability lower than this threshold will be filtered out. random_state : {np.random.RandomState, int}, optional Either a randomState object or a seed to generate one. Useful for reproducibility. """ self.gensim_model = None self.num_topics = num_topics self.id2word = id2word self.author2doc = author2doc self.doc2author = doc2author self.chunksize = chunksize self.passes = passes self.iterations = iterations self.decay = decay self.offset = offset self.alpha = alpha self.eta = eta self.update_every = update_every self.eval_every = eval_every self.gamma_threshold = gamma_threshold self.serialized = serialized self.serialization_path = serialization_path self.minimum_probability = minimum_probability self.random_state = random_state def fit(self, X, y=None): """Fit the model according to the given training data. Parameters ---------- X : iterable of list of (int, number) Sequence of documents in BoW format. Returns ------- :class:`~gensim.sklearn_api.atmodel.AuthorTopicTransformer` The trained model. """ self.gensim_model = models.AuthorTopicModel( corpus=X, num_topics=self.num_topics, id2word=self.id2word, author2doc=self.author2doc, doc2author=self.doc2author, chunksize=self.chunksize, passes=self.passes, iterations=self.iterations, decay=self.decay, offset=self.offset, alpha=self.alpha, eta=self.eta, update_every=self.update_every, eval_every=self.eval_every, gamma_threshold=self.gamma_threshold, serialized=self.serialized, serialization_path=self.serialization_path, minimum_probability=self.minimum_probability, random_state=self.random_state ) return self def transform(self, author_names): """Infer the topic probabilities for each author. Parameters ---------- author_names : {iterable of str, str} Author name or sequence of author names whose topics will be identified. Returns ------- numpy.ndarray Topic distribution for each input author. """ if self.gensim_model is None: raise NotFittedError( "This model has not been fitted yet. Call 'fit' with appropriate arguments before using this method." ) # The input as array of arrays if not isinstance(author_names, list): author_names = [author_names] # returning dense representation for compatibility with sklearn # but we should go back to sparse representation in the future topics = [matutils.sparse2full(self.gensim_model[author_name], self.num_topics) for author_name in author_names] return np.reshape(np.array(topics), (len(author_names), self.num_topics)) def partial_fit(self, X, author2doc=None, doc2author=None): """Train model over a potentially incomplete set of documents. This method can be used in two ways: * On an unfitted model in which case the model is initialized and trained on `X`. * On an already fitted model in which case the model is **updated** by `X`. Parameters ---------- X : iterable of list of (int, number) Sequence of documents in BoW format. author2doc : dict of (str, list of int), optional Maps an authors name to a list of document IDs where has has contributed. Either `author2doc` or `doc2author` **must be supplied**. doc2author : dict of (int, list of str) Maps a document (using its ID) to a list of author names that contributed to it. Either `author2doc` or `doc2author` **must be supplied**. Returns ------- :class:`~gensim.sklearn_api.atmodel.AuthorTopicTransformer` The trained model. """ if self.gensim_model is None: self.gensim_model = models.AuthorTopicModel( corpus=X, num_topics=self.num_topics, id2word=self.id2word, author2doc=self.author2doc, doc2author=self.doc2author, chunksize=self.chunksize, passes=self.passes, iterations=self.iterations, decay=self.decay, offset=self.offset, alpha=self.alpha, eta=self.eta, update_every=self.update_every, eval_every=self.eval_every, gamma_threshold=self.gamma_threshold, serialized=self.serialized, serialization_path=self.serialization_path, minimum_probability=self.minimum_probability, random_state=self.random_state ) self.gensim_model.update(corpus=X, author2doc=author2doc, doc2author=doc2author) return self
midnightradio/gensim
gensim/sklearn_api/atmodel.py
Python
gpl-3.0
10,965
''' ''' from __future__ import print_function import sys from collections import OrderedDict import warnings # from contextlib import contextmanager import tensorflow as tf from tfclusterdefs import JobType, DevType __all__ = ('JobType', 'DevType', 'TFClusterManagerFacade',) class TFClusterManagerFacade(object): ''' Setting config on the server instantiation and then re-using this same config for sesssions is very important. This functionality is wrapped in TFClusterManagerFacade. "My" indicates my task and whatever can be grouped under my task. Each task has a one-to-one correspondence with a worker/parameter server. When the task is a worker, this worker could have multiple devices (typically GPUs) associated with it. ''' def __init__(self, cluster_parser): ''' :param cluster_parser: Cluster parser implementing ClusterParser class. :type cluster_parser: ClusterParser ''' num_tasks_per_host = cluster_parser.num_tasks_per_host hostnames = cluster_parser.hostnames num_parameter_servers = cluster_parser.num_parameter_servers my_proc_id = cluster_parser.my_proc_id starting_port = cluster_parser.starting_port num_processes = sum(num_tasks_per_host) # tuples of (str(Hostname:Port), JobName, TaskID) for each process proc_info = [[None, None, None] for _ in range(num_processes)] # Assign Port# to each process according to Hostname # Note: if there are multiple processes on the same hostname, # each one needs it's own port number, hence the variable name # starting_port) pid = 0 first_pid_per_host = {} # Reverse-Lookup map for cnt, hostname in zip(num_tasks_per_host, hostnames): first_pid_per_host[hostname] = pid for i in range(cnt): proc_info[pid][0] = "{}:{}".format( hostname, starting_port + i) pid += 1 # Assign PSs to different physical hosts # NOTE: this code requires that the num_parameter_servers be less than # or equalto the number of indificial physical nodes ps_strings = [] for ps_id in range(num_parameter_servers): pid = first_pid_per_host[hostnames[ps_id]] ps_strings.append(proc_info[pid][0]) proc_info[pid][1] = JobType.ps proc_info[pid][2] = ps_id # Assign workers to the remaining open spots wk_id = 0 wk_strings = [] for info in proc_info: if info[1] is None: # It's not a ps wk_strings.append(info[0]) info[1] = JobType.worker info[2] = wk_id wk_id += 1 # Each processor: Grab your Job/TaskID self._myhost = proc_info[my_proc_id][0].split(':')[0] self._myjobtype = proc_info[my_proc_id][1] self._mytask_id = proc_info[my_proc_id][2] # get my parameter server (assuming one ps per node) for info in proc_info: ps_host = info[0].split(':')[0] if info[1] == JobType.ps and ps_host == self._myhost: self._myps_id = info[2] break else: # didn't break self._myps_id = 0 # assuming just one parameter server with id 0 # Retain the overall cluster definition. self._cspec_dict = {JobType.worker: wk_strings, JobType.ps: ps_strings} @property def is_chief(self): task_id = self.mytask_id # Worker with task id 0 is chief is_chief = (task_id == 0) and (self.myjobtype == JobType.worker) return is_chief @property def myhost(self): return self._myhost @property def myjobtype(self): return self._myjobtype @property def mytask_id(self): return self._mytask_id @property def mydevtask(self): task_id = self.mytask_id jobtype = self.myjobtype mydevtask = tf.DeviceSpec(job=jobtype, task=task_id) return mydevtask @property def clusterspec_dict(self): return self._cspec_dict @property def num_workers(self): # cspec = self.get_cluster_spec() # num_workers = cspec.num_tasks(JobType.worker) num_workers = len(self.clusterspec_dict.get(JobType.worker, [])) return num_workers @property def num_ps(self): # num_ps = cluster_spec.num_tasks(JobType.ps) num_ps = len(self.clusterspec_dict.get(JobType.ps, [])) return num_ps def get_cluster_spec(self): return tf.train.ClusterSpec(self.clusterspec_dict) def get_server(self, config=None, protocol=None, start=True): '''In distributed environment with multi-GPUs per node, set config gpus option to allow growth. config.gpu_options.allow_growth = True ''' if not config.gpu_options.allow_growth: warnings.warn('Set config.gpu_options.allow_growth=True ' 'to avoid allocation errors on Multi-GPU nodes', UserWarning) cspec = self.get_cluster_spec() server = tf.train.Server(cspec, job_name=self.myjobtype, task_index=self.mytask_id, config=config, protocol=protocol, start=start) return server # @contextmanager def get_session(self, server): '''TF session getter. Works as context manager directly as well.''' config = server.server_def.default_session_config # with tf.Session(server.target, config=config) as sess: # yield sess # force usage of context manager return tf.Session(server.target, config=config) def _signal_chief(self, server, sess=None): task_id = self.mytask_id # assuming chief is worker task id 0. chief_devtask = tf.DeviceSpec(job=JobType.worker, task=0) queue = create_done_queue_task( chief_devtask, shared_name='done_queue_worker_{}'.format(task_id)) eqop = queue.enqueue(1) if sess is None: # config = server.server_def.default_session_config # with tf.Session(server.target, config=config) as sess: with self.get_session(server) as sess: sess.run(eqop) # print('SIGNAL TO CHIEF FROM WORKER {}'.format(task_id)) else: sess.run(eqop) def join(self, server, sess=None, exit_flag=True): # server.join() task_id = self.mytask_id jobtype = self.myjobtype if jobtype == JobType.worker: self._signal_chief(server, sess) # mydevtask = tf.DeviceSpec(job=jobtype, task=task_id) mydevtask = self.mydevtask queue = create_done_queue_task(mydevtask) # RECEIVE SIGNAL FROM CHIEF. if sess is None: # config = server.server_def.default_session_config # with tf.Session(server.target, config=config) as sess: with self.get_session(server) as sess: sess.run(queue.dequeue()) else: sess.run(queue.dequeue()) print("{} {} RECEIVED DONE. QUITTING".format(jobtype, task_id), file=sys.stderr) if exit_flag: sys.exit(0) def stop_chief(self, server, sess=None, stop_workers=True): num_workers = self.num_workers chief_devtask = tf.DeviceSpec(job=JobType.worker, task=0) queue_from_workers = [create_done_queue_task( chief_devtask, shared_name='done_queue_worker_{}'.format(ii)) for ii in range(1, num_workers)] sess = self.get_session(server) if sess is None else sess # MAKE SURE ALL THE WORKERS ARE DONE BEFORE STOPPING # for iw, qfw in enumerate(queue_from_workers): for qfw in queue_from_workers: # RECEIVE SIGNAL FROM WORKERS. # if sess is None: # with self.get_session(server) as sess: # sess.run(qfw.dequeue()) # else: sess.run(qfw.dequeue()) # print("CHIEF {} RECEIVED DONE FROM WORKER {}. QUITTING" # .format(qfw, iw), file=sys.stderr) # SEND SIGNALS TO EVERYONE ELSE TO QUIT num_ps = self.num_ps num_workers = self.num_workers enq_ops = [] ps_devtasklist = [tf.DeviceSpec(job=JobType.ps, task=ii) for ii in range(num_ps)] wrk_devtasklist = [tf.DeviceSpec(job=JobType.worker, task=ii) for ii in range(1, num_workers)] # STOP WORKERS FIRST BEFORE PS if stop_workers: devtasklist = wrk_devtasklist + ps_devtasklist else: devtasklist = ps_devtasklist for q in create_done_queues_chief(devtasklist): qop = q.enqueue(1) enq_ops.append(qop) if sess is None: # config = server.server_def.default_session_config # with tf.Session(server.target, config=config) as sess: with self.get_session(server) as sess: for op in enq_ops: sess.run(op) else: for op in enq_ops: sess.run(op) def get_mypsdevice(self): myps = tf.DeviceSpec( job=JobType.ps, task=self._myps_id, device_type=DevType.cpu, device_index=0).to_string() return myps def get_allps_devlist(self): num_ps = self.num_ps ps_devtasklist = [tf.DeviceSpec(job=JobType.ps, task=ii) for ii in range(num_ps)] return ps_devtasklist def get_allworkers_devlist(self, ngpus): '''Current split strategy is if 1 worker on a node then all GPUs are assigned to that worker. If more than 1 worker then 1 GPU per worker. ''' # TODO: GPU TO WORKERS MAPPING STRATEGY # 1 GPU PER WORKER (M == N below) # SPLIT M GPUs PER N WORKERS M > N: M/N GPUs per WORKER # The ngpus per host needs to be done with MPI or somehow sync'd. # Currently assuming all hosts have the same number of GPUs. # workers_list = cluster_spec.job_tasks(JobType.worker) workers_list = self.clusterspec_dict[JobType.worker] workers_nodetask_map = OrderedDict() for itask, worker in enumerate(workers_list): wnode = worker.split(':')[0] # keep the hostname and discard port workers_nodetask_map.setdefault(wnode, []).append(itask) # print('WORKERS_NODETASK_MAP: {}'.format(workers_nodetask_map)) # # DEBUG wgdev_list = [] # TODO: Generalize this as cluster spec split strategy. for itask_list in workers_nodetask_map.values(): ntasks_per_node = len(itask_list) # == number of workers per node if ntasks_per_node > 1: # 1 GPU per worker on a node. 1 WORKER PER CPU-CORE # Worker Tasks within a Node for itask_cnt, itask in enumerate(itask_list): # USE CPUS for extra workers devtype, devid = (DevType.gpu, itask_cnt) \ if itask_cnt < ngpus else \ (DevType.cpu, itask_cnt - ngpus) wgdev = tf.DeviceSpec( job=JobType.worker, task=itask, device_type=devtype, device_index=devid) wgdev_list.append(wgdev) elif ntasks_per_node == 1 and ngpus > 0: # ALL GPUs per worker on a node. 1 WORKER PER CPU-CORE itask = itask_list[0] for idev in range(ngpus): wgdev = tf.DeviceSpec( job=JobType.worker, task=itask, device_type=DevType.gpu, device_index=idev) wgdev_list.append(wgdev) elif ntasks_per_node == 1: itask = itask_list[0] # USE CPUS wgdev = tf.DeviceSpec( job=JobType.worker, task=itask, device_type=DevType.cpu, device_index=0) wgdev_list.append(wgdev) else: continue return wgdev_list def get_mydevlist(self, ngpus): wdev_list = self.get_allworkers_devlist(ngpus) mytask_id = self.mytask_id #: :type wdev: tf.DeviceSpec mywdev_list = [wdev for wdev in wdev_list if wdev.task == mytask_id] return mywdev_list # ============================================================================= # SIGNAL QUEUES: https://github.com/hustcat/tensorflow_examples/blob/master/mnist_distributed/dist_fifo.py @IgnorePep8 # ============================================================================= # def create_done_queue(i, num_workers=1): # """Queue used to signal death for i'th ps shard. Intended to have # all workers enqueue an item onto it to signal doneness.""" # # with tf.device("/job:ps/task:%d" % (i)): # return tf.FIFOQueue(num_workers, tf.int32, # shared_name="done_queue{}".format(i)) # # # def create_done_queues(num_ps): # return [create_done_queue(i) for i in range(num_ps)] # Perhaps implement a READY queue just like DONE queues. def create_done_queue_task(dev, shared_name=None): ''' :param dev: Device spec. :type dev: :class:`tf.DeviceSpec` ''' task_id = dev.task with tf.device(dev): sname = 'done_queue_chief_{}'.format(task_id) \ if shared_name is None else shared_name return tf.FIFOQueue(1, tf.int32, shared_name=sname) def create_done_queues_chief(devlist): ''' :param devlist: List of device specs :class:`tf.DeviceSpec` objects. ''' return [create_done_queue_task(dev) for dev in devlist]
avolkov1/keras_experiments
src/keras_exp/distrib/cluster_mgrs/tfcmgr.py
Python
unlicense
14,072
''' Decide on a JSONField implementation based on available packages. There are two possible options, preferred in the following order: - JSONField from django-jsonfield with django-jsonfield-compat - JSONField from django-mysql (needs MySQL 5.7+) Raises an ImportError if USE_JSONFIELD is True but none of these are installed. Falls back to a simple Django TextField if USE_JSONFIELD is False, however that field will be removed by migration 0002 directly afterwards. ''' import django from django.db import models from django.core.exceptions import ImproperlyConfigured from actstream.settings import USE_JSONFIELD __all__ = ('DataField', ) DataField = models.TextField if USE_JSONFIELD: if django.VERSION >= (3, 1): from django.db.models import JSONField DataField = JSONField else: try: from django_jsonfield_backport.models import JSONField DataField = JSONField except ImportError: raise ImproperlyConfigured( 'You must install django-jsonfield-backport, ' 'if you wish to use a JSONField on your actions ' 'and run Django < 3.1' )
justquick/django-activity-stream
actstream/jsonfield.py
Python
bsd-3-clause
1,189
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-04-23 19:37 ''' Миграция ''' from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): ''' Добавляем опциональные поля ''' dependencies = [ ('lawe', '0006_remove_account_unit'), ] operations = [ migrations.AlterField( model_name='account', name='group', field=models.CharField(blank=True, max_length=200, verbose_name='Основная группа'), ), migrations.AlterField( model_name='account', name='name', field=models.CharField(blank=True, max_length=200, verbose_name='Название'), ), migrations.AlterField( model_name='account', name='subgroup', field=models.CharField(blank=True, max_length=200, verbose_name='Подгруппа'), ), migrations.AlterField( model_name='transaction', name='description', field=models.CharField(blank=True, max_length=200, verbose_name='Описание'), ), ]
DronMDF/laweb
lawe/migrations/0007_auto_20170423_1937.py
Python
apache-2.0
1,029
from urllib3._collections import HTTPHeaderDict class MetaDataHydrator: def hydrate_from_headers(self, metadata_entity, http_input_headers): for k, v in http_input_headers.items(): attr_name = k.replace(MetaDataDescriptor.prefix + '-', '') attr_name = attr_name.lower().replace('-', '_') if hasattr(metadata_entity, attr_name): setattr(metadata_entity, attr_name, v) return metadata_entity def hydrate_from_fields(self, metadata_entity, fields): for k, v in fields.items(): if hasattr(metadata_entity, k): setattr(metadata_entity, k, v) return metadata_entity class MetaDataHTTPHeadersFilter: """ It helps to filter what heders are from scirocco. """ def __init__(self, metadata_descriptor): self.metadata_descriptor = metadata_descriptor self.system_headers = metadata_descriptor.get_all_http_headers() def filter_system(self, http_input_headers): http_headers = HTTPHeaderDict() for k, v in http_input_headers.items(): if k in self.system_headers: http_headers.add(k, v) return http_headers def filter_http(self, http_input_headers): http_headers = HTTPHeaderDict() for k, v in http_input_headers.items(): if k not in self.system_headers: http_headers.add(k, v) return http_headers class MetaDataDescriptor: """ Used to make translates from scirocco metada and HTTP headers format in both directions. """ prefix = 'Scirocco' separator = '-' def __init__(self, metadata_entity): if not isinstance(metadata_entity, MetaData): raise TypeError self.metadata_entity = metadata_entity def _compose_http_header_from_field_name(self, name): parts = list(filter(None, name.split('_'))) filtered_parts = [] for p in parts: p = p.replace('_', '').title() filtered_parts.append(p) filtered_parts.insert(0, self.prefix) header = self.separator.join(filtered_parts) return header def get_all_fields(self): fields = [] for sh in self.metadata_entity.__dict__: if not sh.startswith("__"): fields.append(sh) return fields def get_all_http_headers(self): headers = [] for sh in self.get_all_fields(): headers.append(self._compose_http_header_from_field_name(sh)) return headers def get_http_header_by_field_name(self, name): if hasattr(self.metadata_entity, name): return self._compose_http_header_from_field_name(name) else: raise AttributeError class MetaData: """ Represent Metada of the message. Its analogous to scirocco HTTP Headers. """ def __init__(self): self._node_destination = None self._node_source = None self._id = None self._topic = None self._status = None self._update_time = None self._created_time = None self._scheduled_time = None self._error_time = None self._processed_time = None self._processing_time = None self._tries = None self._payload_type = None @property def node_source(self): return self._node_source @node_source.setter def node_source(self, node_source): self._node_source = node_source @property def node_destination(self): return self._node_destination @node_destination.setter def node_destination(self, node_destination): self._node_destination = node_destination @property def id(self): return self._id @id.setter def id(self, data): self._id = data @property def topic(self): return self._topic @topic.setter def topic(self, data): self._topic = data @property def status(self): return self._status @status.setter def status(self, data): self._status = data @property def update_time(self): return self._update_time @update_time.setter def update_time(self, data): self._update_time = data @property def created_time(self): return self._created_time @created_time.setter def created_time(self, data): self._created_time = data @property def scheduled_time(self): return self._scheduled_time @scheduled_time.setter def scheduled_time(self, data): self._scheduled_time = data @property def error_time(self): return self._error_time @error_time.setter def error_time(self, data): self._error_time = data @property def processed_time(self): return self._processed_time @processed_time.setter def processed_time(self, data): self._processed_time = data @property def processing_time(self): return self._processing_time @processing_time.setter def processing_time(self, data): self._processing_time = data @property def tries(self): return self._tries @tries.setter def tries(self, data): self._tries = data @property def payload_type(self): return self._payload_type @payload_type.setter def payload_type(self, payload_type): self._payload_type = payload_type
eloylp/scirocco-pyclient
sciroccoclient/metadata.py
Python
agpl-3.0
5,508
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('products', '0016_product_default'), ] operations = [ migrations.RemoveField( model_name='collection', name='brands', ), migrations.AddField( model_name='category', name='brands', field=models.ManyToManyField(blank=True, to='products.Brand'), ), ]
vanabo/mattress
src/products/migrations/0017_auto_20170226_2043.py
Python
mit
531
# -*- coding: utf-8 -*- # Generated by Django 1.9a1 on 2015-10-13 09:44 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('application', '0004_auto_20151013_1513'), ] operations = [ migrations.AlterField( model_name='application', name='is_anonymous', field=models.BooleanField(default=False, help_text=b'Valid for complete anonymous apps. Requires admin permission'), ), ]
DheerendraRathor/ldap-oauth2
application/migrations/0005_auto_20151013_1514.py
Python
gpl-3.0
543
""" Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. For example, Consider the following matrix: [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] Given target = 5, return true. Given target = 20, return false. """ class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if len(matrix) < 1 or len(matrix[0]) < 1: return False row, col = len(matrix), len(matrix[0]) i, j = 0, col - 1 while i < row and j >= 0: if target == matrix[i][j]: return True elif target > matrix[i][j]: i += 1 else: j -= 1 return False
dichen001/Go4Jobs
JackChen/divide&conquer/240. Search a 2D Matrix II.py
Python
gpl-3.0
1,045
class Tokenizer: def __init__(self, token, kind,): self.valor = token self.tipo = kind def setValue(self, booleano): self.booleano = booleano
raphaelmendes18/avaliadorDeProposicoesLogicas
avaliadorDeProposicoesLogicas/classes.py
Python
gpl-2.0
154
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.callback.default import CallbackModule as DefaultCallbackModule # noqa from datetime import datetime # noqa class CallbackModule(DefaultCallbackModule): CALLBACK_VERSION = 2.0 CALLBACK_TYPE = 'stdout' CALLBACK_NAME = 'vanko' def __init__(self): super(CallbackModule, self).__init__() display_orig = self._display.display def display(msg, *args, **kwargs): msg = msg.strip() if msg.endswith('***'): stamp = str(datetime.now().replace(microsecond=0)) if self._display.verbosity < 1: stamp = stamp.split()[1] # omit date part msg = '[%s] %s' % (stamp, msg) if msg: display_orig(msg, *args, **kwargs) self._display.display = display @property def _is_verbose(self): return self._display.verbosity > 1 def v2_playbook_on_task_start(self, task, is_conditional): if self._is_verbose or task.action != 'include': super(CallbackModule, self).v2_playbook_on_task_start(task, is_conditional) def v2_runner_on_skipped(self, result): if self._is_verbose: super(CallbackModule, self).v2_runner_on_skipped(result) def v2_runner_item_on_skipped(self, result): if self._is_verbose: super(CallbackModule, self).v2_runner_item_on_skipped(result) def v2_playbook_on_include(self, included_file): if self._is_verbose: super(CallbackModule, self).v2_playbook_on_include(included_file)
ivandeex/dz
ansible/lib/plugins/callback/vanko.py
Python
mit
1,667
from pymc import Model, Normal, Metropolis, MvNormal import numpy as np import pymc as pm from itertools import product from theano.tensor import log def simple_model(): mu = -2.1 tau = 1.3 with Model() as model: x = Normal('x', mu, tau, shape=2, testval=[.1]*2) return model.test_point, model, (mu, tau ** -1) def multidimensional_model(): mu = -2.1 tau = 1.3 with Model() as model: x = Normal('x', mu, tau, shape=(3,2), testval=.1*np.ones((3,2)) ) return model.test_point, model, (mu, tau ** -1) def simple_init(): start, model, moments = simple_model() step = Metropolis(model.vars, np.diag([1.]), model=model) return model, start, step, moments def simple_2model(): mu = -2.1 tau = 1.3 p = .4 with Model() as model: x = pm.Normal('x', mu, tau, testval=.1) logx = pm.Deterministic('logx', log(x)) y = pm.Bernoulli('y', p) return model.test_point, model def mv_simple(): mu = np.array([-.1, .5, 1.1]) p = np.array([ [2., 0, 0], [.05, .1, 0], [1., -0.05, 5.5]]) tau = np.dot(p, p.T) with pm.Model() as model: x = pm.MvNormal('x', pm.constant(mu), pm.constant( tau), shape=3, testval=np.array([.1, 1., .8])) H = tau C = np.linalg.inv(H) return model.test_point, model, (mu, C) def mv_simple_discrete(): d= 2 n = 5 p = np.array([.15,.85]) with pm.Model() as model: x = pm.Multinomial('x', n, pm.constant(p), shape=d, testval=np.array([1,4])) mu = n * p #covariance matrix C = np.zeros((d,d)) for (i, j) in product(range(d), range(d)): if i == j: C[i,i] = n * p[i]*(1-p[i]) else: C[i,j] = -n*p[i]*p[j] return model.test_point, model, (mu, C) def non_normal(n=2): with pm.Model() as model: x = pm.Beta('x', 3, 3, shape=n) return model.test_point, model, (np.tile([.5], n), None) def exponential_beta(n=2): with pm.Model() as model: x = pm.Beta('x', 3, 1, shape=n) y = pm.Exponential('y', 1, shape=n) return model.test_point, model, None
nmmarquez/pymc
pymc3/tests/models.py
Python
apache-2.0
2,189
# sybase/pyodbc.py # Copyright (C) 2005-2018 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: sybase+pyodbc :name: PyODBC :dbapi: pyodbc :connectstring: sybase+pyodbc://<username>:<password>@<dsnname>\ [/<database>] :url: http://pypi.python.org/pypi/pyodbc/ Unicode Support --------------- The pyodbc driver currently supports usage of these Sybase types with Unicode or multibyte strings:: CHAR NCHAR NVARCHAR TEXT VARCHAR Currently *not* supported are:: UNICHAR UNITEXT UNIVARCHAR """ from sqlalchemy.dialects.sybase.base import SybaseDialect,\ SybaseExecutionContext from sqlalchemy.connectors.pyodbc import PyODBCConnector from sqlalchemy import types as sqltypes, processors import decimal class _SybNumeric_pyodbc(sqltypes.Numeric): """Turns Decimals with adjusted() < -6 into floats. It's not yet known how to get decimals with many significant digits or very large adjusted() into Sybase via pyodbc. """ def bind_processor(self, dialect): super_process = super(_SybNumeric_pyodbc, self).\ bind_processor(dialect) def process(value): if self.asdecimal and \ isinstance(value, decimal.Decimal): if value.adjusted() < -6: return processors.to_float(value) if super_process: return super_process(value) else: return value return process class SybaseExecutionContext_pyodbc(SybaseExecutionContext): def set_ddl_autocommit(self, connection, value): if value: connection.autocommit = True else: connection.autocommit = False class SybaseDialect_pyodbc(PyODBCConnector, SybaseDialect): execution_ctx_cls = SybaseExecutionContext_pyodbc colspecs = { sqltypes.Numeric: _SybNumeric_pyodbc, } dialect = SybaseDialect_pyodbc
fernandog/Medusa
ext/sqlalchemy/dialects/sybase/pyodbc.py
Python
gpl-3.0
2,102
# Copyright 2020 DeepMind Technologies Limited. # # 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. """Configuration for Collaborative Cooking: Impassable. Example video: https://youtu.be/yn1uSNymQ_U Players need to collaborate to follow recipes. They are separated by an impassable kitchen counter, so no player can complete the objective alone. The recipe they must follow is for tomato soup: 1. Add three tomatoes to the cooking pot. 2. Wait for the soup to cook (status bar completion). 3. Bring a bowl to the pot and pour the soup from the pot into the bowl. 4. Deliver the bowl of soup at the goal location. This substrate is a pure common interest game. All players share all rewards. Players have a `5 x 5` observation window. """ # pylint: disable=g-line-too-long from meltingpot.python.configs.substrates import collaborative_cooking as base_config def get_config(): """Default config for training on collaborative cooking.""" config = base_config.get_config("impassable") return config
deepmind/meltingpot
meltingpot/python/configs/substrates/collaborative_cooking_impassable.py
Python
apache-2.0
1,514
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals """ FIXME: Proper module docstring """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "Nov 9, 2012" import unittest2 as unittest import os import json from monty.json import MontyDecoder from pymatgen.entries.entry_tools import group_entries_by_structure test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", 'test_files') class FuncTest(unittest.TestCase): def test_group_entries_by_structure(self): with open(os.path.join(test_dir, "TiO2_entries.json"), "r") as f: entries = json.load(f, cls=MontyDecoder) groups = group_entries_by_structure(entries) self.assertEqual(sorted([len(g) for g in groups]), [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 4]) self.assertLess(len(groups), len(entries)) #Make sure no entries are left behind self.assertEqual(sum([len(g) for g in groups]), len(entries)) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
aykol/pymatgen
pymatgen/entries/tests/test_entry_tools.py
Python
mit
1,311
# -*- coding: utf-8 -*- import json import os import random import requests import re import subprocess import string from django import forms from django.shortcuts import render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.core.mail import send_mail from django.views.decorators.csrf import csrf_exempt from django.core.exceptions import PermissionDenied, ObjectDoesNotExist from constance import config from register.models import Registration, Batch, colleges new_message = u"""نشكرك على التسجيل في السحابة الطبية اسم المستخدم: %s كلمة السر: %s رابط السحابة: https://ksauhs-med.com/ آملين أن تجد فيها ما يفيد! """ forgotten_message = u"""هذه معلوماتك الجديدة للدخول إلى السحابة الطبية: اسم المستخدم: %s كلمة السر: %s رابط السحابة: https://ksauhs-med.com/ آملين أن تجد فيها ما يفيد! """ class RegistrationForm(forms.ModelForm): college = forms.CharField(label=u'الكلية', max_length=1, widget=forms.Select(choices=colleges)) number = forms.IntegerField(label=u"الدفعة", widget=forms.Select(choices=[(i, i) for i in range(1, 17)])) def clean(self): cleaned_data = super(RegistrationForm, self).clean() batch_msg = u"الدفعة التي اخترت غير موجودة." if 'college' in cleaned_data and 'number' in cleaned_data: try: Batch.objects.get( college=cleaned_data['college'], number=int(cleaned_data['number'])) except Batch.DoesNotExist: self._errors['college'] = self.error_class([batch_msg]) self._errors['number'] = self.error_class([batch_msg]) del cleaned_data['college'] del cleaned_data['number'] return cleaned_data def save(self): new_registration = super(RegistrationForm, self).save() batch = Batch.objects.get( college=self.cleaned_data['college'], number=int(self.cleaned_data['number']), ) new_registration.group = batch new_registration.save() return new_registration class Meta: model = Registration fields = ['email', 'college', 'number', 'unisersity_id'] widgets = { 'university_id': forms.TextInput(), } class ResetPasswordForm(forms.Form): email = forms.EmailField(label=u'بريدك الجامعي', max_length=100) @csrf_exempt def register(request): if request.method == 'POST': password = generate_password() initial_registration = Registration(password=password) form = RegistrationForm(request.POST, instance=initial_registration) if form.is_valid(): email = form.cleaned_data['email'] if not email.endswith('ksau-hs.edu.sa'): context = {'form': form, 'error_message': 'university_email'} elif Registration.objects.filter(email__iexact=email, is_successful=True): context = {'form': form, 'error_message': u'already_registered'} else: user = email.split('@')[0].lower() registration = form.save() group = str(registration.group) if createuser(user, password, group): registration.is_successful = True registration.save() send_mail(u'حسابك على السحابة الطبية', new_message % (user, password), 'info@ksauhs-med.com', [email], fail_silently=False) return HttpResponseRedirect(reverse('register:thanks')) else: context = {'form': form, 'error_message': 'unknown'} else: context = {'form': form} else: form = RegistrationForm() context = {'form': form} return render(request, 'register/register.html', context) @csrf_exempt def forgotten(request): if request.method == 'POST': form = ResetPasswordForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] if not email.endswith('ksau-hs.edu.sa'): context = {'form': form, 'error_message': 'university_email'} else: try: previous_registration = Registration.objects.get(email__iexact=email, is_successful=True) except ObjectDoesNotExist: previous_registration = None context = {'form': form, 'error_message': 'not_registered'} if previous_registration: new_password = generate_password() user = previous_registration.email.split('@')[0] if reset_password(user, new_password): previous_registration.password = new_password previous_registration.forgotten_password = True previous_registration.save() send_mail(u'حسابك على السحابة الطبية', forgotten_message % (user, new_password), 'info@ksauhs-med.com', [email], fail_silently=False) return HttpResponseRedirect(reverse('register:thanks')) else: context = {'form': form, 'error_message': 'unknown'} else: context = {'form': form} else: form = ResetPasswordForm() context = {'form': form} return render(request, 'register/reset.html', context) def generate_password(): return ''.join(random.choice(string.ascii_uppercase) for i in range(6)) def login(): homepage_url = "https://www.ksauhs-med.com" homepage = requests.get(homepage_url) oc1d6beae686 = homepage.cookies['oc1d6beae686'] cookies = {'oc1d6beae686': oc1d6beae686} login_requesttoken_regex = re.compile('data-requesttoken="(.+?)"', re.U) login_requesttoken = re.findall(login_requesttoken_regex, homepage.content)[0] login_data = {'user': config.OWNCLOUD_ADMIN_USERNAME, 'password': config.OWNCLOUD_ADMIN_PASSWORD, 'requesttoken': login_requesttoken, 'remember_login': '1', 'timezone-offset': 'Asia/Baghdad', } login_page = requests.post(homepage_url, data=login_data, cookies=cookies) login_cookies = login_page.history[0].cookies cookies = {#'oc_username': login_cookies['oc_username'], #'oc_token': login_cookies['oc_token'], #'oc_remember_login': login_cookies['oc_remember_login'], 'oc1d6beae686': login_cookies['oc1d6beae686'], } return cookies def createuser(user, password, group): os.environ['OC_PASS'] = password command = "/usr/local/bin/php70 /home/medcloud/webapps/ownphp70/occ user:add {} --password-from-env -g {} -n".format(user, group) output = subprocess.call(command, shell=True) if output == 0: return True else: return False # createuser_url = "https://www.ksauhs-med.com/index.php/settings/users/users" # user_url = "https://www.ksauhs-med.com/index.php/settings/users" # login_cookies = login() # user_page = requests.post(user_url, cookies=login_cookies) # regex = re.findall("data-requesttoken=\"([^\"]+)\"", user_page.text) # requesttoken = regex[0] # user_data = {'username': user, # 'password': password, # 'groups[]': group} # headers = {'requesttoken': requesttoken} # createuser_page = requests.post(createuser_url, data=user_data, cookies=login_cookies, headers=headers) # json_object = json.loads(createuser_page.text) # if createuser_page.status_code == 201: # return True # else: # print json_object # REMOVE def reset_password(user, password): os.environ['OC_PASS'] = password command = "/usr/local/bin/php70 /home/medcloud/webapps/ownphp70/occ user:resetpassword {} --password-from-env -n".format(user) output = subprocess.call(command, shell=True) if output == 0: return True else: return False # changepassword_url = "https://www.ksauhs-med.com/index.php/settings/users/changepassword" # user_url = "https://www.ksauhs-med.com/index.php/settings/users" # login_cookies = login() # user_page = requests.post(user_url, cookies=login_cookies) # regex = re.findall("data-requesttoken=\"([^\"]+)\"", user_page.text) # requesttoken = regex[0] # user_data = {'username': user, # 'password': password} # headers = {'requesttoken': requesttoken, # 'X-Requested-With': 'XMLHttpRequest', # 'Referer': user_url} # changepassword_page = requests.post(changepassword_url, # data=user_data, # cookies=login_cookies, # headers=headers) # try: # json_object = json.loads(changepassword_page.text) # except ValueError: # json_object = {} # if json_object.get('status') == 'success': # return True
osamak/medcloud-registration
register/temp/views.py
Python
agpl-3.0
9,644
# -*- coding: utf-8 -*- """ ========================================================= SVM-Kernels ========================================================= Three different types of SVM-Kernels are displayed below. The polynomial and RBF are especially useful when the data-points are not linearly separable. """ # Code source: Gaël Varoquaux # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn import svm # Our dataset and targets X = np.c_[ (0.4, -0.7), (-1.5, -1), (-1.4, -0.9), (-1.3, -1.2), (-1.1, -0.2), (-1.2, -0.4), (-0.5, 1.2), (-1.5, 2.1), (1, 1), # -- (1.3, 0.8), (1.2, 0.5), (0.2, -2), (0.5, -2.4), (0.2, -2.3), (0, -2.7), (1.3, 2.1), ].T Y = [0] * 8 + [1] * 8 # figure number fignum = 1 # fit the model for kernel in ("linear", "poly", "rbf"): clf = svm.SVC(kernel=kernel, gamma=2) clf.fit(X, Y) # plot the line, the points, and the nearest vectors to the plane plt.figure(fignum, figsize=(4, 3)) plt.clf() plt.scatter( clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, facecolors="none", zorder=10, edgecolors="k", ) plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired, edgecolors="k") plt.axis("tight") x_min = -3 x_max = 3 y_min = -3 y_max = 3 XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j] Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()]) # Put the result into a color plot Z = Z.reshape(XX.shape) plt.figure(fignum, figsize=(4, 3)) plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired) plt.contour( XX, YY, Z, colors=["k", "k", "k"], linestyles=["--", "-", "--"], levels=[-0.5, 0, 0.5], ) plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.xticks(()) plt.yticks(()) fignum = fignum + 1 plt.show()
manhhomienbienthuy/scikit-learn
examples/svm/plot_svm_kernels.py
Python
bsd-3-clause
1,970
""" SHOPPING LISTS ITEMS MANAGEMENT """ from string import ascii_letters from datetime import date class ShoppingListItems(object): """ CLASS FOR ADDING, EDITING AND DELETING SHOPPING LIST ITEMS """ def __init__(self): self.list_of_shopping_list_items = [] def get_user_items(self, user, list_name): """METHOD FOR DETERMINING ITEMS IN A USERS LIST""" user_items = \ [item for item in self.list_of_shopping_list_items if item['user'] == user and item['list'] == list_name] return user_items def add(self, list_name, item_name, user): """METHOD FOR ADDING ITEMS IN SHOPPING LIST """ if item_name == '': return 'Name cannot be blank' elif all(c in ascii_letters+'-'+' ' for c in item_name): users_items = self.get_user_items(user, list_name) for item in users_items: if item['name'] == item_name: item['number'] += 1 return "Added 1 more " + item_name self.list_of_shopping_list_items.append({ 'name': item_name, 'list': list_name, 'user': user, 'date': str(date.today()), 'number': 1 }) return self.get_user_items(user, list_name) else: return "Invalid characters" def delete(self, item_name, list_name): """METHOD FOR DELETING ITEM FROM SHOPPING LIST """ if item_name == '': return 'Name cannot be blank' elif item_name not in [item['name'] for item in self.list_of_shopping_list_items if item['list'] == list_name]: return "Item not found" else: specific_shp_lst = [item for item in self.list_of_shopping_list_items if item['list'] == list_name] for item in specific_shp_lst: if item['name'] == item_name: self.list_of_shopping_list_items.remove(item) return self.list_of_shopping_list_items def edit(self, new_name, old_name, list_name, user): """METHOD FOR EDITING ITEM'S NAME IN SHOPPING LIST""" # Get users items users_list_items = self.get_user_items(user, list_name) for item in users_list_items: if new_name == item['name']: return "Name already used on another item" else: for item in users_list_items: if old_name == item['name']: del item['name'] item.update({'name': new_name}) elif old_name not in [item['name'] for item in users_list_items]: return "The Item you want to change does not exist" return users_list_items def edit_parent_list(self, old_list_name, new_list_name, user): """This method is called to sync change in name when changing list name""" users_list_items = self.get_user_items(user, old_list_name) for item in users_list_items: del item['list'] item.update({'list': new_list_name})
parseendavid/Andela-Developer-Challenge---Shopping-List-V2.0
app/shopping_lists_items.py
Python
mit
3,239
""" Week 7 Mini-project Descprition: Implementation of Spaceship Author: Itamar M. B. Lourenço Date: 2014-11-05 """ import simplegui import math import random # globals for user interface WIDTH = 800 HEIGHT = 600 score = 0 lives = 3 time = 0.5 TURN_FACTOR = math.radians(4) # degrees to radians THRUST_FACTOR = 0.35 # acceleration FRICTION_FACTOR = 0.02 # de-acceleration factor ROCK_MAX_ROT = 0.10 MISSILE_SPEED_FACTOR = 8 # DEBUG DEBUG = False class ImageInfo: def __init__(self, center, size, radius = 0, lifespan = None, animated = False): self.center = center self.size = size self.radius = radius if lifespan: self.lifespan = lifespan else: self.lifespan = float('inf') self.animated = animated def get_center(self): return self.center def get_size(self): return self.size def get_radius(self): return self.radius def get_lifespan(self): return self.lifespan def get_animated(self): return self.animated # art assets created by Kim Lathrop, may be freely re-used in non-commercial projects, please credit Kim # debris images - debris1_brown.png, debris2_brown.png, debris3_brown.png, debris4_brown.png # debris1_blue.png, debris2_blue.png, debris3_blue.png, debris4_blue.png, debris_blend.png debris_info = ImageInfo([320, 240], [640, 480]) debris_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/debris2_blue.png") # nebula images - nebula_brown.png, nebula_blue.png nebula_info = ImageInfo([400, 300], [800, 600]) nebula_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/nebula_blue.f2014.png") # splash image splash_info = ImageInfo([200, 150], [400, 300]) splash_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/splash.png") # ship image ship_info = ImageInfo([45, 45], [90, 90], 35) ship_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/double_ship.png") # missile image - shot1.png, shot2.png, shot3.png missile_info = ImageInfo([5,5], [10, 10], 3, 50) missile_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/shot2.png") # asteroid images - asteroid_blue.png, asteroid_brown.png, asteroid_blend.png asteroid_info = ImageInfo([45, 45], [90, 90], 40) asteroid_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blue.png") # animated explosion - explosion_orange.png, explosion_blue.png, explosion_blue2.png, explosion_alpha.png explosion_info = ImageInfo([64, 64], [128, 128], 17, 24, True) explosion_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/explosion_alpha.png") # sound assets purchased from sounddogs.com, please do not redistribute soundtrack = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/soundtrack.mp3") missile_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/missile.mp3") missile_sound.set_volume(.5) ship_thrust_sound = simplegui.load_sound("http://dl.dropbox.com/s/rpnyczqnoha2a50/thrustmm.mp3") #ship_thrust_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/thrust.mp3") explosion_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/explosion.mp3") # helper functions to handle transformations def angle_to_vector(ang): return [math.cos(ang), math.sin(ang)] def dist(p,q): return math.sqrt((p[0] - q[0]) ** 2+(p[1] - q[1]) ** 2) # Ship class class Ship: def __init__(self, pos, vel, angle, image, info): self.pos = [pos[0],pos[1]] self.vel = [vel[0],vel[1]] self.thrust = False self.angle = angle self.angle_vel = 0 self.image = image self.image_center = info.get_center() self.image_size = info.get_size() self.radius = info.get_radius() ship_thrust_sound.rewind() def draw(self,canvas): if self.thrust: # if moving, draw ship image with thrust flames canvas.draw_image(self.image, [self.image_center[0] + self.image_size[0], self.image_center[1]], self.image_size, self.pos, self.image_size, self.angle) else: canvas.draw_image(self.image, self.image_center, self.image_size, self.pos, self.image_size, self.angle) # for debug only if DEBUG: canvas.draw_circle(self.pos, self.radius, 2, "White") def update(self): # if ship is moving, update angular velocity if self.thrust: self.vel[0] += THRUST_FACTOR * angle_to_vector(self.angle)[0] self.vel[1] += THRUST_FACTOR * angle_to_vector(self.angle)[1] # update ship angle self.angle = (self.angle + self.angle_vel) % math.radians(360) # apply friction to velocity self.vel[0] *= (1 - FRICTION_FACTOR) self.vel[1] *= (1 - FRICTION_FACTOR) # update ship position self.pos[0] += self.vel[0] self.pos[1] += self.vel[1] # some math to always have ship inside canvas self.pos[0] = self.pos[0] % WIDTH self.pos[1] = self.pos[1] % HEIGHT # for debug only if DEBUG: shiplabel_pos.set_text("Position: [" + str(int(my_ship.pos[0])) + ", " + str(int(my_ship.pos[1])) + "]") shiplabel_vel.set_text("Velocity: [" + str(round(my_ship.vel[0], 3)) + ", " + str(round(my_ship.vel[1], 3)) + "]") shiplabel_ang.set_text("Angle: " + str(round(my_ship.angle, 3))) shiplabel_ang_v.set_text("Angle Vel: " + str(round(my_ship.angle_vel, 3))) # set ship angle (turn) velocity, or stops turning if 0 def set_angle_vel(self, angle_vel = 0): if angle_vel == 0: self.angle_vel = 0 else: self.angle_vel += angle_vel # switch thrusters on and off def switch_thrust(self): self.thrust = not self.thrust # if on, play thrusters sound if self.thrust: ship_thrust_sound.play() # if off, stop/rewind thrusters sound else: ship_thrust_sound.rewind() # turn ship left def turn_left(self): self.set_angle_vel(-TURN_FACTOR) # turn ship right def turn_right(self): self.set_angle_vel(TURN_FACTOR) # shoot a missile def shoot(self): global a_missile # get ship angle for missile start position and velocity angle = angle_to_vector(self.angle) # missile start position from ship tip position missile_pos = [self.pos[0] + angle[0] * self.image_center[0], self.pos[1] + angle[1] * self.image_center[1]] # missile velocity is ship velocity (and direction) plus own velocity missile_vel = [self.vel[0] + MISSILE_SPEED_FACTOR * angle[0], self.vel[1] + MISSILE_SPEED_FACTOR * angle[1]] # spawn missile a_missile = Sprite(missile_pos, missile_vel, 0, 0, missile_image, missile_info, missile_sound) # END Chip class # Sprite class class Sprite: def __init__(self, pos, vel, ang, ang_vel, image, info, sound = None): self.pos = [pos[0],pos[1]] self.vel = [vel[0],vel[1]] self.angle = ang self.angle_vel = ang_vel self.image = image self.image_center = info.get_center() self.image_size = info.get_size() self.radius = info.get_radius() self.lifespan = info.get_lifespan() self.animated = info.get_animated() self.age = 0 if sound: sound.rewind() sound.play() def draw(self, canvas): canvas.draw_image(self.image, self.image_center, self.image_size, self.pos, self.image_size, self.angle) # for debug only if DEBUG: canvas.draw_circle(self.pos, self.radius, 2, "Red") def update(self): # update object (turning) angle self.angle = (self.angle + self.angle_vel) % math.radians(360) # update object position self.pos[0] += self.vel[0] self.pos[1] += self.vel[1] # some math to always have object inside canvas self.pos[0] = self.pos[0] % WIDTH self.pos[1] = self.pos[1] % HEIGHT # for debug only if DEBUG: rocklabel_pos.set_text("Position: [" + str(int(a_rock.pos[0])) + ", " + str(int(a_rock.pos[1])) + "]") rocklabel_vel.set_text("Velocity: [" + str(round(a_rock.vel[0], 2)) + ", " + str(round(a_rock.vel[1], 2)) + "]") rocklabel_ang.set_text("Angle: " + str(round(a_rock.angle, 3))) rocklabel_ang_v.set_text("Angle Vel: " + str(round(a_rock.angle_vel, 3))) misslabel_pos.set_text("Position: [" + str(int(a_missile.pos[0])) + ", " + str(int(a_missile.pos[1])) + "]") misslabel_vel.set_text("Velocity: [" + str(round(a_missile.vel[0], 2)) + ", " + str(round(a_missile.vel[1], 2)) + "]") misslabel_ang.set_text("Angle: " + str(round(a_missile.angle, 3))) misslabel_ang_v.set_text("Angle Vel: " + str(round(a_missile.angle_vel, 3))) # END Sprite class def draw(canvas): global time # animiate background time += 1 wtime = (time / 4) % WIDTH center = debris_info.get_center() size = debris_info.get_size() canvas.draw_image(nebula_image, nebula_info.get_center(), nebula_info.get_size(), [WIDTH / 2, HEIGHT / 2], [WIDTH, HEIGHT]) canvas.draw_image(debris_image, center, size, (wtime - WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT)) canvas.draw_image(debris_image, center, size, (wtime + WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT)) canvas.draw_text("Lives", [20, 30], 20, "White") canvas.draw_text(str(lives), [20, 55], 20, "White") canvas.draw_text("Score", [WIDTH - 80, 30], 20, "White") canvas.draw_text(str(score), [WIDTH - 80, 55], 20, "White") # draw ship and sprites my_ship.draw(canvas) a_rock.draw(canvas) a_missile.draw(canvas) # update ship and sprites my_ship.update() a_rock.update() a_missile.update() # timer handler that spawns a rock def rock_spawner(): global a_rock pos = [random.randrange(0, WIDTH), random.randrange(0, HEIGHT)] vel = [random.choice([-1, 1]) * (random.random() + ROCK_MAX_ROT), random.choice([-1, 1]) * (random.random() + ROCK_MAX_ROT)] rotation = random.choice([-1, 1]) * (random.random() * ROCK_MAX_ROT) a_rock = Sprite(pos, vel, 0, rotation, asteroid_image, asteroid_info) # keydown handler def keydown(key): for i in move_keys: if key == simplegui.KEY_MAP[i]: move_keys[i]() # keyup handler def keyup(key): if key == simplegui.KEY_MAP["up"]: my_ship.switch_thrust() elif key == simplegui.KEY_MAP["left"] or key == simplegui.KEY_MAP["right"]: my_ship.set_angle_vel() # initialize frame frame = simplegui.create_frame("Asteroids", WIDTH, HEIGHT) # initialize ship and two sprites # def __init__(self, pos, vel, ang, ang_vel, image, info, sound = None): my_ship = Ship([WIDTH / 2, HEIGHT / 2], [0, 0], 0, ship_image, ship_info) a_rock = Sprite([WIDTH / 3, HEIGHT / 3], [1, 1], 0, 0, asteroid_image, asteroid_info) a_missile = Sprite([2 * WIDTH / 3, 2 * HEIGHT / 3], [-1,1], 0, 0, missile_image, missile_info, missile_sound) move_keys = {"up": my_ship.switch_thrust, "left": my_ship.turn_left, "right": my_ship.turn_right, "space": my_ship.shoot} # register handlers frame.set_draw_handler(draw) frame.set_keydown_handler(keydown) frame.set_keyup_handler(keyup) timer = simplegui.create_timer(1000.0, rock_spawner) # some game debug info if DEBUG: frame.add_label("Ship Info:") shiplabel_pos = frame.add_label("Position:" + str(my_ship.pos)) shiplabel_vel = frame.add_label("Velocity:" + str(my_ship.vel)) shiplabel_ang = frame.add_label("Angle:" + str(my_ship.angle)) shiplabel_ang_v = frame.add_label("Angle Vel:" + str(my_ship.angle_vel)) frame.add_label("") frame.add_label("Rock Info:") rocklabel_pos = frame.add_label("Position:" + str(a_rock.pos)) rocklabel_vel = frame.add_label("Velocity:" + str(a_rock.vel)) rocklabel_ang = frame.add_label("Angle:" + str(a_rock.angle)) rocklabel_ang_v = frame.add_label("Angle Vel:" + str(a_rock.angle_vel)) frame.add_label("") frame.add_label("Missile Info:") misslabel_pos = frame.add_label("Position:" + str(a_missile.pos)) misslabel_vel = frame.add_label("Velocity:" + str(a_missile.vel)) misslabel_ang = frame.add_label("Angle:" + str(a_missile.angle)) misslabel_ang_v = frame.add_label("Angle Vel:" + str(a_missile.angle_vel)) frame.add_label("") # get things rolling timer.start() frame.start()
italou/interactive-python-2014
week7-ship.py
Python
mit
13,611
#!/bin/python3 # -*- coding: utf-8 -*- from runner import Runner class FullRunner(Runner): def setup(self): self['number of years'] = 300 self['use all planets'] = False self['use planets'] = ['Sun', 'Earth', 'Jupiter', 'Venus', 'Mercury', 'Saturn', 'Neptune', 'Uranus', 'Pluto', 'Mars'] self['steps per year'] = 1e5 self['freeze sun'] = False self['use two body approximation'] = False self['method'] = 'verlet' self['do save results'] = False self['do save any results'] = True self['save period'] = 1000 self['find perihelion precession'] = False self['use relativistic correction'] = False self['gravitational exponent'] = 2 def run(self): out, _ = self.run_simulation() print(out) print(f"Simulation ran in {self.extract_time(out)} s") self.run_analysis() if __name__ == '__main__': with FullRunner() as system: system.run()
Caronthir/FYS3150
Project3/analysis/fullsystem.py
Python
mit
1,022
''' mostly for 2d polygons ''' import numpy as np def center(poly): return poly.mean(axis=0) def area(x,y): """ Calculate the area of a polygon given as x(...),y(...) Implementation of Shoelace formula """ # http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) def scale(poly, factor, center=None): poly = np.asarray(poly) x = poly[:,0] y = poly[:,1] try: fx,fy = factor except TypeError: fx,fy = factor, factor if center is None: center = x.mean(),y.mean() cx,cy = center dx = x-cx dy = y-cy out = np.empty_like(poly) out[:,0] = cx+dx*fx out[:,1] = cy+dy*fy return out def pointInsidePolygon(x, y, poly): """ Determine if a point is inside a given polygon or not Polygon is a list of (x,y) pairs. [code taken from: http://www.ariel.com.au/a/python-point-int-poly.html] let's make an easy square: >>> poly = [ (0,0),\ (1,0),\ (1,1),\ (0,1) ] >>> pointInsidePolygon(0.5,0.5, poly) True >>> pointInsidePolygon(1.5,1.5, poly) False """ n = len(poly) inside = False p1x, p1y = poly[0] for i in range(n + 1): p2x, p2y = poly[i % n] if y > min(p1y, p2y): if y <= max(p1y, p2y): if x <= max(p1x, p2x): if p1y != p2y: xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x if p1x == p2x or x <= xinters: inside = not inside p1x, p1y = p2x, p2y return inside if __name__ == '__main__': import doctest doctest.testmod() x = np.arange(0, 1, 0.001) y = np.sqrt(1 - x**2) print(area(x, y))
radjkarl/fancyTools
fancytools/geometry/polygon.py
Python
gpl-3.0
1,888
'''The Monty Hall Problem Modelled as a Bayesian Belief Network''' from bayesian.factor_graph import * ''' As BBN: GuestDoor ActualDoor \ / MontyDoor p(M|G,A) As Factor Graph: fGuestDoor fActualDoor | | GuestDoor ActualDoor | | +------fMontyDoor--------+ | MontyDoor Now Query: Given Guest chooses door A and Monty chooses door B, should guest switch to C or stay with A? ''' def f_prize_door(prize_door): return 1.0 / 3 def f_guest_door(guest_door): return 1.0 / 3 def f_monty_door(prize_door, guest_door, monty_door): if prize_door == guest_door: if prize_door == monty_door: return 0 else: return 0.5 elif prize_door == monty_door: return 0 elif guest_door == monty_door: return 0 return 1 if __name__ == '__main__': g = build_graph( f_prize_door, f_guest_door, f_monty_door, domains=dict( prize_door=['A', 'B', 'C'], guest_door=['A', 'B', 'C'], monty_door=['A', 'B', 'C']), name='Monty_Hall') g.inference_method = 'sample_db' # Initial Marginals without any knowledge. # Observe that the likelihood for # all three doors is 1/3. #print 'Initial Marginal Probabilities:' #g.q() # Now suppose the guest chooses # door A and Monty chooses door B. # Should we switch our choice from # A to C or not? # To answer this we "query" the # graph with instantiation of the # observed variables as "evidence". # The likelihood for door C has # indeed increased to 2/3 therefore # we should switch to door C. #print 'Marginals after knowing Guest chose A and Monty chose B.' #g.q(guest_door='A', monty_door='B')
kamijawa/ogc_server
bayesian/examples/factor_graphs/monty_hall_sampled.py
Python
mit
1,998
class Edge(): def __init__(self): self.origin = None self.goal = None self.value = None self.isDouble = False self.pX = [] # To Draw self.pY = []
ejherran/acaest
Grafos/general/Edge.py
Python
gpl-3.0
250
""" Word scoring Christopher Von Bargen, <cdvonbargen@gmail.com> Copyright (c) 2017 """ class Tile: """ """ def __init__(self, letter): """ """ self.letter = letter class TilePool: """ """ def __init__(self): """ """ self.pool = [] def drawTile(self): """ """ pass def returnTile(self): """ """ pass class Player: """ """ def __init__(self, name): """ """ self.name = name self.hand = [] self.score = 0 class Board: """ """ def __init__(self): """ """ pass def playTile(self, tile): """ """ pass
cdvonbargen/wordjerks
python/tile_pool.py
Python
gpl-3.0
756
import distutils.dir_util import glob import os import shutil import subprocess import time from cassandra.concurrent import execute_concurrent_with_args from dtest import (Tester, cleanup_cluster, create_ccm_cluster, create_ks, debug, get_test_path) from tools.assertions import assert_one from tools.files import replace_in_file, safe_mkdtemp from tools.hacks import advance_to_next_cl_segment from tools.misc import ImmutableMapping from tools.decorators import since class SnapshotTester(Tester): def create_schema(self, session): create_ks(session, 'ks', 1) session.execute('CREATE TABLE ks.cf ( key int PRIMARY KEY, val text);') def insert_rows(self, session, start, end): insert_statement = session.prepare("INSERT INTO ks.cf (key, val) VALUES (?, 'asdf')") args = [(r,) for r in range(start, end)] execute_concurrent_with_args(session, insert_statement, args, concurrency=20) def make_snapshot(self, node, ks, cf, name): debug("Making snapshot....") node.flush() snapshot_cmd = 'snapshot {ks} -cf {cf} -t {name}'.format(ks=ks, cf=cf, name=name) debug("Running snapshot cmd: {snapshot_cmd}".format(snapshot_cmd=snapshot_cmd)) node.nodetool(snapshot_cmd) tmpdir = safe_mkdtemp() os.mkdir(os.path.join(tmpdir, ks)) os.mkdir(os.path.join(tmpdir, ks, cf)) # Find the snapshot dir, it's different in various C* x = 0 for data_dir in node.data_directories(): snapshot_dir = "{data_dir}/{ks}/{cf}/snapshots/{name}".format(data_dir=data_dir, ks=ks, cf=cf, name=name) if not os.path.isdir(snapshot_dir): snapshot_dirs = glob.glob("{data_dir}/{ks}/{cf}-*/snapshots/{name}".format(data_dir=data_dir, ks=ks, cf=cf, name=name)) if len(snapshot_dirs) > 0: snapshot_dir = snapshot_dirs[0] else: continue debug("snapshot_dir is : " + snapshot_dir) debug("snapshot copy is : " + tmpdir) # Copy files from the snapshot dir to existing temp dir distutils.dir_util.copy_tree(str(snapshot_dir), os.path.join(tmpdir, str(x), ks, cf)) x += 1 return tmpdir def restore_snapshot(self, snapshot_dir, node, ks, cf): debug("Restoring snapshot....") for x in xrange(0, self.cluster.data_dir_count): snap_dir = os.path.join(snapshot_dir, str(x), ks, cf) if os.path.exists(snap_dir): ip = node.address() args = [node.get_tool('sstableloader'), '-d', ip, snap_dir] p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() exit_status = p.wait() if exit_status != 0: raise Exception("sstableloader command '%s' failed; exit status: %d'; stdout: %s; stderr: %s" % (" ".join(args), exit_status, stdout, stderr)) def restore_snapshot_schema(self, snapshot_dir, node, ks, cf): debug("Restoring snapshot schema....") for x in xrange(0, self.cluster.data_dir_count): schema_path = os.path.join(snapshot_dir, str(x), ks, cf, 'schema.cql') if os.path.exists(schema_path): node.run_cqlsh(cmds="SOURCE '%s'" % schema_path) class TestSnapshot(SnapshotTester): def test_basic_snapshot_and_restore(self): cluster = self.cluster cluster.populate(1).start() (node1,) = cluster.nodelist() session = self.patient_cql_connection(node1) self.create_schema(session) self.insert_rows(session, 0, 100) snapshot_dir = self.make_snapshot(node1, 'ks', 'cf', 'basic') # Write more data after the snapshot, this will get thrown # away when we restore: self.insert_rows(session, 100, 200) rows = session.execute('SELECT count(*) from ks.cf') self.assertEqual(rows[0][0], 200) # Drop the keyspace, make sure we have no data: session.execute('DROP KEYSPACE ks') self.create_schema(session) rows = session.execute('SELECT count(*) from ks.cf') self.assertEqual(rows[0][0], 0) # Restore data from snapshot: self.restore_snapshot(snapshot_dir, node1, 'ks', 'cf') node1.nodetool('refresh ks cf') rows = session.execute('SELECT count(*) from ks.cf') # clean up debug("removing snapshot_dir: " + snapshot_dir) shutil.rmtree(snapshot_dir) self.assertEqual(rows[0][0], 100) @since('3.0') def test_snapshot_and_restore_drop_table_remove_dropped_column(self): """ @jira_ticket CASSANDRA-13730 Dropping table should clear entries in dropped_column table """ cluster = self.cluster cluster.populate(1).start() node1, = cluster.nodelist() session = self.patient_cql_connection(node1) # Create schema and insert some data create_ks(session, 'ks', 1) session.execute("CREATE TABLE ks.cf (k int PRIMARY KEY, a text, b text)") session.execute("INSERT INTO ks.cf (k, a, b) VALUES (1, 'a', 'b')") assert_one(session, "SELECT * FROM ks.cf", [1, "a", "b"]) # Take a snapshot and drop the column and then drop table snapshot_dir = self.make_snapshot(node1, 'ks', 'cf', 'basic') session.execute("ALTER TABLE ks.cf DROP b") assert_one(session, "SELECT * FROM ks.cf", [1, "a"]) session.execute("DROP TABLE ks.cf") # Restore schema and data from snapshot, data should be the same as input self.restore_snapshot_schema(snapshot_dir, node1, 'ks', 'cf') self.restore_snapshot(snapshot_dir, node1, 'ks', 'cf') node1.nodetool('refresh ks cf') assert_one(session, "SELECT * FROM ks.cf", [1, "a", "b"]) # Clean up debug("removing snapshot_dir: " + snapshot_dir) shutil.rmtree(snapshot_dir) @since('3.11') def test_snapshot_and_restore_dropping_a_column(self): """ @jira_ticket CASSANDRA-13276 Can't load snapshots of tables with dropped columns. """ cluster = self.cluster cluster.populate(1).start() node1, = cluster.nodelist() session = self.patient_cql_connection(node1) # Create schema and insert some data create_ks(session, 'ks', 1) session.execute("CREATE TABLE ks.cf (k int PRIMARY KEY, a text, b text)") session.execute("INSERT INTO ks.cf (k, a, b) VALUES (1, 'a', 'b')") assert_one(session, "SELECT * FROM ks.cf", [1, "a", "b"]) # Drop a column session.execute("ALTER TABLE ks.cf DROP b") assert_one(session, "SELECT * FROM ks.cf", [1, "a"]) # Take a snapshot and drop the table snapshot_dir = self.make_snapshot(node1, 'ks', 'cf', 'basic') session.execute("DROP TABLE ks.cf") # Restore schema and data from snapshot self.restore_snapshot_schema(snapshot_dir, node1, 'ks', 'cf') self.restore_snapshot(snapshot_dir, node1, 'ks', 'cf') node1.nodetool('refresh ks cf') assert_one(session, "SELECT * FROM ks.cf", [1, "a"]) # Clean up debug("removing snapshot_dir: " + snapshot_dir) shutil.rmtree(snapshot_dir) class TestArchiveCommitlog(SnapshotTester): cluster_options = ImmutableMapping({'commitlog_segment_size_in_mb': 1}) def make_snapshot(self, node, ks, cf, name): debug("Making snapshot....") node.flush() snapshot_cmd = 'snapshot {ks} -cf {cf} -t {name}'.format(ks=ks, cf=cf, name=name) debug("Running snapshot cmd: {snapshot_cmd}".format(snapshot_cmd=snapshot_cmd)) node.nodetool(snapshot_cmd) tmpdirs = [] base_tmpdir = safe_mkdtemp() for x in xrange(0, self.cluster.data_dir_count): tmpdir = os.path.join(base_tmpdir, str(x)) os.mkdir(tmpdir) # Copy files from the snapshot dir to existing temp dir distutils.dir_util.copy_tree(os.path.join(node.get_path(), 'data{0}'.format(x), ks), tmpdir) tmpdirs.append(tmpdir) return tmpdirs def restore_snapshot(self, snapshot_dir, node, ks, cf, name): debug("Restoring snapshot for cf ....") data_dir = os.path.join(node.get_path(), 'data{0}'.format(os.path.basename(snapshot_dir))) cfs = [s for s in os.listdir(snapshot_dir) if s.startswith(cf + "-")] if len(cfs) > 0: cf_id = cfs[0] glob_path = "{snapshot_dir}/{cf_id}/snapshots/{name}".format(snapshot_dir=snapshot_dir, cf_id=cf_id, name=name) globbed = glob.glob(glob_path) if len(globbed) > 0: snapshot_dir = globbed[0] if not os.path.exists(os.path.join(data_dir, ks)): os.mkdir(os.path.join(data_dir, ks)) os.mkdir(os.path.join(data_dir, ks, cf_id)) debug("snapshot_dir is : " + snapshot_dir) distutils.dir_util.copy_tree(snapshot_dir, os.path.join(data_dir, ks, cf_id)) def test_archive_commitlog(self): self.run_archive_commitlog(restore_point_in_time=False) def test_archive_commitlog_with_active_commitlog(self): """ Copy the active commitlogs to the archive directory before restoration """ self.run_archive_commitlog(restore_point_in_time=False, archive_active_commitlogs=True) def dont_test_archive_commitlog(self): """ Run the archive commitlog test, but forget to add the restore commands """ self.run_archive_commitlog(restore_point_in_time=False, restore_archived_commitlog=False) def test_archive_commitlog_point_in_time(self): """ Test archive commit log with restore_point_in_time setting """ self.run_archive_commitlog(restore_point_in_time=True) def test_archive_commitlog_point_in_time_with_active_commitlog(self): """ Test archive commit log with restore_point_in_time setting """ self.run_archive_commitlog(restore_point_in_time=True, archive_active_commitlogs=True) def test_archive_commitlog_point_in_time_with_active_commitlog_ln(self): """ Test archive commit log with restore_point_in_time setting """ self.run_archive_commitlog(restore_point_in_time=True, archive_active_commitlogs=True, archive_command='ln') def run_archive_commitlog(self, restore_point_in_time=False, restore_archived_commitlog=True, archive_active_commitlogs=False, archive_command='cp'): """ Run archive commit log restoration test """ cluster = self.cluster cluster.populate(1) (node1,) = cluster.nodelist() # Create a temp directory for storing commitlog archives: tmp_commitlog = safe_mkdtemp() debug("tmp_commitlog: " + tmp_commitlog) # Edit commitlog_archiving.properties and set an archive # command: replace_in_file(os.path.join(node1.get_path(), 'conf', 'commitlog_archiving.properties'), [(r'^archive_command=.*$', 'archive_command={archive_command} %path {tmp_commitlog}/%name'.format( tmp_commitlog=tmp_commitlog, archive_command=archive_command))]) cluster.start() session = self.patient_cql_connection(node1) create_ks(session, 'ks', 1) # Write until we get a new CL segment. This avoids replaying # initialization mutations from startup into system tables when # restoring snapshots. See CASSANDRA-11811. advance_to_next_cl_segment( session=session, commitlog_dir=os.path.join(node1.get_path(), 'commitlogs') ) session.execute('CREATE TABLE ks.cf ( key bigint PRIMARY KEY, val text);') debug("Writing first 30,000 rows...") self.insert_rows(session, 0, 30000) # Record when this first set of inserts finished: insert_cutoff_times = [time.gmtime()] # Delete all commitlog backups so far: for f in glob.glob(tmp_commitlog + "/*"): debug('Removing {}'.format(f)) os.remove(f) snapshot_dirs = self.make_snapshot(node1, 'ks', 'cf', 'basic') if self.cluster.version() >= '3.0': system_ks_snapshot_dirs = self.make_snapshot(node1, 'system_schema', 'keyspaces', 'keyspaces') else: system_ks_snapshot_dirs = self.make_snapshot(node1, 'system', 'schema_keyspaces', 'keyspaces') if self.cluster.version() >= '3.0': system_col_snapshot_dirs = self.make_snapshot(node1, 'system_schema', 'columns', 'columns') else: system_col_snapshot_dirs = self.make_snapshot(node1, 'system', 'schema_columns', 'columns') if self.cluster.version() >= '3.0': system_ut_snapshot_dirs = self.make_snapshot(node1, 'system_schema', 'types', 'usertypes') else: system_ut_snapshot_dirs = self.make_snapshot(node1, 'system', 'schema_usertypes', 'usertypes') if self.cluster.version() >= '3.0': system_cfs_snapshot_dirs = self.make_snapshot(node1, 'system_schema', 'tables', 'cfs') else: system_cfs_snapshot_dirs = self.make_snapshot(node1, 'system', 'schema_columnfamilies', 'cfs') try: # Write more data: debug("Writing second 30,000 rows...") self.insert_rows(session, 30000, 60000) node1.flush() time.sleep(10) # Record when this second set of inserts finished: insert_cutoff_times.append(time.gmtime()) debug("Writing final 5,000 rows...") self.insert_rows(session, 60000, 65000) # Record when the third set of inserts finished: insert_cutoff_times.append(time.gmtime()) # Flush so we get an accurate view of commitlogs node1.flush() rows = session.execute('SELECT count(*) from ks.cf') # Make sure we have the same amount of rows as when we snapshotted: self.assertEqual(rows[0][0], 65000) # Check that there are at least one commit log backed up that # is not one of the active commit logs: commitlog_dir = os.path.join(node1.get_path(), 'commitlogs') debug("node1 commitlog dir: " + commitlog_dir) debug("node1 commitlog dir contents: " + str(os.listdir(commitlog_dir))) debug("tmp_commitlog contents: " + str(os.listdir(tmp_commitlog))) self.assertNotEqual(set(os.listdir(tmp_commitlog)) - set(os.listdir(commitlog_dir)), set()) cluster.flush() cluster.compact() node1.drain() # Destroy the cluster cluster.stop() debug("node1 commitlog dir contents after stopping: " + str(os.listdir(commitlog_dir))) debug("tmp_commitlog contents after stopping: " + str(os.listdir(tmp_commitlog))) self.copy_logs(self.cluster, name=self.id().split(".")[0] + "_pre-restore") cleanup_cluster(self.cluster, self.test_path) self.test_path = get_test_path() cluster = self.cluster = create_ccm_cluster(self.test_path, name='test') cluster.populate(1) node1, = cluster.nodelist() # Restore schema from snapshots: for system_ks_snapshot_dir in system_ks_snapshot_dirs: if self.cluster.version() >= '3.0': self.restore_snapshot(system_ks_snapshot_dir, node1, 'system_schema', 'keyspaces', 'keyspaces') else: self.restore_snapshot(system_ks_snapshot_dir, node1, 'system', 'schema_keyspaces', 'keyspaces') for system_col_snapshot_dir in system_col_snapshot_dirs: if self.cluster.version() >= '3.0': self.restore_snapshot(system_col_snapshot_dir, node1, 'system_schema', 'columns', 'columns') else: self.restore_snapshot(system_col_snapshot_dir, node1, 'system', 'schema_columns', 'columns') for system_ut_snapshot_dir in system_ut_snapshot_dirs: if self.cluster.version() >= '3.0': self.restore_snapshot(system_ut_snapshot_dir, node1, 'system_schema', 'types', 'usertypes') else: self.restore_snapshot(system_ut_snapshot_dir, node1, 'system', 'schema_usertypes', 'usertypes') for system_cfs_snapshot_dir in system_cfs_snapshot_dirs: if self.cluster.version() >= '3.0': self.restore_snapshot(system_cfs_snapshot_dir, node1, 'system_schema', 'tables', 'cfs') else: self.restore_snapshot(system_cfs_snapshot_dir, node1, 'system', 'schema_columnfamilies', 'cfs') for snapshot_dir in snapshot_dirs: self.restore_snapshot(snapshot_dir, node1, 'ks', 'cf', 'basic') cluster.start(wait_for_binary_proto=True) session = self.patient_cql_connection(node1) node1.nodetool('refresh ks cf') rows = session.execute('SELECT count(*) from ks.cf') # Make sure we have the same amount of rows as when we snapshotted: self.assertEqual(rows[0][0], 30000) # Edit commitlog_archiving.properties. Remove the archive # command and set a restore command and restore_directories: if restore_archived_commitlog: replace_in_file(os.path.join(node1.get_path(), 'conf', 'commitlog_archiving.properties'), [(r'^archive_command=.*$', 'archive_command='), (r'^restore_command=.*$', 'restore_command=cp -f %from %to'), (r'^restore_directories=.*$', 'restore_directories={tmp_commitlog}'.format( tmp_commitlog=tmp_commitlog))]) if restore_point_in_time: restore_time = time.strftime("%Y:%m:%d %H:%M:%S", insert_cutoff_times[1]) replace_in_file(os.path.join(node1.get_path(), 'conf', 'commitlog_archiving.properties'), [(r'^restore_point_in_time=.*$', 'restore_point_in_time={restore_time}'.format(restore_time=restore_time))]) debug("Restarting node1..") node1.stop() node1.start(wait_for_binary_proto=True) node1.nodetool('flush') node1.nodetool('compact') session = self.patient_cql_connection(node1) rows = session.execute('SELECT count(*) from ks.cf') # Now we should have 30000 rows from the snapshot + 30000 rows # from the commitlog backups: if not restore_archived_commitlog: self.assertEqual(rows[0][0], 30000) elif restore_point_in_time: self.assertEqual(rows[0][0], 60000) else: self.assertEqual(rows[0][0], 65000) finally: # clean up debug("removing snapshot_dir: " + ",".join(snapshot_dirs)) for snapshot_dir in snapshot_dirs: shutil.rmtree(snapshot_dir) debug("removing snapshot_dir: " + ",".join(system_ks_snapshot_dirs)) for system_ks_snapshot_dir in system_ks_snapshot_dirs: shutil.rmtree(system_ks_snapshot_dir) debug("removing snapshot_dir: " + ",".join(system_cfs_snapshot_dirs)) for system_cfs_snapshot_dir in system_cfs_snapshot_dirs: shutil.rmtree(system_cfs_snapshot_dir) debug("removing snapshot_dir: " + ",".join(system_ut_snapshot_dirs)) for system_ut_snapshot_dir in system_ut_snapshot_dirs: shutil.rmtree(system_ut_snapshot_dir) debug("removing snapshot_dir: " + ",".join(system_col_snapshot_dirs)) for system_col_snapshot_dir in system_col_snapshot_dirs: shutil.rmtree(system_col_snapshot_dir) debug("removing tmp_commitlog: " + tmp_commitlog) shutil.rmtree(tmp_commitlog) def test_archive_and_restore_commitlog_repeatedly(self): """ @jira_ticket CASSANDRA-10593 Run archive commit log restoration test repeatedly to make sure it is idempotent and doesn't fail if done repeatedly """ cluster = self.cluster cluster.populate(1) node1 = cluster.nodelist()[0] # Create a temp directory for storing commitlog archives: tmp_commitlog = safe_mkdtemp() debug("tmp_commitlog: {}".format(tmp_commitlog)) # Edit commitlog_archiving.properties and set an archive # command: replace_in_file(os.path.join(node1.get_path(), 'conf', 'commitlog_archiving.properties'), [(r'^archive_command=.*$', 'archive_command=ln %path {tmp_commitlog}/%name'.format( tmp_commitlog=tmp_commitlog)), (r'^restore_command=.*$', 'restore_command=cp -f %from %to'), (r'^restore_directories=.*$', 'restore_directories={tmp_commitlog}'.format( tmp_commitlog=tmp_commitlog))]) cluster.start(wait_for_binary_proto=True) debug("Creating initial connection") session = self.patient_cql_connection(node1) create_ks(session, 'ks', 1) session.execute('CREATE TABLE ks.cf ( key bigint PRIMARY KEY, val text);') debug("Writing 30,000 rows...") self.insert_rows(session, 0, 60000) try: # Check that there are at least one commit log backed up that # is not one of the active commit logs: commitlog_dir = os.path.join(node1.get_path(), 'commitlogs') debug("node1 commitlog dir: " + commitlog_dir) cluster.flush() self.assertNotEqual(set(os.listdir(tmp_commitlog)) - set(os.listdir(commitlog_dir)), set()) debug("Flushing and doing first restart") cluster.compact() node1.drain() # restart the node which causes the active commitlogs to be archived node1.stop() node1.start(wait_for_binary_proto=True) debug("Stopping and second restart") node1.stop() node1.start(wait_for_binary_proto=True) # Shouldn't be any additional data since it's replaying the same stuff repeatedly session = self.patient_cql_connection(node1) rows = session.execute('SELECT count(*) from ks.cf') self.assertEqual(rows[0][0], 60000) finally: debug("removing tmp_commitlog: " + tmp_commitlog) shutil.rmtree(tmp_commitlog)
snazy/cassandra-dtest
snapshot_test.py
Python
apache-2.0
23,150
from helper import unittest, PillowTestCase, hopper from PIL import Image, IptcImagePlugin TEST_FILE = "Tests/images/iptc.jpg" class TestFileIptc(PillowTestCase): # Helpers def dummy_IptcImagePlugin(self): # Create an IptcImagePlugin object without initializing it class FakeImage(object): pass im = FakeImage() im.__class__ = IptcImagePlugin.IptcImageFile return im # Tests def test_getiptcinfo_jpg_none(self): # Arrange im = hopper() # Act iptc = IptcImagePlugin.getiptcinfo(im) # Assert self.assertIsNone(iptc) def test_getiptcinfo_jpg_found(self): # Arrange im = Image.open(TEST_FILE) # Act iptc = IptcImagePlugin.getiptcinfo(im) # Assert self.assertIsInstance(iptc, dict) self.assertEqual(iptc[(2, 90)], b"Budapest") self.assertEqual(iptc[(2, 101)], b"Hungary") def test_i(self): # Arrange c = b"a" # Act ret = IptcImagePlugin.i(c) # Assert self.assertEqual(ret, 97) def test_dump(self): # Arrange c = b"abc" # Temporarily redirect stdout try: from cStringIO import StringIO except ImportError: from io import StringIO import sys old_stdout = sys.stdout sys.stdout = mystdout = StringIO() # Act IptcImagePlugin.dump(c) # Reset stdout sys.stdout = old_stdout # Assert self.assertEqual(mystdout.getvalue(), "61 62 63 \n") if __name__ == '__main__': unittest.main() # End of file
liorvh/infernal-twin
build/pillow/Tests/test_file_iptc.py
Python
gpl-3.0
1,685
from datetime import * from dateutil.relativedelta import * from eventtools.conf import settings import calendar WEEKDAY_MAP = { calendar.MONDAY: MO, calendar.TUESDAY: TU, calendar.WEDNESDAY: WE, calendar.THURSDAY: TH, calendar.FRIDAY: FR, calendar.SATURDAY: SA, calendar.SUNDAY: SU, } def _weekday_fn(wk): return WEEKDAY_MAP.get(wk, wk) FIRST_DAY_OF_WEEK = _weekday_fn(settings.FIRST_DAY_OF_WEEK) FIRST_DAY_OF_WEEKEND = _weekday_fn(settings.FIRST_DAY_OF_WEEKEND) LAST_DAY_OF_WEEKEND = _weekday_fn(settings.LAST_DAY_OF_WEEKEND) class XDateRange(object): """ Embryo class to replace xdaterange below. For now this is only used in calendar sets (which uses the 'in' method) """ def __init__(self, start, end): self.start = start self.end = end self.delta = end - start def __contains__(self, item): if self.start is not None: after_start = item >= self.start else: after_start = True if self.end is not None: before_end = item <= self.end else: before_end = True return after_start and before_end def __unicode__(self): if self.delta: return '%s - %s' % ( self.start.strftime('%d %b %Y'), self.end.strftime('%d %b %Y'), ) return self.start.strftime('%d %b %Y') def later(self): return XDateRange(self.end + timedelta(1), self.end + self.delta + timedelta(1)) def earlier(self): return XDateRange(self.start - self.delta - timedelta(1), self.start - timedelta(1)) class DateTester(object): """ A class that takes a set of occurrences. Then you can test dates with it to see if the date is in that set. if date.today() in date_tester_object: ... """ def __init__(self, occurrence_qs): self.occurrence_qs = occurrence_qs def __contains__(self, d): occs = self.occurrence_qs.starts_on(d) return occs def xdaterange(d1, d2): delta_range = range((d2-d1).days) for td in delta_range: yield d1 + timedelta(td) def daterange(d1, d2): return list(xdaterange(d1, d2)) def dates_for_week_of(d): d1 = d + relativedelta(weekday = FIRST_DAY_OF_WEEK(-1)) d2 = d1 + timedelta(7) return d1, d2 def dates_in_week_of(d): return daterange(*dates_for_week_of(d)) def dates_for_weekend_of(d): d1 = d + relativedelta(weekday = FIRST_DAY_OF_WEEKEND(+1)) d2 = d1 + relativedelta(weekday = LAST_DAY_OF_WEEKEND(+1)) return d1, d2 def dates_in_weekend_of(d): return daterange(*dates_for_weekend_of(d)) def dates_for_fortnight_of(d): #fortnights overlap d1 = d + relativedelta(weekday = FIRST_DAY_OF_WEEK(-1)) d2 = d1 + timedelta(14) return d1, d2 def dates_in_fortnight_of(d): return daterange(*dates_for_fortnight_of(d)) def dates_for_month_of(d): d1 = d + relativedelta(day=1) #looks like a bug; isn't. d2 = d1 + relativedelta(months=+1, days=-1) return d1, d2 def dates_in_month_of(d): return daterange(*dates_for_month_of(d)) def dates_for_year_of(d): d1 = date(d.year, 1, 1) d2 = date(d.year, 12, 31) return d1, d2 def dates_in_year_of(d): return daterange(*dates_for_year_of(d)) def is_weekend(d): if type(d) in [date, datetime]: d = d.weekday() if type(d) == type(MO): d = d.weekday if FIRST_DAY_OF_WEEKEND <= LAST_DAY_OF_WEEKEND: return (FIRST_DAY_OF_WEEKEND.weekday <= d <= LAST_DAY_OF_WEEKEND.weekday) else: return (d >= FIRST_DAY_OF_WEEKEND.weekday) or (d <= LAST_DAY_OF_WEEKEND.weekday) def is_weekday(d): return not is_weekend(d)
ixc/glamkit-eventtools
eventtools/utils/dateranges.py
Python
bsd-3-clause
3,790
""" Yammer OAuth2 support """ import logging from urllib import urlencode from urlparse import parse_qs from django.utils import simplejson from django.utils.datastructures import MergeDict from social_auth.backends import BaseOAuth2, OAuthBackend, USERNAME from social_auth.exceptions import AuthCanceled from social_auth.utils import dsa_urlopen, setting YAMMER_SERVER = 'yammer.com' YAMMER_STAGING_SERVER = 'staging.yammer.com' YAMMER_OAUTH_URL = 'https://www.%s/oauth2/' % YAMMER_SERVER YAMMER_AUTH_URL = 'https://www.%s/dialog/oauth' % YAMMER_SERVER YAMMER_API_URL = 'https://www.%s/api/v1/' % YAMMER_SERVER class YammerBackend(OAuthBackend): name = 'yammer' EXTRA_DATA = [ ('id', 'id'), ('expires', setting('SOCIAL_AUTH_EXPIRATION', 'expires')), ('mugshot_url', 'mugshot_url') ] def get_user_id(self, details, response): return response['user']['id'] def get_user_details(self, response): username = response['user']['name'] first_name = response['user']['first_name'] last_name = response['user']['last_name'] full_name = response['user']['full_name'] email = response['user']['contact']['email_addresses'][0]['address'] mugshot_url = response['user']['mugshot_url'] return { USERNAME: username, 'email': email, 'fullname': full_name, 'first_name': first_name, 'last_name': last_name, 'picture_url': mugshot_url } class YammerOAuth2(BaseOAuth2): AUTH_BACKEND = YammerBackend AUTHORIZATION_URL = YAMMER_AUTH_URL ACCESS_TOKEN_URL = '%s%s' % (YAMMER_OAUTH_URL, 'access_token') REQUEST_TOKEN_URL = '%s%s' % (YAMMER_OAUTH_URL, 'request_token') SETTINGS_KEY_NAME = 'YAMMER_CONSUMER_KEY' SETTINGS_SECRET_NAME = 'YAMMER_CONSUMER_SECRET' def user_data(self, access_token, *args, **kwargs): """Load user data from yammer""" params = { 'client_id': setting(self.SETTINGS_KEY_NAME, ''), 'client_secret': setting(self.SETTINGS_SECRET_NAME, ''), 'code': access_token } url = '%s?%s' % (self.ACCESS_TOKEN_URL, urlencode(params)) try: return simplejson.load(dsa_urlopen(url)) except Exception, e: logging.exception(e) return None def auth_complete(self, *args, **kwargs): """Yammer API is a little strange""" if 'error' in self.data: logging.error("%s: %s:\n%s" % ( self.data('error'), self.data('error_reason'), self.data('error_description') )) raise AuthCanceled(self) # now we need to clean up the data params data = dict(self.data.copy()) redirect_state = data.get('redirect_state') if redirect_state and '?' in redirect_state: redirect_state, extra = redirect_state.split('?', 1) extra = parse_qs(extra) data['redirect_state'] = redirect_state if 'code' in extra: data['code'] = extra['code'][0] self.data = MergeDict(data) return super(YammerOAuth2, self).auth_complete(*args, **kwargs) BACKENDS = { 'yammer': YammerOAuth2 }
eahneahn/free
djangoproject/social_auth/backends/contrib/yammer.py
Python
agpl-3.0
3,276
# encoding: utf-8 # Copyright 2013 maker # License """ Finance integration with Events module Provides Liabilities as EventRenderer instances """ from maker.finance.models import Liability from maker.core.models import Object from maker.events.rendering import EventRenderer from django.db.models import Q import datetime def get_events(request): "Return a list of EventRenderers from available Liability" events = [] query = Q(due_date__isnull=False) liabilities = Object.filter_by_request(request, manager=Liability.objects.filter(query)) for liability in liabilities: if liability.due_date: old = liability.due_date new_due_date = datetime.datetime(year=old.year, month=old.month, day=old.day, hour=12, minute=0, second=0) event = EventRenderer(liability.name, None, new_due_date, liability.get_absolute_url()) event.css_class += " finance-calendar-liability" events.append(event) return events
alejo8591/maker
finance/events.py
Python
mit
1,017
# Generated by Django 2.2.9 on 2020-01-31 22:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('symposion_speakers', '0004_make_speaker_slugs_unique'), ] operations = [ migrations.AddField( model_name='speaker', name='github_username', field=models.CharField(blank=True, help_text='Your Github account', max_length=39), ), ]
pydata/conf_site
symposion/speakers/migrations/0005_speaker_github_username.py
Python
mit
457
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fundraising', '0001_initial'), ] operations = [ migrations.CreateModel( name='Donation', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('amount', models.DecimalField(null=True, max_digits=9, decimal_places=2)), ('date', models.DateTimeField()), ('donor', models.ForeignKey(to='fundraising.DjangoHero', null=True)), ], options={ }, bases=(models.Model,), ), migrations.AlterField( model_name='djangohero', name='is_amount_displayed', field=models.BooleanField(default=False, verbose_name='Agreed to disclose amount of donation?'), preserve_default=True, ), migrations.AlterField( model_name='djangohero', name='is_subscribed', field=models.BooleanField(default=False, verbose_name='Agreed to being contacted by DSF?'), preserve_default=True, ), migrations.AlterField( model_name='djangohero', name='is_visible', field=models.BooleanField(default=False, verbose_name='Agreed to displaying on the fundraising page?'), preserve_default=True, ), migrations.AlterField( model_name='djangohero', name='logo', field=models.ImageField(upload_to='fundraising/logos/', blank=True), preserve_default=True, ), ]
gnarf/djangoproject.com
fundraising/migrations/0002_auto_20150117_1728.py
Python
bsd-3-clause
1,761
"""Contains the SwitchController class which is responsible for reading switch states and posting events to the framework. """ # switch_controller.py # Mission Pinball Framework # Written by Brian Madden & Gabe Knuth # Released under the MIT License. (See license info at the end of this file.) # Documentation and more info at http://missionpinball.com/mpf import logging from collections import defaultdict import time from mpf.system.config import CaseInsensitiveDict from mpf.system.timing import Timing from mpf.system.utility_functions import Util class SwitchController(object): """Base class for the switch controller, which is responsible for receiving all switch activity in the machine and converting them into events. More info: http://missionpinball.com/docs/system-components/switch-controller/ """ log = logging.getLogger('SwitchController') def __init__(self, machine): self.machine = machine self.registered_switches = CaseInsensitiveDict() # Dictionary of switches and states that have been registered for # callbacks. self.active_timed_switches = defaultdict(list) # Dictionary of switches that are currently in a state counting ms # waiting to notify their handlers. In other words, this is the dict that # tracks current switches for things like "do foo() if switch bar is # active for 100ms." self.switches = CaseInsensitiveDict() # Dictionary which holds the master list of switches as well as their # current states. State here does factor in whether a switch is NO or NC, # so 1 = active and 0 = inactive. self.switch_event_active = ( self.machine.config['mpf']['switch_event_active']) self.switch_event_inactive = ( self.machine.config['mpf']['switch_event_inactive']) self.switch_tag_event = ( self.machine.config['mpf']['switch_tag_event']) # register for events self.machine.events.add_handler('timer_tick', self._tick, 1000) self.machine.events.add_handler('init_phase_2', self._initialize_switches, 1000) # priority 1000 so this fires first self.machine.events.add_handler('machine_reset_phase_3', self.log_active_switches) self.monitors = list() def _initialize_switches(self): self.update_switches_from_hw() for switch in self.machine.switches: # Populate self.switches self.set_state(switch.name, switch.state, reset_time=True) # Populate self.registered_switches self.registered_switches[switch.name + '-0'] = list() self.registered_switches[switch.name + '-1'] = list() if self.machine.config['mpf']['auto_create_switch_events']: switch.activation_events.add( self.machine.config['mpf']['switch_event_active'].replace( '%', switch.name)) switch.deactivation_events.add( self.machine.config['mpf'][ 'switch_event_inactive'].replace( '%', switch.name)) if 'activation_events' in switch.config: for event in Util.string_to_lowercase_list( switch.config['activation_events']): if "|" in event: ev_name, ev_time = event.split("|") self.add_switch_handler( switch_name=switch.name, callback=self.machine.events.post, state=1, ms=Timing.string_to_ms(ev_time), callback_kwargs={'event': ev_name} ) else: switch.activation_events.add(event) if 'deactivation_events' in switch.config: for event in Util.string_to_lowercase_list( switch.config['deactivation_events']): if "|" in event: ev_name, ev_time = event.split("|") self.add_switch_handler( switch_name=switch.name, callback=self.machine.events.post, state=0, ms=Timing.string_to_ms(ev_time), callback_kwargs={'event': ev_name} ) else: switch.deactivation_events.add(event) def update_switches_from_hw(self): """Updates the states of all the switches be re-reading the states from the hardware platform. This method works silently and does not post any events if any switches changed state. """ # create a list of hw switch numbers, platforms, and switch objects platforms = set() switches = set() # (switch_object, number) for switch in self.machine.switches: platforms.add(switch.platform) switches.add((switch, switch.number)) for platform in platforms: switch_states = platform.get_hw_switch_states() for switch, number in switches: switch.state = switch_states[number] ^ switch.invert def verify_switches(self): """Loops through all the switches and queries their hardware states via their platform interfaces and them compares that to the state that MPF thinks the switches are in. Throws logging warnings if anything doesn't match. This method is notification only. It doesn't fix anything. """ current_states = dict() for switch in self.machine.switches: current_states[switch] = switch.state self.update_switches_from_hw() for switch in self.machine.switches: if switch.state ^ switch.invert != current_states[switch]: self.log.warning("Switch State Error! Switch: %s, HW State: " "%s, MPF State: %s", switch.name, current_states[switch], switch.state ^ switch.invert) def is_state(self, switch_name, state, ms=0): """Queries whether a switch is in a given state and (optionally) whether it has been in that state for the specified number of ms. Returns True if the switch_name has been in the state for the given number of ms. If ms is not specified, returns True if the switch is in the state regardless of how long it's been in that state. """ if self.switches[switch_name]['state'] == state: if ms <= self.ms_since_change(switch_name): return True else: return False else: return False def is_active(self, switch_name, ms=None): """Queries whether a switch is active. Returns True if the current switch is active. If optional arg ms is passed, will only return true if switch has been active for that many ms. Note this method does consider whether a switch is NO or NC. So an NC switch will show as active if it is open, rather than closed. """ return self.is_state(switch_name=switch_name, state=1, ms=ms) def is_inactive(self, switch_name, ms=None): """Queries whether a switch is inactive. Returns True if the current switch is inactive. If optional arg `ms` is passed, will only return true if switch has been inactive for that many ms. Note this method does consider whether a switch is NO or NC. So an NC switch will show as active if it is closed, rather than open. """ return self.is_state(switch_name=switch_name, state=0, ms=ms) def ms_since_change(self, switch_name): """Returns the number of ms that have elapsed since this switch last changed state. """ return (time.time() - self.switches[switch_name]['time']) * 1000.0 def secs_since_change(self, switch_name): """Returns the number of ms that have elapsed since this switch last changed state. """ return time.time() - self.switches[switch_name]['time'] def set_state(self, switch_name, state=1, reset_time=False): """Sets the state of a switch.""" if reset_time: timestamp = 1 else: timestamp = time.time() self.switches.update({switch_name: {'state': state, 'time': timestamp } }) # todo this method does not set the switch device's state. Either get # rid of it, or move the switch device settings from process_switch() # to here. def process_switch(self, name=None, state=1, logical=False, num=None, obj=None, debounced=True): """Processes a new switch state change. Args: name: The string name of the switch. This is optional if you specify the switch via the 'num' or 'obj' parameters. state: Boolean or int of state of the switch you're processing, True/1 is active, False/0 is inactive. logical: Boolean which specifies whether the 'state' argument represents the "physical" or "logical" state of the switch. If True, a 1 means this switch is active and a 0 means it's inactive, regardless of the NC/NO configuration of the switch. If False, then the state paramenter passed will be inverted if the switch is configured to be an 'NC' type. Typically the hardware will send switch states in their raw (logical=False) states, but other interfaces like the keyboard and OSC will use logical=True. num: The hardware number of the switch. obj: The switch object. debounced: Whether or not the update for the switch you're sending has been debounced or not. Default is True Note that there are three different paramter options to specify the switch: 'name', 'num', and 'obj'. You only need to pass one of them. This is the method that is called by the platform driver whenever a switch changes state. It's also used by the "other" modules that activate switches, including the keyboard and OSC interfaces. State 0 means the switch changed from active to inactive, and 1 means it changed from inactive to active. (The hardware & platform code handles NC versus NO switches and translates them to 'active' versus 'inactive'.) """ self.log.debug("Processing switch. Name: %s, state: %s, logical: %s," "num: %s, obj: %s, debounced: %s", name, state, logical, num, obj, debounced) # Find the switch name if num is not None: # can't be 'if num:` in case the num is 0. for switch in self.machine.switches: if switch.number == num: name = switch.name obj = switch break elif obj: name = obj.name elif name: try: obj = self.machine.switches[name] except KeyError: self.log.warning("Cannot process switch '%s' as this is not a" "valid switch name.", name) return name = obj.name # switches this to the name MPF wants to use if not obj: self.log.warning("Received a state change from non-configured " "switch. Number: %s, Name: %s", num, name) return # We need int, but this lets it come in as boolean also if state: state = 1 else: state = 0 # flip the logical & physical states for NC switches hw_state = state if obj.invert: if logical: # NC + logical means hw_state is opposite of state hw_state ^= 1 else: # NC w/o logical (i.e. hardware state was sent) means logical # state is the opposite state ^= 1 # If this update is not debounced, only proceed if this switch is # configured to not be debounced. if not debounced: if obj.config['debounce']: return # Update the hardware state since we always want this to match real hw obj.hw_state = hw_state # if the switch is active, check to see if it's recycle_time has passed if state and not self._check_recycle_time(obj, state): return obj.state = state # update the switch device if state: # update the switch's next recycle clear time obj.recycle_clear_tick = Timing.tick + obj.recycle_ticks # if the switch is already in this state, then abort if self.switches[name]['state'] == state: if not obj.recycle_ticks: self.log.info("Received duplicate switch state, which means " "this switch had some non-debounced state changes. This " "could be nothing, but if it happens a lot it could " "indicate noise or interference on the line. Switch: %s", name) return self.log.info("<<<<< switch: %s, State:%s >>>>>", name, state) # Update the switch controller's logical state for this switch self.set_state(name, state) # Combine name & state so we can look it up switch_key = str(name) + '-' + str(state) # Do we have any registered handlers for this switch/state combo? if switch_key in self.registered_switches: for entry in self.registered_switches[switch_key]: # generator? # Found an entry. if entry['ms']: # This entry is for a timed switch, so add it to our # active timed switch list key = time.time() + (entry['ms'] / 1000.0) value = {'switch_action': str(name) + '-' + str(state), 'callback': entry['callback'], 'switch_name': name, 'state': state, 'ms': entry['ms'], 'removed': False, 'return_info': entry['return_info'], 'callback_kwargs': entry['callback_kwargs']} self.active_timed_switches[key].append(value) self.log.debug( "Found timed switch handler for k/v %s / %s", key, value) else: # This entry doesn't have a timed delay, so do the action # now if entry['return_info']: entry['callback'](switch_name=name, state=state, ms=0, **entry['callback_kwargs']) else: entry['callback'](**entry['callback_kwargs']) # todo need to add args and kwargs support to callback # now check if the opposite state is in the active timed switches list # if so, remove it for k, v, in self.active_timed_switches.items(): # using items() instead of iteritems() since we might want to # delete while iterating for item in v: if item['switch_action'] == str(name) + '-' + str(state ^ 1): # ^1 in above line invertes the state if self.active_timed_switches[k]: del self.active_timed_switches[k] for monitor in self.monitors: monitor(name, state) self._post_switch_events(name, state) def add_monitor(self, monitor): if monitor not in self.monitors: self.monitors.append(monitor) def add_switch_handler(self, switch_name, callback, state=1, ms=0, return_info=False, callback_kwargs=None): """Register a handler to take action on a switch event. Args: switch_name: String name of the switch you're adding this handler for. callback: The method you want called when this switch handler fires. state: Integer of the state transition you want to callback to be triggered on. Default is 1 which means it's called when the switch goes from inactive to active, but you can also use 0 which means your callback will be called when the switch becomes inactive ms: Integer. If you specify a 'ms' parameter, the handler won't be called until the witch is in that state for that many milliseconds (rounded up to the nearst machine timer tick). return_info: If True, the switch controller will pass the parameters of the switch handler as arguments to the callback, including switch_name, state, and ms. If False (default), it just calls the callback with no parameters. callback_kwargs: Additional kwargs that will be passed with the callback. You can mix & match entries for the same switch here. """ if not callback_kwargs: callback_kwargs = dict() self.log.debug("Registering switch handler: %s, %s, state: %s, ms: %s" ", info: %s, cb_kwargs: %s", switch_name, callback, state, ms, return_info, callback_kwargs) entry_val = {'ms': ms, 'callback': callback, 'return_info': return_info, 'callback_kwargs': callback_kwargs} entry_key = str(switch_name) + '-' + str(state) self.registered_switches[entry_key].append(entry_val) # If the switch handler that was just registered has a delay (i.e. ms>0, # then let's see if the switch is currently in the state that the # handler was registered for. If so, and if the switch has been in this # state for less time than the ms registered, then we need to add this # switch to our active_timed_switches list so this handler is called # when this switch's active time expires. (in other words, we're # catching delayed switches that were in progress when this handler was # registered. if ms: # only do this for handlers that have delays if state == 1: if self.is_active(switch_name, 0) and ( self.ms_since_change(switch_name) < ms): # figure out when this handler should fire based on the # switch's original activation time. key = ( time.time() + ((ms - self.ms_since_change(switch_name)) / 1000.0)) value = {'switch_action': entry_key, 'callback': callback, 'switch_name': switch_name, 'state': state, 'ms': ms, 'removed': False, 'return_info': return_info, 'callback_kwargs': callback_kwargs} self.active_timed_switches[key].append(value) elif state == 0: if self.is_inactive(switch_name, 0) and ( self.ms_since_change(switch_name) < ms): key = ( time.time() + ((ms - self.ms_since_change(switch_name)) / 1000.0)) value = {'switch_action': entry_key, 'callback': callback, 'switch_name': switch_name, 'state': state, 'ms': ms, 'removed': False, 'return_info': return_info, 'callback_kwargs': callback_kwargs} self.active_timed_switches[key].append(value) # Return the args we used to setup this handler for easy removal later return {'switch_name': switch_name, 'callback': callback, 'state': state, 'ms': ms} def remove_switch_handler(self, switch_name, callback, state=1, ms=0): """Removes a registered switch handler. Currently this only works if you specify everything exactly as you set it up. (Except for return_info, which doesn't matter if true or false, it will remove either / both. """ self.log.debug( "Removing switch handler. Switch: %s, State: %s, ms: %s", switch_name, state, ms) entry_key = str(switch_name) + '-' + str(state) if entry_key in self.registered_switches: for index, settings in enumerate( self.registered_switches[entry_key]): if (settings['ms'] == ms and settings['callback'] == callback): self.registered_switches[entry_key].remove(settings) for timed_key, timed_entry in self.active_timed_switches.items(): for key, entry in enumerate(timed_entry): if entry['switch_action'] == entry_key and entry['ms'] == ms and entry['callback'] == callback: entry['removed'] = True def log_active_switches(self): """Writes out entries to the log file of all switches that are currently active. This is used to set the "initial" switch states of standalone testing tools, like our log file playback utility, but it might be useful in other scenarios when weird things are happening. This method dumps these events with logging level "INFO." """ self.log.info("Dumping current active switches") for k, v in self.switches.iteritems(): if v['state']: self.log.info("Active Switch|%s", k) def _check_recycle_time(self, switch, state): # checks to see when a switch is ok to be activated again after it's # been last activated if Timing.tick >= switch.recycle_clear_tick: return True else: if state: switch.recycle_jitter_count += 1 return False def _post_switch_events(self, switch_name, state): """Posts the game events based on this switch changing state. """ # the following events all fire the moment a switch goes active if state == 1: for event in self.machine.switches[switch_name].activation_events: self.machine.events.post(event) for tag in self.machine.switches[switch_name].tags: self.machine.events.post( self.switch_tag_event.replace('%', tag)) # the following events all fire the moment a switch becomes inactive elif state == 0: for event in ( self.machine.switches[switch_name].deactivation_events): self.machine.events.post(event) def _tick(self): """Called once per machine tick. Checks the current list of active timed switches to see if it's time to take action on any of them. If so, does the callback and then removes that entry from the list. """ for k in self.active_timed_switches.keys(): if k <= time.time(): # change to generator? for entry in self.active_timed_switches[k]: if entry['removed']: continue self.log.debug( "Processing timed switch handler. Switch: %s " " State: %s, ms: %s", entry['switch_name'], entry['state'], entry['ms']) if entry['return_info']: entry['callback'](switch_name=entry['switch_name'], state=entry['state'], ms=entry['ms'], **entry['callback_kwargs']) else: entry['callback'](**entry['callback_kwargs']) del self.active_timed_switches[k] # The MIT License (MIT) # Copyright (c) 2013-2015 Brian Madden and Gabe Knuth # 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.
spierepf/mpf
mpf/system/switch_controller.py
Python
mit
26,529
# Amara, universalsubtitles.org # # Copyright (C) 2018 Participatory Culture Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see # http://www.gnu.org/licenses/agpl-3.0.html. import re import textwrap from django.conf import settings from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from lxml import html from auth.models import CustomUser as User from messages.models import Message, SYSTEM_NOTIFICATION from utils.enum import Enum from utils.taskqueue import job Notifications = Enum('Notifications', [ ('ROLE_CHANGED', _('Role changed')), ('TEAM_INVITATION', _('Team invitation')), ]) def notify_users(notification, user_list, subject, template_name, context, send_email=None): """ Send notification messages to a list of users Arguments: notification: member from the Notifications enum user_list: list/iterable of CustomUser objects to notify template_name: template to render the notification with context: context dict to use for the 2 templates send_email: Should we send an email alongside the message? Use True/False to force an email to be sent or not sent. None, the default means use the notify_by_email flag from CustomUser. Note that we use the same template to render both the HTML and plaintext version of the message. Here's the system we use to make this work. - Templates are written in simplified HTML - The only block-level tags supported are <p>, <ul>, and <li> - The only inline tags supported are <a>, <em>, and <strong> - For <a> tags make sure to use the {% universal_url %} tag or filter """ message = _render_message_template(subject, template_name, context, 'text') html_message = _render_message_template(subject, template_name, context, 'html') do_notify_users.delay(notification, [u.id for u in user_list], subject, message, html_message, send_email) @job def do_notify_users(notification, user_ids, subject, message, html_message, send_email): user_list = User.objects.filter(id__in=user_ids) for user in user_list: if not user.is_active: continue if should_send_email(user, send_email): send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email], html_message=html_message) if user.notify_by_message: Message.objects.create(user=user, subject=subject, message_type=SYSTEM_NOTIFICATION, content=html_message, html_formatted=True) def should_send_email(user, send_email): """ Logic to decide if we should send an email to the user for notify_users() """ return (user.email and (send_email == True or send_email is None and user.notify_by_email)) def _render_message_template(subject, template_name, context, mode): source = render_to_string(template_name, context) if mode == 'html': return format_html_message(subject, source) else: return format_text_message(subject, source) def format_html_message(subject, source): return render_to_string('messages/html-email.html', { 'subject': subject, 'body': source, }) def format_text_message(subject, source): return TextEmailRenderer(source).text class TextEmailRenderer(object): """ Handles converting the HTML emails to plaintext """ def __init__(self, source): self.parts = [] self.process_source(source) self.text = ''.join(self.parts) def process_source(self, source): tree = html.fragment_fromstring(source, create_parent=True) self.check_no_text(tree.text) for i, elt in enumerate(tree): if i > 0: self.parts.append('\n') # extra newline to separate paragraphs self.process_blocklevel(elt) def process_blocklevel(self, elt): self.check_no_text(elt.tail) if elt.tag == 'p': self.process_inline_text(elt) self.parts.append('\n') elif elt.tag == 'ul': self.process_list(elt) def process_inline_text(self, elt): inline_parts = [] if elt.text: inline_parts.append(elt.text) for child in elt: if child.tag == 'a': inline_parts.append(self.format_link(child)) else: raise ValueError( "Don't know how to process inline {} " "elements for the plaintext email".format(child.tag)) if child.tail: inline_parts.append(child.tail) self.parts.append(textwrap.fill( ''.join(inline_parts), 70)) def process_list(self, elt): for child in elt: if child.tag == 'li': self.parts.append(' - ') self.process_inline_text(child) self.parts.append('\n') else: raise ValueError( "Invalid ul child: {}".format(elt.tag)) def format_link(self, elt): return '{} ({})'.format(elt.text, elt.get('href')) def check_no_text(self, text_or_tail): if text_or_tail and not text_or_tail.isspace(): raise ValueError( "Can't process text outside <p> tags for the " "plaintext email: {}".format(text_or_tail))
pculture/unisubs
apps/messages/notify.py
Python
agpl-3.0
6,266
import logging from autotest.client.shared import error from autotest.client import utils @error.context_aware def run_timerdevice_tscwrite(test, params, env): """ Timer device tscwrite test: 1) Check for an appropriate clocksource on host. 2) Boot the guest. 3) Download and compile the newest msr-tools. 4) Execute cmd in guest. @param test: QEMU test object. @param params: Dictionary with test parameters. @param env: Dictionary with the test environment. """ error.context("Check for an appropriate clocksource on host", logging.info) host_cmd = "cat /sys/devices/system/clocksource/" host_cmd += "clocksource0/current_clocksource" if not "tsc" in utils.system_output(host_cmd): raise error.TestNAError("Host must use 'tsc' clocksource") error.context("Boot the guest", logging.info) vm = env.get_vm(params["main_vm"]) vm.verify_alive() timeout = int(params.get("login_timeout", 360)) session = vm.wait_for_login(timeout=timeout) error.context("Download and compile the newest msr-tools", logging.info) msr_tools_install_cmd = params["msr_tools_install_cmd"] session.cmd(msr_tools_install_cmd) error.context("Execute cmd in guest", logging.info) cmd = "dmesg -c > /dev/null" session.cmd(cmd) date_cmd = "strace date 2>&1 | egrep 'clock_gettime|gettimeofday' | wc -l" output = session.cmd(date_cmd) if not '0' in output: raise error.TestFail("Test failed before run msr tools." " Output: '%s'" % output) msr_tools_cmd = params["msr_tools_cmd"] session.cmd(msr_tools_cmd) cmd = "dmesg" session.cmd(cmd) output = session.cmd(date_cmd) if not "1" in output: raise error.TestFail("Test failed after run msr tools." " Output: '%s'" % output)
sathnaga/virt-test
qemu/tests/timerdevice_tscwrite.py
Python
gpl-2.0
1,871
#!/usr/bin/env python """ This example shows how to create a zip file in python using the built in python module 'zipfile' References: - https://stackoverflow.com/questions/1855095/how-to-create-a-zip-archive-of-a-directory """ import zipfile zipfile_handle = zipfile.ZipFile('/tmp/demo.zip', 'w', zipfile.ZIP_DEFLATED) # add a file to the archive, name in the archive will be the full # name of the file zipfile_handle.write("/etc/passwd") # add a file with a different name zipfile_handle.write( filename="/etc/group", arcname="this_is_groups", ) # add a string as content # TBD zipfile_handle.close()
veltzer/demos-python
src/examples/short/zipfile/create_zip_simple.py
Python
gpl-3.0
624
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class StandardReply(Document): pass
gangadharkadam/letzfrappe
frappe/email/doctype/standard_reply/standard_reply.py
Python
mit
257
from datetime import date from django import db from django import forms from django.forms.models import modelform_factory, ModelChoiceField from django.conf import settings from django.test import TestCase from models import Person, RealPerson, Triple, FilePathModel, Article, \ Publication, CustomFF, Author, Author1, Homepage class ModelMultipleChoiceFieldTests(TestCase): def setUp(self): self.old_debug = settings.DEBUG settings.DEBUG = True def tearDown(self): settings.DEBUG = self.old_debug def test_model_multiple_choice_number_of_queries(self): """ Test that ModelMultipleChoiceField does O(1) queries instead of O(n) (#10156). """ for i in range(30): Person.objects.create(name="Person %s" % i) db.reset_queries() f = forms.ModelMultipleChoiceField(queryset=Person.objects.all()) selected = f.clean([1, 3, 5, 7, 9]) self.assertEquals(len(db.connection.queries), 1) class TripleForm(forms.ModelForm): class Meta: model = Triple class UniqueTogetherTests(TestCase): def test_multiple_field_unique_together(self): """ When the same field is involved in multiple unique_together constraints, we need to make sure we don't remove the data for it before doing all the validation checking (not just failing after the first one). """ Triple.objects.create(left=1, middle=2, right=3) form = TripleForm({'left': '1', 'middle': '2', 'right': '3'}) self.failIf(form.is_valid()) form = TripleForm({'left': '1', 'middle': '3', 'right': '1'}) self.failUnless(form.is_valid()) class TripleFormWithCleanOverride(forms.ModelForm): class Meta: model = Triple def clean(self): if not self.cleaned_data['left'] == self.cleaned_data['right']: raise forms.ValidationError('Left and right should be equal') return self.cleaned_data class OverrideCleanTests(TestCase): def test_override_clean(self): """ Regression for #12596: Calling super from ModelForm.clean() should be optional. """ form = TripleFormWithCleanOverride({'left': 1, 'middle': 2, 'right': 1}) self.failUnless(form.is_valid()) # form.instance.left will be None if the instance was not constructed # by form.full_clean(). self.assertEquals(form.instance.left, 1) # Regression test for #12960. # Make sure the cleaned_data returned from ModelForm.clean() is applied to the # model instance. class PublicationForm(forms.ModelForm): def clean(self): self.cleaned_data['title'] = self.cleaned_data['title'].upper() return self.cleaned_data class Meta: model = Publication class ModelFormCleanTest(TestCase): def test_model_form_clean_applies_to_model(self): data = {'title': 'test', 'date_published': '2010-2-25'} form = PublicationForm(data) publication = form.save() self.assertEqual(publication.title, 'TEST') class FPForm(forms.ModelForm): class Meta: model = FilePathModel class FilePathFieldTests(TestCase): def test_file_path_field_blank(self): """ Regression test for #8842: FilePathField(blank=True) """ form = FPForm() names = [p[1] for p in form['path'].field.choices] names.sort() self.assertEqual(names, ['---------', '__init__.py', 'models.py', 'tests.py']) class ManyToManyCallableInitialTests(TestCase): def test_callable(self): "Regression for #10349: A callable can be provided as the initial value for an m2m field" # Set up a callable initial value def formfield_for_dbfield(db_field, **kwargs): if db_field.name == 'publications': kwargs['initial'] = lambda: Publication.objects.all().order_by('date_published')[:2] return db_field.formfield(**kwargs) # Set up some Publications to use as data Publication(title="First Book", date_published=date(2007,1,1)).save() Publication(title="Second Book", date_published=date(2008,1,1)).save() Publication(title="Third Book", date_published=date(2009,1,1)).save() # Create a ModelForm, instantiate it, and check that the output is as expected ModelForm = modelform_factory(Article, formfield_callback=formfield_for_dbfield) form = ModelForm() self.assertEquals(form.as_ul(), u"""<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="100" /></li> <li><label for="id_publications">Publications:</label> <select multiple="multiple" name="publications" id="id_publications"> <option value="1" selected="selected">First Book</option> <option value="2" selected="selected">Second Book</option> <option value="3">Third Book</option> </select> Hold down "Control", or "Command" on a Mac, to select more than one.</li>""") class CFFForm(forms.ModelForm): class Meta: model = CustomFF class CustomFieldSaveTests(TestCase): def test_save(self): "Regression for #11149: save_form_data should be called only once" # It's enough that the form saves without error -- the custom save routine will # generate an AssertionError if it is called more than once during save. form = CFFForm(data = {'f': None}) form.save() class ModelChoiceIteratorTests(TestCase): def test_len(self): class Form(forms.ModelForm): class Meta: model = Article fields = ["publications"] Publication.objects.create(title="Pravda", date_published=date(1991, 8, 22)) f = Form() self.assertEqual(len(f.fields["publications"].choices), 1) class RealPersonForm(forms.ModelForm): class Meta: model = RealPerson class CustomModelFormSaveMethod(TestCase): def test_string_message(self): data = {'name': 'anonymous'} form = RealPersonForm(data) self.assertEqual(form.is_valid(), False) self.assertEqual(form.errors['__all__'], ['Please specify a real name.']) class ModelClassTests(TestCase): def test_no_model_class(self): class NoModelModelForm(forms.ModelForm): pass self.assertRaises(ValueError, NoModelModelForm) class OneToOneFieldTests(TestCase): def test_assignment_of_none(self): class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['publication', 'full_name'] publication = Publication.objects.create(title="Pravda", date_published=date(1991, 8, 22)) author = Author.objects.create(publication=publication, full_name='John Doe') form = AuthorForm({'publication':u'', 'full_name':'John Doe'}, instance=author) self.assert_(form.is_valid()) self.assertEqual(form.cleaned_data['publication'], None) author = form.save() # author object returned from form still retains original publication object # that's why we need to retreive it from database again new_author = Author.objects.get(pk=author.pk) self.assertEqual(new_author.publication, None) def test_assignment_of_none_null_false(self): class AuthorForm(forms.ModelForm): class Meta: model = Author1 fields = ['publication', 'full_name'] publication = Publication.objects.create(title="Pravda", date_published=date(1991, 8, 22)) author = Author1.objects.create(publication=publication, full_name='John Doe') form = AuthorForm({'publication':u'', 'full_name':'John Doe'}, instance=author) self.assert_(not form.is_valid()) class ModelChoiceForm(forms.Form): person = ModelChoiceField(Person.objects.all()) class TestTicket11183(TestCase): def test_11183(self): form1 = ModelChoiceForm() field1 = form1.fields['person'] # To allow the widget to change the queryset of field1.widget.choices correctly, # without affecting other forms, the following must hold: self.assert_(field1 is not ModelChoiceForm.base_fields['person']) self.assert_(field1.widget.choices.field is field1) class HomepageForm(forms.ModelForm): class Meta: model = Homepage class URLFieldTests(TestCase): def test_url_on_modelform(self): "Check basic URL field validation on model forms" self.assertFalse(HomepageForm({'url': 'foo'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://example'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://example.'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://com.'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://localhost'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://example.com'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com/test'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000/test'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://example.com/foo/bar'}).is_valid()) def test_http_prefixing(self): "If the http:// prefix is omitted on form input, the field adds it again. (Refs #13613)" form = HomepageForm({'url': 'example.com'}) form.is_valid() # self.assertTrue(form.is_valid()) # self.assertEquals(form.cleaned_data['url'], 'http://example.com/') form = HomepageForm({'url': 'example.com/test'}) form.is_valid() # self.assertTrue(form.is_valid()) # self.assertEquals(form.cleaned_data['url'], 'http://example.com/test') class FormFieldCallbackTests(TestCase): def test_baseform_with_widgets_in_meta(self): """Regression for #13095: Using base forms with widgets defined in Meta should not raise errors.""" widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {'name': widget} Form = modelform_factory(Person, form=BaseForm) self.assertTrue(Form.base_fields['name'].widget is widget) def test_custom_callback(self): """Test that a custom formfield_callback is used if provided""" callback_args = [] def callback(db_field, **kwargs): callback_args.append((db_field, kwargs)) return db_field.formfield(**kwargs) widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {'name': widget} _ = modelform_factory(Person, form=BaseForm, formfield_callback=callback) id_field, name_field = Person._meta.fields self.assertEqual(callback_args, [(id_field, {}), (name_field, {'widget': widget})]) def test_bad_callback(self): # A bad callback provided by user still gives an error self.assertRaises(TypeError, modelform_factory, Person, formfield_callback='not a function or callable')
andim27/magiccamp
tests/regressiontests/model_forms_regress/tests.py
Python
bsd-3-clause
11,548
# Processes Damped Harmonic Motion From a Logger Pro Utility # # Copyright (c) 2016 George L. # # # import sys print("Processor Copyright (c) 2016 George L.\n") THRESHOLD = int(input("what is your equilibuium position?: ")) NUM = int(input("how many types of data in one run?: ")) TOL = float(input("What is your tolerance for the microfluxuations in current? (recommended: .005): ")) #Opens the file if len(sys.argv) == 2: raw = open(sys.argv[1],"r") else: raw = open("data.csv","r") #Checks headers for how many runs headers = raw.readline().split(",") header = headers[:NUM] sets = int(len(headers)/NUM) #sanity check print("Sets of data: "+str(sets)) #First pass of processing #[row][coloumn] pass1 = [] for i,l in enumerate(raw): temp = l.replace("\n","") pass1.append([float("0" if len(x) == 0 else x) for x in temp.split(",")]) #print(pass1) #Second pass of processing #[row][set][member of set] pass2 = [[[] for y in range(sets)] for x in range(len(pass1))] for i,l in enumerate(pass1): for j in range(sets): pass2[i][j] = l[NUM*j:NUM*(j+1)] #Initializes maximum list #[set of data][Nth maximum] maximums = [ [] for i in range(sets) ] #for finding acceleration accel = lambda x : x[4] if len(x) > 4 else 0 #for finding position pos = lambda x : x[2] if len(x) > 2 else 0 #for finding current cur = lambda x : x[1] if len(x) > 1 else 0 callb = cur #for checking inequalities def posToNeg(a,b,callback,threshold = 0): return callback(a) > threshold and callback(b) < threshold def negToPos(a,b,callback,threshold = 0): return posToNeg(b,a,callback,threshold) #for finding the maximum in the set findMax = lambda x : sorted(x,key=callb)[-1] #for processing each set for i in range(sets): #last - the last data point last = [] #the interval interval = [] #some flags crossedOnce = False collecting = False processing = False for j,l in enumerate(pass2): #sets current set setN = l[i] #initialized so there's no errors if j == 0: last = setN #if you haven't crossed once, wait until you do if not crossedOnce: if negToPos(last,setN,callb,THRESHOLD): crossedOnce = True #if you've crossed once if crossedOnce: #if you went from negative to positive if negToPos(last,setN,callb,THRESHOLD): collecting = True processing = False #if you went from positive to negative if posToNeg(last,setN,callb,THRESHOLD): collecting = False processing = True #collects data if collecting: interval.append(setN) #processes the collected data if processing: maximums[i].append(findMax(interval[:])[:]) del interval[:] collecting = True processing = False last = setN print("init sorting done") #Checks for points that don't clear tolerance and removes them maximums2 = [ [] for i in range(sets) ] for i in range(len(maximums)): for x in maximums[i]: if callb(x) > TOL: maximums2[i].append(x) maximums = maximums2[:] #print(maximums) #print(header) #output to a file for each set for i in range(len(maximums)): name = "%s-run%1d-processed.csv"%("data" if len(sys.argv) != 2 else sys.argv[1][:-4],i+1) out = open(name,"w") #outputs header out.write(",".join(header).replace("1","%d"%(i+1))) #outputs data for j,l in enumerate(maximums[i]): temp = ",".join([str(x) for x in l])+"\n" out.write(temp) out.close() input("done")
TheToppestKek/DHM-Data-Processor
Processor.py
Python
gpl-3.0
3,749
# -*- coding: utf-8 -*- import pytest from mitmproxy.test import tutils from mitmproxy.net import http def _test_passthrough_attr(message, attr): assert getattr(message, attr) == getattr(message.data, attr) setattr(message, attr, b"foo") assert getattr(message.data, attr) == b"foo" def _test_decoded_attr(message, attr): assert getattr(message, attr) == getattr(message.data, attr).decode("utf8") # Set str, get raw bytes setattr(message, attr, "foo") assert getattr(message.data, attr) == b"foo" # Set raw bytes, get decoded setattr(message.data, attr, b"BAR") # use uppercase so that we can also cover request.method assert getattr(message, attr) == "BAR" # Set bytes, get raw bytes setattr(message, attr, b"baz") assert getattr(message.data, attr) == b"baz" # Set UTF8 setattr(message, attr, "Non-Autorisé") assert getattr(message.data, attr) == b"Non-Autoris\xc3\xa9" # Don't fail on garbage setattr(message.data, attr, b"FOO\xBF\x00BAR") assert getattr(message, attr).startswith("FOO") assert getattr(message, attr).endswith("BAR") # foo.bar = foo.bar should not cause any side effects. d = getattr(message, attr) setattr(message, attr, d) assert getattr(message.data, attr) == b"FOO\xBF\x00BAR" class TestMessageData: def test_eq_ne(self): data = tutils.tresp(timestamp_start=42, timestamp_end=42).data same = tutils.tresp(timestamp_start=42, timestamp_end=42).data assert data == same assert not data != same other = tutils.tresp(content=b"foo").data assert not data == other assert data != other assert data != 0 class TestMessage: def test_init(self): resp = tutils.tresp() assert resp.data def test_eq_ne(self): resp = tutils.tresp(timestamp_start=42, timestamp_end=42) same = tutils.tresp(timestamp_start=42, timestamp_end=42) assert resp == same assert not resp != same other = tutils.tresp(timestamp_start=0, timestamp_end=0) assert not resp == other assert resp != other assert resp != 0 def test_serializable(self): resp = tutils.tresp() resp2 = http.Response.from_state(resp.get_state()) assert resp == resp2 def test_content_length_update(self): resp = tutils.tresp() resp.content = b"foo" assert resp.data.content == b"foo" assert resp.headers["content-length"] == "3" resp.content = b"" assert resp.data.content == b"" assert resp.headers["content-length"] == "0" resp.raw_content = b"bar" assert resp.data.content == b"bar" assert resp.headers["content-length"] == "0" def test_headers(self): _test_passthrough_attr(tutils.tresp(), "headers") def test_timestamp_start(self): _test_passthrough_attr(tutils.tresp(), "timestamp_start") def test_timestamp_end(self): _test_passthrough_attr(tutils.tresp(), "timestamp_end") def test_http_version(self): _test_decoded_attr(tutils.tresp(), "http_version") def test_replace(self): r = tutils.tresp() r.content = b"foofootoo" r.replace(b"foo", "gg") assert r.content == b"ggggtoo" r.content = b"foofootoo" r.replace(b"foo", "gg", count=1) assert r.content == b"ggfootoo" class TestMessageContentEncoding: def test_simple(self): r = tutils.tresp() assert r.raw_content == b"message" assert "content-encoding" not in r.headers r.encode("gzip") assert r.headers["content-encoding"] assert r.raw_content != b"message" assert r.content == b"message" assert r.raw_content != b"message" def test_modify(self): r = tutils.tresp() assert "content-encoding" not in r.headers r.encode("gzip") r.content = b"foo" assert r.raw_content != b"foo" r.decode() assert r.raw_content == b"foo" with pytest.raises(TypeError): r.content = u"foo" def test_unknown_ce(self): r = tutils.tresp() r.headers["content-encoding"] = "zopfli" r.raw_content = b"foo" with pytest.raises(ValueError): assert r.content assert r.headers["content-encoding"] assert r.get_content(strict=False) == b"foo" def test_utf8_as_ce(self): r = tutils.tresp() r.headers["content-encoding"] = "utf8" r.raw_content = b"foo" with pytest.raises(ValueError): assert r.content assert r.headers["content-encoding"] assert r.get_content(strict=False) == b"foo" def test_cannot_decode(self): r = tutils.tresp() r.encode("gzip") r.raw_content = b"foo" with pytest.raises(ValueError): assert r.content assert r.headers["content-encoding"] assert r.get_content(strict=False) == b"foo" with pytest.raises(ValueError): r.decode() assert r.raw_content == b"foo" assert "content-encoding" in r.headers r.decode(strict=False) assert r.content == b"foo" assert "content-encoding" not in r.headers def test_none(self): r = tutils.tresp(content=None) assert r.content is None r.content = b"foo" assert r.content is not None r.content = None assert r.content is None def test_cannot_encode(self): r = tutils.tresp() r.encode("gzip") r.content = None assert r.headers["content-encoding"] assert r.raw_content is None r.headers["content-encoding"] = "zopfli" r.content = b"foo" assert "content-encoding" not in r.headers assert r.raw_content == b"foo" with pytest.raises(ValueError): r.encode("zopfli") assert r.raw_content == b"foo" assert "content-encoding" not in r.headers class TestMessageText: def test_simple(self): r = tutils.tresp(content=b'\xfc') assert r.raw_content == b"\xfc" assert r.content == b"\xfc" assert r.text == u"ü" r.encode("gzip") assert r.text == u"ü" r.decode() assert r.text == u"ü" r.headers["content-type"] = "text/html; charset=latin1" r.content = b"\xc3\xbc" assert r.text == u"ü" r.headers["content-type"] = "text/html; charset=utf8" assert r.text == u"ü" def test_guess_json(self): r = tutils.tresp(content=b'"\xc3\xbc"') r.headers["content-type"] = "application/json" assert r.text == u'"ü"' def test_none(self): r = tutils.tresp(content=None) assert r.text is None r.text = u"foo" assert r.text is not None r.text = None assert r.text is None def test_modify(self): r = tutils.tresp() r.text = u"ü" assert r.raw_content == b"\xfc" r.headers["content-type"] = "text/html; charset=utf8" r.text = u"ü" assert r.raw_content == b"\xc3\xbc" assert r.headers["content-length"] == "2" def test_unknown_ce(self): r = tutils.tresp() r.headers["content-type"] = "text/html; charset=wtf" r.raw_content = b"foo" with pytest.raises(ValueError): assert r.text == u"foo" assert r.get_text(strict=False) == u"foo" def test_cannot_decode(self): r = tutils.tresp() r.headers["content-type"] = "text/html; charset=utf8" r.raw_content = b"\xFF" with pytest.raises(ValueError): assert r.text assert r.get_text(strict=False) == '\udcff' def test_cannot_encode(self): r = tutils.tresp() r.content = None assert "content-type" not in r.headers assert r.raw_content is None r.headers["content-type"] = "text/html; charset=latin1; foo=bar" r.text = u"☃" assert r.headers["content-type"] == "text/html; charset=utf-8; foo=bar" assert r.raw_content == b'\xe2\x98\x83' r.headers["content-type"] = "gibberish" r.text = u"☃" assert r.headers["content-type"] == "text/plain; charset=utf-8" assert r.raw_content == b'\xe2\x98\x83' del r.headers["content-type"] r.text = u"☃" assert r.headers["content-type"] == "text/plain; charset=utf-8" assert r.raw_content == b'\xe2\x98\x83' r.headers["content-type"] = "text/html; charset=latin1" r.text = u'\udcff' assert r.headers["content-type"] == "text/html; charset=utf-8" assert r.raw_content == b"\xFF"
mosajjal/mitmproxy
test/mitmproxy/net/http/test_message.py
Python
mit
8,776
from .variables import * from . import armadillo as arma def Get(node): if len(node) != 1: if not len(node): node.error("Zero arguments in a vec call") return "%(name)s()" elif len(node) == 2 and node[1].cls == "Int" and node[1].value == "1": pass #special case hh = h0F(:,ones(1,M)) with h0F vec, and ones elif len(node) == 2 and node[0].name == "ones" or \ node[1].name == "ones": out = "%(name)s(" if node[0].name == "ones": out = out + "%(0)s-1, " #return "%(name)s(%(0)s-1, %(1)s)" else: out = out + "%(0)s, " if node[1].name == "ones": out = out + "%(1)s-1)" #return "%(name)s(%(0)s, %(1)s-1)" else: out = out + "%(1)s)" return out else: node.error("More than one arguments in a vec call") return "%(name)s(", ", ", ")" #if len(node) == 1: arg, dim = arma.configure_arg(node[0], 0) if dim == -1: return "%(name)s(", "-1, ", "-1)" #if dim == 0: # node.dim = 0 return "%(name)s(" + arg + ")" """ elif len(node) == 2: arg0, dim0 = arma.configure_arg(node[0], 0) arg1, dim1 = arma.configure_arg(node[1], 1) if dim0 == -1: return "%(name)s(", "-1, ", "-1)" elif dim1 == -1: return "%(name)s(", "-1, ", "-1)" #if dim == 0: # node.dim = 0 return "%(name)s(" + arg0 + ", " + arg1 + ")" """ def Set(node): if len(node) != 1: if not len(node): node.error("Zero arguments in a vec call") return "%(name)s()" elif len(node) == 2 and node[1].cls == "Int" and node[1].value == "1": pass else: node.error("More than one arguments in a vec call") return "%(name)s(", "-1, ", "-1)" arg, dim = arma.configure_arg(node[0], 0) if dim == -1: return "%(name)s(", "-1, ", "-1)" #if dim == 0: # node.dim = 0 return "%(name)s(" + arg + ")"
jonathf/matlab2cpp
src/matlab2cpp/rules/vec.py
Python
bsd-3-clause
2,188
#!/usr/bin/python # Copyright 2003 Dave Abrahams # Copyright 2003, 2006 Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # Test main target alternatives. import BoostBuild import string t = BoostBuild.Tester(use_test_config=False) # Test that basic alternatives selection works. t.write("jamroot.jam", "") t.write("jamfile.jam", """ exe a : a_empty.cpp ; exe a : a.cpp : <variant>release ; """) t.write("a_empty.cpp", "") t.write("a.cpp", "int main() {}\n") t.run_build_system(["release"]) t.expect_addition("bin/$toolset/release/a.exe") # Test that alternative selection works for ordinary properties, in particular # user-defined. t.write("jamroot.jam", "") t.write("jamfile.jam", """ import feature ; feature.feature X : off on : propagated ; exe a : b.cpp ; exe a : a.cpp : <X>on ; """) t.write("b.cpp", "int main() {}\n") t.rm("bin") t.run_build_system() t.expect_addition("bin/$toolset/debug/b.obj") t.run_build_system(["X=on"]) t.expect_addition("bin/$toolset/debug/X-on/a.obj") t.rm("bin") # Test that everything works ok even with the default build. t.write("jamfile.jam", """\ exe a : a_empty.cpp : <variant>release ; exe a : a.cpp : <variant>debug ; """) t.run_build_system() t.expect_addition("bin/$toolset/debug/a.exe") # Test that only properties which are in the build request matter for # alternative selection. IOW, alternative with <variant>release is better than # one with <variant>debug when building the release variant. t.write("jamfile.jam", """\ exe a : a_empty.cpp : <variant>debug ; exe a : a.cpp : <variant>release ; """) t.run_build_system(["release"]) t.expect_addition("bin/$toolset/release/a.exe") # Test that free properties do not matter. We really do not want <cxxflags> # property in build request to affect alternative selection. t.write("jamfile.jam", """ exe a : a_empty.cpp : <variant>debug <define>FOO <include>BAR ; exe a : a.cpp : <variant>release ; """) t.rm("bin/$toolset/release/a.exe") t.run_build_system(["release", "define=FOO"]) t.expect_addition("bin/$toolset/release/a.exe") # Test that ambiguity is reported correctly. t.write("jamfile.jam", """\ exe a : a_empty.cpp ; exe a : a.cpp ; """) t.run_build_system(["--no-error-backtrace"], status=None) t.fail_test(string.find(t.stdout(), "No best alternative") == -1) # Another ambiguity test: two matches properties in one alternative are neither # better nor worse than a single one in another alternative. t.write("jamfile.jam", """\ exe a : a_empty.cpp : <optimization>off <profiling>off ; exe a : a.cpp : <debug-symbols>on ; """) t.run_build_system(["--no-error-backtrace"], status=None) t.fail_test(string.find(t.stdout(), "No best alternative") == -1) # Test that we can have alternative without sources. t.write("jamfile.jam", """\ alias specific-sources ; import feature ; feature.extend os : MAGIC ; alias specific-sources : b.cpp : <os>MAGIC ; exe a : a.cpp specific-sources ; """) t.rm("bin") t.run_build_system() t.cleanup()
NixaSoftware/CVis
venv/bin/tools/build/v2/test/alternatives.py
Python
apache-2.0
3,072
import datetime import json import platform def get_platform(): """ Utility function for determining the current operating system. """ return 'macos' if platform.uname().system == 'Darwin' else 'windows' class DatetimeEncoder(json.JSONEncoder): """ Converts a python object, where datetime and timedelta objects are converted into objects that can be decoded using the DatetimeDecoder. """ def default(self, obj): if isinstance(obj, datetime.datetime): return { '__type__': 'datetime', 'year': obj.year, 'month': obj.month, 'day': obj.day, 'hour': obj.hour, 'minute': obj.minute, 'second': obj.second, 'microsecond': obj.microsecond, } elif isinstance(obj, datetime.timedelta): return { '__type__': 'timedelta', 'days': obj.days, 'seconds': obj.seconds, 'microseconds': obj.microseconds, } else: return json.JSONEncoder.default(self, obj) class DatetimeDecoder(json.JSONDecoder): """ Converts a json string, where datetime and timedelta objects were converted into objects using the DatetimeEncoder, back into a python object. """ def __init__(self): json.JSONDecoder.__init__(self, object_hook=self.dict_to_object) def dict_to_object(self, d): if '__type__' not in d: return d type = d.pop('__type__') if type == 'datetime': return datetime.datetime(**d) elif type == 'timedelta': return datetime.timedelta(**d) else: # Oops... better put this back together. d['__type__'] = type return d
VISTAS-IVES/pyvistas
source/vistas/core/utils.py
Python
bsd-3-clause
1,836
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .resource import Resource class VirtualNetworkGateway(Resource): """A common class for general resource information. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param ip_configurations: IP configurations for virtual network gateway. :type ip_configurations: list[~azure.mgmt.network.v2017_06_01.models.VirtualNetworkGatewayIPConfiguration] :param gateway_type: The type of this virtual network gateway. Possible values are: 'Vpn' and 'ExpressRoute'. Possible values include: 'Vpn', 'ExpressRoute' :type gateway_type: str or ~azure.mgmt.network.v2017_06_01.models.VirtualNetworkGatewayType :param vpn_type: The type of this virtual network gateway. Possible values are: 'PolicyBased' and 'RouteBased'. Possible values include: 'PolicyBased', 'RouteBased' :type vpn_type: str or ~azure.mgmt.network.v2017_06_01.models.VpnType :param enable_bgp: Whether BGP is enabled for this virtual network gateway or not. :type enable_bgp: bool :param active_active: ActiveActive flag :type active_active: bool :param gateway_default_site: The reference of the LocalNetworkGateway resource which represents local network site having default routes. Assign Null value in case of removing existing default site setting. :type gateway_default_site: ~azure.mgmt.network.v2017_06_01.models.SubResource :param sku: The reference of the VirtualNetworkGatewaySku resource which represents the SKU selected for Virtual network gateway. :type sku: ~azure.mgmt.network.v2017_06_01.models.VirtualNetworkGatewaySku :param vpn_client_configuration: The reference of the VpnClientConfiguration resource which represents the P2S VpnClient configurations. :type vpn_client_configuration: ~azure.mgmt.network.v2017_06_01.models.VpnClientConfiguration :param bgp_settings: Virtual network gateway's BGP speaker settings. :type bgp_settings: ~azure.mgmt.network.v2017_06_01.models.BgpSettings :param resource_guid: The resource GUID property of the VirtualNetworkGateway resource. :type resource_guid: str :ivar provisioning_state: The provisioning state of the VirtualNetworkGateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :vartype provisioning_state: str :param etag: Gets a unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'provisioning_state': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[VirtualNetworkGatewayIPConfiguration]'}, 'gateway_type': {'key': 'properties.gatewayType', 'type': 'str'}, 'vpn_type': {'key': 'properties.vpnType', 'type': 'str'}, 'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'}, 'active_active': {'key': 'properties.activeActive', 'type': 'bool'}, 'gateway_default_site': {'key': 'properties.gatewayDefaultSite', 'type': 'SubResource'}, 'sku': {'key': 'properties.sku', 'type': 'VirtualNetworkGatewaySku'}, 'vpn_client_configuration': {'key': 'properties.vpnClientConfiguration', 'type': 'VpnClientConfiguration'}, 'bgp_settings': {'key': 'properties.bgpSettings', 'type': 'BgpSettings'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, *, id: str=None, location: str=None, tags=None, ip_configurations=None, gateway_type=None, vpn_type=None, enable_bgp: bool=None, active_active: bool=None, gateway_default_site=None, sku=None, vpn_client_configuration=None, bgp_settings=None, resource_guid: str=None, etag: str=None, **kwargs) -> None: super(VirtualNetworkGateway, self).__init__(id=id, location=location, tags=tags, **kwargs) self.ip_configurations = ip_configurations self.gateway_type = gateway_type self.vpn_type = vpn_type self.enable_bgp = enable_bgp self.active_active = active_active self.gateway_default_site = gateway_default_site self.sku = sku self.vpn_client_configuration = vpn_client_configuration self.bgp_settings = bgp_settings self.resource_guid = resource_guid self.provisioning_state = None self.etag = etag
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_06_01/models/virtual_network_gateway_py3.py
Python
mit
5,611
#!/usr/bin/python3 """Sorts input lines by order of decreasing line length. Read std input, then emit output lines in decreasing/increasing order of line length. """ from collections import defaultdict import getopt import os import sys import script_utils as u flag_reverse = True def usage(msgarg): """Print usage and exit.""" if msgarg: sys.stderr.write("error: %s\n" % msgarg) print("""\ usage: %s [options] options: -d increase debug msg verbosity level -r reverse send of sort (increasing length) """ % os.path.basename(sys.argv[0])) sys.exit(1) def parse_args(): """Command line argument parsing.""" global flag_reverse try: optlist, _ = getopt.getopt(sys.argv[1:], "dr") except getopt.GetoptError as err: # unrecognized option usage(str(err)) for opt, _ in optlist: if opt == "-d": u.increment_verbosity() elif opt == "-r": flag_reverse = False # Setup u.setdeflanglocale() parse_args() # Read d = defaultdict(list) lines = sys.stdin.readlines() for line in lines: ll = len(line) d[ll].append(line) # Sort dkeys = list(d.keys()) dkeys.sort(reverse=flag_reverse) # Output for idx in dkeys: llist = d[idx] for ln in llist: sys.stdout.write(ln)
thanm/devel-scripts
llsort.py
Python
apache-2.0
1,262
""" LTI Provider view functions """ from __future__ import absolute_import import logging import six from django.conf import settings from django.http import Http404, HttpResponseBadRequest, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey, UsageKey from lti_provider.models import LtiConsumer from lti_provider.outcomes import store_outcome_parameters from lti_provider.signature_validator import SignatureValidator from lti_provider.users import authenticate_lti_user from openedx.core.lib.url_utils import unquote_slashes from util.views import add_p3p_header log = logging.getLogger("edx.lti_provider") # LTI launch parameters that must be present for a successful launch REQUIRED_PARAMETERS = [ 'roles', 'context_id', 'oauth_version', 'oauth_consumer_key', 'oauth_signature', 'oauth_signature_method', 'oauth_timestamp', 'oauth_nonce', 'user_id' ] OPTIONAL_PARAMETERS = [ 'context_title', 'context_label', 'lis_result_sourcedid', 'lis_outcome_service_url', 'tool_consumer_instance_guid' ] @csrf_exempt @add_p3p_header def lti_launch(request, course_id, usage_id): """ Endpoint for all requests to embed edX content via the LTI protocol. This endpoint will be called by a POST message that contains the parameters for an LTI launch (we support version 1.2 of the LTI specification): http://www.imsglobal.org/lti/ltiv1p2/ltiIMGv1p2.html An LTI launch is successful if: - The launch contains all the required parameters - The launch data is correctly signed using a known client key/secret pair """ if not settings.FEATURES['ENABLE_LTI_PROVIDER']: return HttpResponseForbidden() # Check the LTI parameters, and return 400 if any required parameters are # missing params = get_required_parameters(request.POST) if not params: return HttpResponseBadRequest() params.update(get_optional_parameters(request.POST)) # Get the consumer information from either the instance GUID or the consumer # key try: lti_consumer = LtiConsumer.get_or_supplement( params.get('tool_consumer_instance_guid', None), params['oauth_consumer_key'] ) except LtiConsumer.DoesNotExist: return HttpResponseForbidden() # Check the OAuth signature on the message if not SignatureValidator(lti_consumer).verify(request): return HttpResponseForbidden() # Add the course and usage keys to the parameters array try: course_key, usage_key = parse_course_and_usage_keys(course_id, usage_id) except InvalidKeyError: log.error( u'Invalid course key %s or usage key %s from request %s', course_id, usage_id, request ) raise Http404() params['course_key'] = course_key params['usage_key'] = usage_key # Create an edX account if the user identifed by the LTI launch doesn't have # one already, and log the edX account into the platform. authenticate_lti_user(request, params['user_id'], lti_consumer) # Store any parameters required by the outcome service in order to report # scores back later. We know that the consumer exists, since the record was # used earlier to verify the oauth signature. store_outcome_parameters(params, request.user, lti_consumer) return render_courseware(request, params['usage_key']) def get_required_parameters(dictionary, additional_params=None): """ Extract all required LTI parameters from a dictionary and verify that none are missing. :param dictionary: The dictionary that should contain all required parameters :param additional_params: Any expected parameters, beyond those required for the LTI launch. :return: A new dictionary containing all the required parameters from the original dictionary and additional parameters, or None if any expected parameters are missing. """ params = {} additional_params = additional_params or [] for key in REQUIRED_PARAMETERS + additional_params: if key not in dictionary: return None params[key] = dictionary[key] return params def get_optional_parameters(dictionary): """ Extract all optional LTI parameters from a dictionary. This method does not fail if any parameters are missing. :param dictionary: A dictionary containing zero or more optional parameters. :return: A new dictionary containing all optional parameters from the original dictionary, or an empty dictionary if no optional parameters were present. """ return {key: dictionary[key] for key in OPTIONAL_PARAMETERS if key in dictionary} def render_courseware(request, usage_key): """ Render the content requested for the LTI launch. TODO: This method depends on the current refactoring work on the courseware/courseware.html template. It's signature may change depending on the requirements for that template once the refactoring is complete. Return an HttpResponse object that contains the template and necessary context to render the courseware. """ # return an HttpResponse object that contains the template and necessary context to render the courseware. from lms.djangoapps.courseware.views.views import render_xblock return render_xblock(request, six.text_type(usage_key), check_if_enrolled=False) def parse_course_and_usage_keys(course_id, usage_id): """ Convert course and usage ID strings into key objects. Return a tuple of (course_key, usage_key), or throw an InvalidKeyError if the translation fails. """ course_key = CourseKey.from_string(course_id) usage_id = unquote_slashes(usage_id) usage_key = UsageKey.from_string(usage_id).map_into_course(course_key) return course_key, usage_key
ESOedX/edx-platform
lms/djangoapps/lti_provider/views.py
Python
agpl-3.0
5,989
from random import randint from micromouse import maze class Mouse: x = 0 y = 0 maze = [] visited = [] n_distance = 0 e_distance = 0 s_distance = 0 w_distance = 0 def __init__(self, x, y, some_maze): print "Micromouse initialized. Hello world!" self.x = x self.y = y self.maze = some_maze some_maze.map[x][y].visited = True def sensor_read(self, direction): if direction is 'north': self.n_distance = 0 elif direction is 'east': self.e_distance = 1 elif direction is 'south': self.s_distance = 2 elif direction is 'west': self.w_distance = 3 else: print "Usage error: sensor_read(north|east|south|west)" def find_path(self): xn = self.x - 1 ye = self.y + 1 xs = self.x + 1 yw = self.y - 1 n = self.maze.map[xn][self.y] e = self.maze.map[self.x][ye] s = self.maze.map[xs][self.y] w = self.maze.map[self.x][yw] options = [n, e, s, w] best_case = min(n.get_weight(), e.get_weight(), s.get_weight(), w.get_weight()) best_options = [] for i in options: if i.get_weight() is best_case: best_options.append(i) choice = randint(0, len(best_options) - 1) return best_options[choice] def take_path(self, next_cell): self.x = next_cell.x self.y = next_cell.y self.visited.append(next_cell) def get_coordinates(self): return [self.x, self.y] def set_coordinates(self, x, y): self.x = x self.y = y def move_north(self): # Add current coordinates to stack # Move to north cell self.x -= 1 def move_east(self): # Add current coordinates to stack # Move to east cell self.y += 1 def move_south(self): # Add current coordinates to stack # Move to south cell self.x += 1 def move_west(self): # Add current coordinates to stack # Move to west cell self.y -= 1
onu-opensource/micromouse_python
micromouse/mouse.py
Python
mit
2,148