Example #1
1
    def store(cls, sr, account, text=None, css_class=None):
        flair = Flair(sr, account, "flair", text=text, css_class=css_class)
        flair._commit()

        setattr(account, "flair_%s_text" % sr._id, text)
        setattr(account, "flair_%s_css_class" % sr._id, css_class)
        account._commit()
Example #2
1
def make_cache_level(ncaches, prototypes, level, next_cache):
    global next_subsys_index, proto_l1, testerspec, proto_tester

    index = next_subsys_index[level]
    next_subsys_index[level] += 1

    # Create a subsystem to contain the crossbar and caches, and
    # any testers
    subsys = SubSystem()
    setattr(system, "l%dsubsys%d" % (level, index), subsys)

    # The levels are indexing backwards through the list
    ntesters = testerspec[len(cachespec) - level]

    # Scale the progress threshold as testers higher up in the tree
    # (smaller level) get a smaller portion of the overall bandwidth,
    # and also make the interval of packet injection longer for the
    # testers closer to the memory (larger level) to prevent them
    # hogging all the bandwidth
    limit = (len(cachespec) - level + 1) * 100000000
    testers = [proto_tester(interval=10 * (level * level + 1), progress_check=limit) for i in xrange(ntesters)]
    if ntesters:
        subsys.tester = testers

    if level != 0:
        # Create a crossbar and add it to the subsystem, note that
        # we do this even with a single element on this level
        xbar = L2XBar()
        subsys.xbar = xbar
        if next_cache:
            xbar.master = next_cache.cpu_side

        # Create and connect the caches, both the ones fanning out
        # to create the tree, and the ones used to connect testers
        # on this level
        tree_caches = [prototypes[0]() for i in xrange(ncaches[0])]
        tester_caches = [proto_l1() for i in xrange(ntesters)]

        subsys.cache = tester_caches + tree_caches
        for cache in tree_caches:
            cache.mem_side = xbar.slave
            make_cache_level(ncaches[1:], prototypes[1:], level - 1, cache)
        for tester, cache in zip(testers, tester_caches):
            tester.port = cache.cpu_side
            cache.mem_side = xbar.slave
    else:
        if not next_cache:
            print "Error: No next-level cache at top level"
            sys.exit(1)

        if ntesters > 1:
            # Create a crossbar and add it to the subsystem
            xbar = L2XBar()
            subsys.xbar = xbar
            xbar.master = next_cache.cpu_side
            for tester in testers:
                tester.port = xbar.slave
        else:
            # Single tester
            testers[0].port = next_cache.cpu_side
Example #3
1
 def add_variable(self, name, dims, data=None, **kwargs):
     if data is None:
         char = "d"
     else:
         if isinstance(data, np.ndarray):
             char = data.dtype.char
         elif isinstance(data, float):
             char = "d"
         elif isinstance(data, int):
             char = "i"
         else:
             char = "c"
     print(("%-34s %s%s" % (name, char, tuple([self.nc.dimensions[dim] for dim in dims]))))
     var = self.nc.createVariable(name, char, dims)
     for attr, value in kwargs.items():
         setattr(var, attr, value)
     if data is not None:
         if len(dims) == 0:
             var.assignValue(data)
         else:
             if char == "c":
                 if len(dims) == 1:
                     var[: len(data)] = data
                 else:
                     for i, x in enumerate(data):
                         var[i, : len(x)] = x
             else:
                 var[:] = data
     return var
Example #4
1
    def serialize(self, ctx, message):
        assert message in (self.REQUEST, self.RESPONSE)

        self.event_manager.fire_event("before_serialize", ctx)

        if ctx.out_error is not None:
            ctx.out_document = [ctx.out_error.to_dict(ctx.out_error)]

        else:
            # get the result message
            if message is self.REQUEST:
                out_type = ctx.descriptor.in_message
            elif message is self.RESPONSE:
                out_type = ctx.descriptor.out_message
            if out_type is None:
                return

            out_type_info = out_type._type_info

            # instantiate the result message
            out_instance = out_type()

            # assign raw result to its wrapper, result_message
            for i in range(len(out_type_info)):
                attr_name = out_type_info.keys()[i]
                setattr(out_instance, attr_name, ctx.out_object[i])

            ctx.out_document = self._object_to_doc(out_type, out_instance, skip_depth=self.skip_depth)
            self.event_manager.fire_event("after_serialize", ctx)
Example #5
1
 def __init__(self, dictionary):
     self.update(**dictionary)
     for k, v in dictionary.items():
         try:
             setattr(self, k, v)
         except Exception as e:
             pass
Example #6
1
    def add(self, selection_type, selection_subtype, selection_object):
        """Adds a selection item (protein, family, sequence segment etc.) to the selection"""
        # only one reference can be selected at a time, clear the selection
        if selection_type == "reference":
            selection = []
        # for other types, add the selected item
        else:
            selection = getattr(self, selection_type)

        # make sure there is an active group
        if selection_subtype == "site_residue":
            if not self.active_site_residue_group:
                self.active_site_residue_group = 1

            # update selection object with group id
            selection_object.properties["site_residue_group"] = self.active_site_residue_group

        # check whether the selected item is already in the selection
        if selection_object not in selection:  # if not, add it
            # site residue groups
            if selection_subtype == "site_residue":
                if not self.site_residue_groups:
                    self.site_residue_groups = [[]]
                self.site_residue_groups[self.active_site_residue_group - 1].append(1)

            selection.append(selection_object)
            setattr(self, selection_type, selection)
Example #7
0
def make(STRUCT, **fields):
    """ Malloc a structure and populate it's fields
    """
    ptr = lltype.malloc(STRUCT, flavor="raw")
    for name, value in fields.items():
        setattr(ptr, name, value)
    return ptr
Example #8
0
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop("partial", False)
        self.object = self.get_object()

        if self.object is None:
            raise XOSProgrammingError("Use the List API for creating objects")

        serializer = self.get_serializer(self.object, data=request.data, partial=partial)

        if not serializer.is_valid():
            raise XOSValidationError(fields=serializer._errors)

        # Do the XOS perm check

        assert serializer.instance is not None
        obj = serializer.instance
        for attr, value in serializer.validated_data.items():
            setattr(obj, attr, value)
        obj.caller = request.user
        if not obj.can_update(request.user):
            raise XOSPermissionDenied()

        self.perform_update(serializer)

        return Response(serializer.data, status=status.HTTP_200_OK)
def OvfInvalidValueEmpty(vim, *args, **kwargs):
    """If an attribute is found with an empty value where it is not allowed."""

    obj = vim.client.factory.create("{urn:vim25}OvfInvalidValueEmpty")

    # do some validation checking...
    if (len(args) + len(kwargs)) < 8:
        raise IndexError("Expected at least 9 arguments got: %d" % len(args))

    required = [
        "value",
        "attributeName",
        "elementName",
        "lineNumber",
        "dynamicProperty",
        "dynamicType",
        "faultCause",
        "faultMessage",
    ]
    optional = []

    for name, arg in zip(required + optional, args):
        setattr(obj, name, arg)

    for name, value in kwargs.items():
        if name in required + optional:
            setattr(obj, name, value)
        else:
            raise InvalidArgumentError(
                "Invalid argument: %s.  Expected one of %s" % (name, ", ".join(required + optional))
            )

    return obj
Example #10
0
 def decorated_func(obj):
     cached_attr = "_cached_%s" % accessor_func.__name__
     if hasattr(obj, cached_attr):
         return getattr(obj, cached_attr)
     val = accessor_func(obj)
     setattr(obj, cached_attr, val)
     return val
Example #11
0
    def __init__(self, path):
        self.path = os.path.abspath(path)

        with open(os.path.join(self.path, "info.yaml")) as fd:
            self.info = i = yaml.load(fd)

        if not all(k in i for k in ("name", "identifier", "application")):
            raise AttributeError(
                """
                                 Theme configuration MUST contain:\n
                                 - theme name\n
                                 - theme identifier\n
                                 - application identifier\n
                                 theme configuration contained:{i}
                                 """
            ).format(i)

        # The theme's human readable name, as given in info.yaml.
        self.name = i.pop("name")

        # The theme's identifier. In most situations should match the name of
        # the directory the theme is in.
        self.identifier = i.pop("identifier")

        # The application name to associate them with application.
        self.application = i.pop("application")

        for k, v in iter(i.items()):
            setattr(self, k, v)
Example #12
0
 def __init__(self, *args, **kwargs):
     self.io_loop = kwargs.pop("io_loop", None) or ioloop.IOLoop.current()
     to_close = []
     if kwargs.get("stdin") is Subprocess.STREAM:
         in_r, in_w = _pipe_cloexec()
         kwargs["stdin"] = in_r
         to_close.append(in_r)
         self.stdin = PipeIOStream(in_w, io_loop=self.io_loop)
     if kwargs.get("stdout") is Subprocess.STREAM:
         out_r, out_w = _pipe_cloexec()
         kwargs["stdout"] = out_w
         to_close.append(out_w)
         self.stdout = PipeIOStream(out_r, io_loop=self.io_loop)
     if kwargs.get("stderr") is Subprocess.STREAM:
         err_r, err_w = _pipe_cloexec()
         kwargs["stderr"] = err_w
         to_close.append(err_w)
         self.stderr = PipeIOStream(err_r, io_loop=self.io_loop)
     self.proc = subprocess.Popen(*args, **kwargs)
     for fd in to_close:
         os.close(fd)
     for attr in ["stdin", "stdout", "stderr", "pid"]:
         if not hasattr(self, attr):  # don't clobber streams set above
             setattr(self, attr, getattr(self.proc, attr))
     self._exit_callback = None
     self.returncode = None
Example #13
0
    def getOrganisations(self):
        """
        Returns the list of organisations
        """
        from xml.etree.cElementTree import XMLParser

        # need some error handling here (see equivalent function in
        # medin portal)
        xml = self.client.service.ws_edmo_get_list()
        parser = XMLParser()
        parser.feed(xml)
        tree = parser.close()

        organisations = []
        for element in tree:
            n_code = int(element.findtext("n_code"))
            name = element.findtext("name")
            organisation = Organisation(n_code, name)
            for attr in ("address", "city", "zipcode", "state", "email", "phone", "fax", "website"):
                value = element.findtext(attr).strip()
                if value:
                    setattr(organisation, attr, value)
            organisation.country = element.findtext("c_country")
            organisations.append(organisation)

        return organisations
Example #14
0
 def __call__(self, parser, namespace, values, option_string=None):
     try:
         lib = importlib.import_module("." + values, "attakeism")
         processor = lib.Processor
     except ImportError as err:
         parser.error(str(err))
     setattr(namespace, self.dest, processor)
Example #15
0
def make_module(new_module, doc="", scope=locals()):
    """
    modified from 
    http://dietbuddha.blogspot.com.au/2012/11/python-metaprogramming-dynamic-module.html
    make_module('a.b.c.d', doc="", scope=locals()]) -> <module built-in="built-in" d="d">

    * creates module (and submodules as needed)
    * adds module (and submodules) to sys.modules
    * correctly nests submodules as needed
    * not overwritting existing modules (my modification to the original function)
    """
    module_name = []

    for name in new_module.split("."):
        m = ModuleType(name, doc)
        parent_module_name = ".".join(module_name)

        if parent_module_name:
            if parent_module_name not in sys.modules.keys():  # do not overwrite existing modules
                print "creating parent", parent_module_name
                setattr(sys.modules[parent_module_name], name, m)
        else:
            if m not in scope.keys():  # do not overwrite existing modules
                scope[name] = m

        module_name.append(name)

        name_path = ".".join(module_name)
        if name_path not in sys.modules.keys():  # do not overwrite existing modules
            print "Added %s" % name_path
            sys.modules[name_path] = m

    return sys.modules[".".join(module_name)]
Example #16
0
def TaskInfo(vim, *args, **kwargs):
    '''This data object type contains all information about a task. A task represents
    an operation performed by VirtualCenter or ESX.'''
    
    obj = vim.client.factory.create('ns0:TaskInfo')

    # do some validation checking...
    if (len(args) + len(kwargs)) < 9:
        raise IndexError('Expected at least 10 arguments got: %d' % len(args))

    required = [ 'cancelable', 'cancelled', 'descriptionId', 'eventChainId', 'key', 'queueTime',
        'reason', 'state', 'task' ]
    optional = [ 'changeTag', 'completeTime', 'description', 'entity', 'entityName', 'error',
        'locked', 'name', 'parentTaskKey', 'progress', 'result', 'rootTaskKey',
        'startTime', 'dynamicProperty', 'dynamicType' ]

    for name, arg in zip(required+optional, args):
        setattr(obj, name, arg)

    for name, value in kwargs.items():
        if name in required + optional:
            setattr(obj, name, value)
        else:
            raise InvalidArgumentError("Invalid argument: %s.  Expected one of %s" % (name, ", ".join(required + optional)))

    return obj
    
Example #17
0
    def __init__(self):
        """Initializes the Config object

        Takes no parameters and is essentiall read only thus multiple
        copies of Config can be taken as identical."""

        try:
            confdir = os.environ["XDG_CONFIG_HOME"]
        except:
            confdir = "%s/.config" % os.environ["HOME"]

        self.confpath = os.path.join(confdir, "pyxis")
        self.conffile = os.path.join(self.confpath, "pyxisrc")

        # Config Sections
        self.account = None
        self.settings = None
        self.mediaplayer = None

        self.config = ConfigParser.SafeConfigParser()
        self.config.read(self.conffile)

        sections = self.config.sections()
        for section in sections:
            items = self.config.items(section)
            setattr(self, section, Section(items))

        if not self.validate():
            self.create()
Example #18
0
    def init_app(self, app, config=None):
        "This is used to initialize cache with your app object"

        if config is not None:
            self.config = config
        elif self.config is None:
            self.config = app.config

        if not isinstance(self.config, (NoneType, dict)):
            raise ValueError("`config` must be an instance of dict or NoneType")

        self.config.setdefault("CACHE_DEFAULT_TIMEOUT", 300)
        self.config.setdefault("CACHE_THRESHOLD", 500)
        self.config.setdefault("CACHE_KEY_PREFIX", None)
        self.config.setdefault("CACHE_MEMCACHED_SERVERS", None)
        self.config.setdefault("CACHE_DIR", None)
        self.config.setdefault("CACHE_OPTIONS", None)
        self.config.setdefault("CACHE_ARGS", [])
        self.config.setdefault("CACHE_TYPE", "null")

        if self.with_jinja2_ext:
            setattr(app.jinja_env, JINJA_CACHE_ATTR_NAME, self)

            app.jinja_env.add_extension(CacheExtension)

        self.app = app

        self._set_cache()
def make_tfunc(url, stype, sig_input, expected_sig):
    m = re.match(r".*-([a-zA-Z0-9_-]+)(?:/watch_as3|/html5player)?\.[a-z]+$", url)
    assert m, "%r should follow URL format" % url
    test_id = m.group(1)

    def test_func(self):
        basename = "player-%s.%s" % (test_id, stype)
        fn = os.path.join(self.TESTDATA_DIR, basename)

        if not os.path.exists(fn):
            compat_urlretrieve(url, fn)

        ie = YoutubeIE()
        if stype == "js":
            with io.open(fn, encoding="utf-8") as testf:
                jscode = testf.read()
            func = ie._parse_sig_js(jscode)
        else:
            assert stype == "swf"
            with open(fn, "rb") as testf:
                swfcode = testf.read()
            func = ie._parse_sig_swf(swfcode)
        src_sig = compat_str(string.printable[:sig_input]) if isinstance(sig_input, int) else sig_input
        got_sig = func(src_sig)
        self.assertEqual(got_sig, expected_sig)

    test_func.__name__ = str("test_signature_" + stype + "_" + test_id)
    setattr(TestSignature, test_func.__name__, test_func)
Example #20
0
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        newInteraction()

        root = functional.getRootFolder()
        setSite(root)
        sm = root.getSiteManager()
        sm.getUtility(INameChooserConfiglet).short_url_enabled = True

        # IIntIds
        root["ids"] = IntIds()
        sm.registerUtility(root["ids"], IIntIds)
        root["ids"].register(root)

        # catalog
        root["catalog"] = Catalog()
        sm.registerUtility(root["catalog"], ICatalog)

        # space
        space = ContentSpace(title=u"Space")
        event.notify(ObjectCreatedEvent(space))
        root["space"] = space

        setattr(root, "principal", getUtility(IAuthentication).getPrincipal("zope.mgr"))
        # people
        people = PersonalSpaceManager(title=u"People")
        event.notify(ObjectCreatedEvent(people))
        root["people"] = people
        sm.registerUtility(root["people"], IPersonalSpaceManager)

        endInteraction()
Example #21
0
File: cards.py Project: bqv/anki
 def updateStats(self, ease, state):
     self.reps += 1
     if ease > 1:
         self.successive += 1
     else:
         self.successive = 0
     delay = min(self.totalTime(), MAX_TIMER)
     self.reviewTime += delay
     if self.averageTime:
         self.averageTime = (self.averageTime + delay) / 2.0
     else:
         self.averageTime = delay
     # we don't track first answer for cards
     if state == "new":
         state = "young"
     # update ease and yes/no count
     attr = state + "Ease%d" % ease
     setattr(self, attr, getattr(self, attr) + 1)
     if ease < 2:
         self.noCount += 1
     else:
         self.yesCount += 1
     if not self.firstAnswered:
         self.firstAnswered = time.time()
     self.setModified()
Example #22
0
def make_setting(key, value):
    """ if you really need to alter your runtime settings (maybe for testing
    this is okay, but otherwise don't do it).
    """
    s = Settings()
    setattr(s, key, value)
    return s
Example #23
0
    def __init__(self, label="", **kwargs):
        self.label = label
        self._parent = None
        self.instance = None
        self._getters = []
        self._setters = []

        for name, arg in self.arguments.items():
            if name in kwargs:
                value = kwargs.pop(name)
            elif arg.has_default:
                value = arg.default
            else:
                raise TypeError("The %s argument is required for %s fields" % (arg.name, self.__class__.__name__))
            setattr(self, name, value)
        if kwargs:
            raise TypeError(
                "%s is not a valid argument for %s fields" % (list(kwargs.keys())[0], self.__class__.__name__)
            )

        # Once the base values are all in place, arguments can be initialized properly
        for name, arg in self.arguments.items():
            if hasattr(self, name):
                value = getattr(self, name)
            else:
                value = None
            setattr(self, name, arg.initialize(self, value))
    def update_cell(self, request, datum, user_id, cell_name, new_cell_value):
        try:
            user_obj = datum
            setattr(user_obj, cell_name, new_cell_value)
            kwargs = {}
            attr_to_keyword_map = {
                "name": "name",
                "description": "description",
                "email": "email",
                "enabled": "enabled",
                "project_id": "project",
            }
            for key in attr_to_keyword_map:
                value = getattr(user_obj, key, None)
                keyword_name = attr_to_keyword_map[key]
                if value is not None:
                    kwargs[keyword_name] = value
            api.keystone.user_update(request, user_obj, **kwargs)

        except horizon_exceptions.Conflict:
            message = _("This name is already taken.")
            messages.warning(request, message)
            raise django_exceptions.ValidationError(message)
        except Exception:
            horizon_exceptions.handle(request, ignore=True)
            return False
        return True
def setInitList(_InstanceVariable, _DoStr, _TagStr):

    # get
    Variable = getattr(_InstanceVariable, DoStrToDoingStrOrderedDict[_DoStr] + _TagStr + "Variable")

    # type
    Type = type(Variable)

    # import
    import numpy as np

    # set
    SetKeyStr = DoStrToDoneStrOrderedDict[_DoStr] + _TagStr + "FloatsList"

    # Check
    if Type in [list, np.array]:

        # array
        setattr(_InstanceVariable, SetKeyStr, list(Variable))

    else:

        # array
        setattr(_InstanceVariable, SetKeyStr, [Variable])

        # Check
    NewDoUnitsInt = len(getattr(_InstanceVariable, SetKeyStr))

    # Check
    if _InstanceVariable.DoUnitsInt < NewDoUnitsInt:
        _InstanceVariable.DoUnitsInt = NewDoUnitsInt
Example #26
0
    def load_data_fields(self):
        """
        Get object's data record from database.
        """
        # Get model and key names.
        key = self.get_data_key()
        if not key:
            return

        models = OBJECT_KEY_HANDLER.get_models(key)

        for model in models:
            # Get db model
            model_obj = apps.get_model(settings.WORLD_DATA_APP, model)
            if not model_obj:
                logger.log_errmsg("%s can not open model %s" % (key, model))
                continue

            # Get data record.
            try:
                data = model_obj.objects.get(key=key)
            except Exception, e:
                logger.log_errmsg("%s can not find key %s" % (key, key))
                continue

            # Set data.
            for field in data._meta.fields:
                setattr(self.dfield, field.name, data.serializable_value(field.name))
Example #27
0
 def load_cascade_file(self, module_path, cascade_file_path):
     if not hasattr(self.__class__, "cascade"):
         if isabs(cascade_file_path):
             cascade_file = cascade_file_path
         else:
             cascade_file = join(abspath(dirname(module_path)), cascade_file_path)
         setattr(self.__class__, "cascade", cv.Load(cascade_file))
Example #28
0
    def __getitem__(self, name):
        """
        Any class attribute which is an instance providing
        :class:`pyramid.interfaces.ILocation` will be returned as is.

        Attributes which are constructors for implementing classes will
        be replaced with a constructed instance by reifying the newly
        constructed resource in place of the attribute.

        Assignment to the sub-resources `__name__` and `__parent__` properties
        is handled automatically.
        """

        factory_or_resource = getattr(self, name, None)

        if factory_or_resource:
            if ILocation.implementedBy(factory_or_resource):
                inst = factory_or_resource(self.request)
                inst.__name__ = name
                inst.__parent__ = self
                setattr(self, name, inst)
                return inst

            if ILocation.providedBy(factory_or_resource):
                return factory_or_resource

        raise KeyError(name)
Example #29
0
 def parseXML(self, blockette, xml_doc, pos=0):
     """
     """
     try:
         text = xml_doc.xpath(self.field_name + "/text()")[pos]
     except:
         setattr(blockette, self.attribute_name, self.default_value)
         # debug
         if blockette.debug:
             print("  %s: set to default value %s" % (self, self.default_value))
         return
     # Parse X-Path if necessary. The isdigit test assures legacy support
     # for XSEED without XPaths.
     if self.xpath and not text.isdigit():
         text = utils.getXPath(text)
     # check if already exists
     if hasattr(blockette, self.attribute_name):
         temp = getattr(blockette, self.attribute_name)
         if not isinstance(temp, list):
             temp = [temp]
         temp.append(text)
         text = temp
     setattr(blockette, self.attribute_name, self.convert(text))
     # debug
     if blockette.debug:
         print("  %s: %s" % (self, text))
    def __call__(self, env, data):
        list_item_form = self.ListItemForm(env)
        ordering_field = list_item_form.ordering_field
        if list_item_form is not None:

            if list_item_form.accept(env.request.POST):
                modified_items = []
                lock_messages = []
                edit_sessions = {}
                for value in list_item_form.python_data["items"]:
                    item = value["item"]
                    if getattr(item, ordering_field) != value["order"]:
                        try:
                            edit_sessions[item] = env.item_lock.create(item)
                        except ModelLockedByOther, e:
                            lock_messages.append(unicode(e))
                        except ModelLockError, e:
                            lock_messages.append(unicode(e))

                        setattr(item, ordering_field, value["order"])
                        modified_items.append(item)

                if len(lock_messages) > 0:
                    env.db.rollback()
                    flash(env, u"Изменения не были сохранены:\n%s" % "\n".join(lock_messages), "failure")
                elif len(modified_items) > 0:
                    env.db.commit()
                    flash(env, "\n".join([u"Объект (%s) сохранен" % (item,) for item in modified_items]), "success")
                    [env.item_lock.remove(item, data.edit_session) for item, data.edit_session in edit_sessions.items()]
                return env.json({"success": True})