Пример #1
1
 def update_buttons(self):
     sale_view = self.sales.get_selected()
     self.details_button.set_sensitive(bool(sale_view))
     can_return = bool(sale_view and sale_view.can_return())
     can_edit = bool(sale_view and sale_view.status == Sale.STATUS_QUOTE)
     self.return_sale_button.set_sensitive(can_return)
     self.edit_button.set_sensitive(can_edit)
Пример #2
1
def create_parameter_group(
    name, db_parameter_group_family, description, tags=None, region=None, key=None, keyid=None, profile=None
):
    """
    Create an RDS parameter group

    CLI example to create an RDS parameter group::

        salt myminion boto_rds.create_parameter_group my-param-group mysql5.6 \
                "group description"
    """
    res = __salt__["boto_rds.parameter_group_exists"](name, tags, region, key, keyid, profile)
    if res.get("exists"):
        return {"exists": bool(res)}

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        if not conn:
            return {"results": bool(conn)}

        taglist = _tag_doc(tags)
        rds = conn.create_db_parameter_group(
            DBParameterGroupName=name,
            DBParameterGroupFamily=db_parameter_group_family,
            Description=description,
            Tags=taglist,
        )
        if not rds:
            return {"created": False, "message": "Failed to create RDS parameter group {0}".format(name)}

        return {"exists": bool(rds), "message": "Created RDS parameter group {0}".format(name)}
    except ClientError as e:
        return {"error": salt.utils.boto3.get_error(e)}
Пример #3
1
def update_parameter_group(
    name, parameters, apply_method="pending-reboot", tags=None, region=None, key=None, keyid=None, profile=None
):
    """
    Update an RDS parameter group.

    CLI example::

        salt myminion boto_rds.update_parameter_group my-param-group \
                parameters='{"back_log":1, "binlog_cache_size":4096}' \
                region=us-east-1
    """

    res = __salt__["boto_rds.parameter_group_exists"](name, tags, region, key, keyid, profile)
    if not res.get("exists"):
        return {"exists": bool(res), "message": "RDS parameter group {0} does not exist.".format(name)}

    param_list = []
    for key, value in six.iteritems(parameters):
        item = (key, value, apply_method)
        param_list.append(item)
        if not len(param_list):
            return {"results": False}

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        if not conn:
            return {"results": bool(conn)}

        res = conn.modify_db_parameter_group(DBParameterGroupName=name, Parameters=param_list)
        return {"results": bool(res)}
    except ClientError as e:
        return {"error": salt.utils.boto3.get_error(e)}
def handleLight(node):
    dlog("Handling Light.")
    light = Light()
    light.name = getAttribute(node, "name")
    light.id = getAttribute(node, "id")
    light.type = getAttribute(node, "type", "point")
    light.visible = bool(getAttribute(node, "visible", True))
    light.castShadows = bool(getAttribute(node, "castShadows", True))
    for child in node.childNodes:
        if child.nodeType == xml.dom.Node.ELEMENT_NODE:
            if child.tagName == "position":
                light.position = handleVector(child)
            elif child.tagName == "normal":
                light.normal = handleVector(child)
            elif child.tagName == "colourDiffuse":
                light.colourDiffuse = handleColour(child)
            elif child.tagName == "colourSpecular":
                light.colourSpecular = handleColour(child)
            elif child.tagName == "lightRange":
                light.lightRange = handleLightRange(child)
            elif child.tagName == "lightAttenuation":
                light.lightAttenuation = handleLightAttenuation(child)
            elif child.tagName == "userDataReference":
                light.userDataReference = handleUserDataReference(child)
            elif lower(child.tagName) == "userdata":
                light.userData = handleUserData(child)
            else:
                vlog("Light: Encountered unknown tag %s" % child.tagName)
    return light
Пример #5
1
 def _title_update(self, contents_changed=None):
     if contents_changed in [True, False]:
         self.file_changed = contents_changed
     self.menu_file_save.Enable(self.filename != None and bool(contents_changed))
     self.SetTitle(
         self.title + [" ", " - " + str(self.filename)][bool(self.filename)] + ["", "*"][bool(self.file_changed)]
     )
Пример #6
1
    def extract_document(cls, obj_id):
        """Extracts indexable attributes from a Question and its answers."""

        # Note: Need to keep this in sync with
        # tasks.update_question_vote_chunk.
        obj = cls.uncached.values(
            "id",
            "title",
            "content",
            "num_answers",
            "solution_id",
            "is_locked",
            "created",
            "updated",
            "num_votes_past_week",
            "creator__username",
        ).get(pk=obj_id)

        d = {}
        d["id"] = obj["id"]
        d["model"] = cls.get_model_name()
        d["title"] = obj["title"]
        d["question_content"] = obj["content"]
        d["num_answers"] = obj["num_answers"]
        d["is_solved"] = bool(obj["solution_id"])
        d["is_locked"] = obj["is_locked"]
        d["has_answers"] = bool(obj["num_answers"])

        # We do this because get_absolute_url is an instance method
        # and we don't want to create an instance because it's a DB
        # hit and expensive. So we do it by hand. get_absolute_url
        # doesn't change much, so this is probably ok.
        d["url"] = reverse("questions.answers", kwargs={"question_id": obj["id"]})

        # TODO: Sphinx stores created and updated as seconds since the
        # epoch, so we convert them to that format here so that the
        # search view works correctly. When we ditch Sphinx, we should
        # see if it's faster to filter on ints or whether we should
        # switch them to dates.
        d["created"] = int(time.mktime(obj["created"].timetuple()))
        d["updated"] = int(time.mktime(obj["updated"].timetuple()))

        d["question_creator"] = obj["creator__username"]
        d["num_votes"] = QuestionVote.objects.filter(question=obj["id"]).count()
        d["num_votes_past_week"] = obj["num_votes_past_week"]

        d["tag"] = list(TaggedItem.tags_for(Question, Question(pk=obj_id)).values_list("name", flat=True))

        answer_values = list(Answer.objects.filter(question=obj_id).values_list("content", "creator__username"))

        d["answer_content"] = [a[0] for a in answer_values]
        d["answer_creator"] = list(set([a[1] for a in answer_values]))

        if not answer_values:
            d["has_helpful"] = False
        else:
            d["has_helpful"] = Answer.objects.filter(question=obj_id).filter(votes__helpful=True).exists()

        d["indexed_on"] = int(time.time())
        return d
Пример #7
0
Файл: group.py Проект: ccoss/fas
    def create(
        self,
        name,
        display_name,
        owner,
        group_type,
        invite_only=0,
        needs_sponsor=0,
        user_can_remove=1,
        prerequisite="",
        joinmsg="",
        apply_rules="None",
    ):
        """Create a group"""

        groupname = name
        person = People.by_username(turbogears.identity.current.user_name)
        person_owner = People.by_username(owner)

        if not can_create_group(person):
            turbogears.flash(_("Only FAS adminstrators can create groups."))
            turbogears.redirect("/")
        try:
            owner = People.by_username(owner)
            group = Groups()
            group.name = name
            group.display_name = display_name
            group.owner_id = person_owner.id
            group.group_type = group_type
            group.needs_sponsor = bool(needs_sponsor)
            group.user_can_remove = bool(user_can_remove)
            if prerequisite:
                prerequisite = Groups.by_name(prerequisite)
                group.prerequisite = prerequisite
            group.joinmsg = joinmsg
            group.apply_rules = apply_rules
            # Log group creation
            Log(author_id=person.id, description="%s created group %s" % (person.username, group.name))
            session.flush()
        except TypeError:
            turbogears.flash(_("The group: '%s' could not be created.") % groupname)
            return dict()
        else:
            try:
                owner.apply(group, person)  # Apply...
                session.flush()
                owner.sponsor(group, person)
                owner.upgrade(group, person)
                owner.upgrade(group, person)
            except KeyError:
                turbogears.flash(
                    _(
                        "The group: '%(group)s' has been created, but '%(user)s' could not be added as a group administrator."
                    )
                    % {"group": group.name, "user": owner.username}
                )
            else:
                turbogears.flash(_("The group: '%s' has been created.") % group.name)
            turbogears.redirect("/group/view/%s" % group.name)
            return dict()
Пример #8
0
    def _get_no_init(self):
        if None is self._no_init and False == bool(self.indexing_suite):
            # select all public constructors and exclude copy constructor
            cs = self.constructors(
                lambda c: not c.is_copy_constructor and c.access_type == "public", recursive=False, allow_empty=True
            )

            has_suitable_constructor = bool(cs)
            if cs and len(cs) == 1 and cs[0].is_trivial_constructor and self.find_noncopyable_vars():
                has_suitable_constructor = False

            has_nonpublic_destructor = declarations.has_destructor(self) and not declarations.has_public_destructor(
                self
            )

            trivial_constructor = self.find_trivial_constructor()

            if (
                has_nonpublic_destructor
                or (self.is_abstract and not self.is_wrapper_needed())
                or not has_suitable_constructor
            ):
                self._no_init = True
            elif not trivial_constructor or trivial_constructor.access_type != "public":
                exportable_cs = filter(lambda c: c.exportable and c.ignore == False, cs)
                if not exportable_cs:
                    self._no_init = True
            else:
                pass
        if None is self._no_init:
            self._no_init = False
        return self._no_init
Пример #9
0
 def create(cls, **kwargs):
     """Insert a new Muni stop entry with all corresponding geoboxes.
 
 Args:
   system: The muni system to use. Always "sf-muni" right now.
   lat, lon: Coordinates of stop.
   stop_id: The stop ID of the stop.
   in_routes: List of inbound routes.
   out_routes: List of outbound routes.
 """
     all_boxes = []
     lat = kwargs.pop("lat")
     lon = kwargs.pop("lon")
     for (resolution, slice, use_set) in GEOBOX_CONFIGS:
         if use_set:
             all_boxes.extend(geobox.compute_set(lat, lon, resolution, slice))
         else:
             all_boxes.append(geobox.compute(lat, lon, resolution, slice))
     kwargs["stop_id"] = str(kwargs["stop_id"])
     kwargs["location"] = db.GeoPt(lat, lon)
     kwargs["key_name"] = "stop:%s:%s" % (kwargs["system"], kwargs["stop_id"])
     kwargs["geoboxes"] = all_boxes
     kwargs["has_inbound_routes"] = bool(len(kwargs["in_routes"]) > 0)
     kwargs["has_outbound_routes"] = bool(len(kwargs["out_routes"]) > 0)
     return cls(**kwargs)
Пример #10
0
    def __init__(self, name=None, redditobj=None, ctb=None):
        """
        Initialize CtbUser object with given parameters
        """
        lg.debug("> CtbUser::__init__(%s)", name)

        if not bool(name):
            raise Exception("CtbUser::__init__(): name must be set")
        self.name = name

        if not bool(ctb):
            raise Exception("CtbUser::__init__(): ctb must be set")
        self.ctb = ctb

        if bool(redditobj):
            self.prawobj = redditobj

        # Determine if user is banned
        if ctb.conf.reddit.banned_users:
            if ctb.conf.reddit.banned_users.method == "subreddit":
                for u in ctb.reddit.get_banned(ctb.conf.reddit.banned_users.subreddit):
                    if self.name.lower() == u.name.lower():
                        self.banned = True
            elif ctb.conf.reddit.banned_users.method == "list":
                for u in ctb.conf.reddit.banned_users.list:
                    if self.name.lower() == u.lower():
                        self.banned = True
            else:
                lg.warning(
                    "CtbUser::__init__(): invalid method '%s' in banned_users config"
                    % ctb.conf.reddit.banned_users.method
                )

        lg.debug("< CtbUser::__init__(%s) DONE", name)
Пример #11
0
    def create(self, *args, **kwargs):
        """
            Create the droplet with object properties.

            Note: Every argument and parameter given to this method will be
            assigned to the object.
        """
        for attr in kwargs.keys():
            setattr(self, attr, kwargs[attr])

        # Provide backwards compatibility
        if not self.size_slug and self.size:
            self.size_slug = self.size

        data = {
            "name": self.name,
            "size": self.size_slug,
            "image": self.image,
            "region": self.region,
            "ssh_keys": self.__get_ssh_keys_id_or_fingerprint(),
            "backups": bool(self.backups),
            "ipv6": bool(self.ipv6),
            "private_networking": bool(self.private_networking),
        }

        if self.user_data:
            data["user_data"] = self.user_data

        data = self.get_data("droplets", type=POST, params=data)

        if data:
            self.id = data["droplet"]["id"]
            action_id = data["links"]["actions"][0]["id"]
            self.action_ids = []
            self.action_ids.append(action_id)
Пример #12
0
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel["max-age"]:
        try:
            expires = int(time.time() + int(morsel["max-age"]))
        except ValueError:
            raise TypeError("max-age: %s must be integer" % morsel["max-age"])
    elif morsel["expires"]:
        time_template = "%a, %d-%b-%Y %H:%M:%S GMT"
        expires = calendar.timegm(time.strptime(morsel["expires"], time_template))
    return create_cookie(
        comment=morsel["comment"],
        comment_url=bool(morsel["comment"]),
        discard=False,
        domain=morsel["domain"],
        expires=expires,
        name=morsel.key,
        path=morsel["path"],
        port=None,
        rest={"HttpOnly": morsel["httponly"]},
        rfc2109=False,
        secure=bool(morsel["secure"]),
        value=morsel.value,
        version=morsel["version"] or 0,
    )
Пример #13
0
def create_cookie(name, value, **kwargs):
    """Make a cookie from underspecified parameters.

    By default, the pair of `name` and `value` will be set for the domain ''
    and sent on every request (this is sometimes called a "supercookie").
    """
    result = dict(
        version=0,
        name=name,
        value=value,
        port=None,
        domain="",
        path="/",
        secure=False,
        expires=None,
        discard=True,
        comment=None,
        comment_url=None,
        rest={"HttpOnly": None},
        rfc2109=False,
    )

    badargs = set(kwargs) - set(result)
    if badargs:
        err = "create_cookie() got unexpected keyword arguments: %s"
        raise TypeError(err % list(badargs))

    result.update(kwargs)
    result["port_specified"] = bool(result["port"])
    result["domain_specified"] = bool(result["domain"])
    result["domain_initial_dot"] = result["domain"].startswith(".")
    result["path_specified"] = bool(result["path"])

    return cookielib.Cookie(**result)
Пример #14
0
    def test_nonzero_single_element(self):

        # allow single item via bool method
        s = Series([True])
        self.assert_(s.bool() is True)

        s = Series([False])
        self.assert_(s.bool() is False)

        # single item nan to raise
        for s in [Series([np.nan]), Series([pd.NaT]), Series([True]), Series([False])]:
            self.assertRaises(ValueError, lambda: bool(s))

        for s in [Series([np.nan]), Series([pd.NaT])]:
            self.assertRaises(ValueError, lambda: s.bool())

        # multiple bool are still an error
        for s in [Series([True, True]), Series([False, False])]:
            self.assertRaises(ValueError, lambda: bool(s))
            self.assertRaises(ValueError, lambda: s.bool())

        # single non-bool are an error
        for s in [Series([1]), Series([0]), Series(["a"]), Series([0.0])]:
            self.assertRaises(ValueError, lambda: bool(s))
            self.assertRaises(ValueError, lambda: s.bool())
Пример #15
0
def metrics_expand():
    errors = {}
    try:
        group_by_expr = bool(int(RequestParams.get("groupByExpr", 0)))
    except ValueError:
        errors["groupByExpr"] = "must be 0 or 1."
    try:
        leaves_only = bool(int(RequestParams.get("leavesOnly", 0)))
    except ValueError:
        errors["leavesOnly"] = "must be 0 or 1."

    if "query" not in RequestParams:
        errors["query"] = "this parameter is required."
    if errors:
        return jsonify({"errors": errors}, status=400)

    results = defaultdict(set)
    for query in RequestParams.getlist("query"):
        for node in app.store.find(query):
            if node.is_leaf or not leaves_only:
                results[query].add(node.path)

    if group_by_expr:
        for query, matches in results.items():
            results[query] = sorted(matches)
    else:
        new_results = set()
        for value in results.values():
            new_results = new_results.union(value)
        results = sorted(new_results)

    return jsonify({"results": results})
Пример #16
0
    def test_two_joins_adaption(self):
        a, b, c, d = self.tables.a, self.tables.b, self.tables.c, self.tables.d
        q = self._two_join_fixture()

        btoc = q._from_obj[0].left

        ac_adapted = btoc.right.element.left
        c_adapted = btoc.right.element.right

        is_(ac_adapted.element, a)
        is_(c_adapted.element, c)

        ctod = q._from_obj[0].right
        ad_adapted = ctod.left
        d_adapted = ctod.right
        is_(ad_adapted.element, a)
        is_(d_adapted.element, d)

        bname, cname, dname = q._entities

        b_name_adapted = bname._resolve_expr_against_query_aliases(q, bname.column, None)
        c_name_adapted = cname._resolve_expr_against_query_aliases(q, cname.column, None)
        d_name_adapted = dname._resolve_expr_against_query_aliases(q, dname.column, None)

        assert bool(b_name_adapted == a.c.name)
        assert bool(c_name_adapted == ac_adapted.c.name)
        assert bool(d_name_adapted == ad_adapted.c.name)
Пример #17
0
    def readGrace(self):
        """Read grace note effect.

        -   Fret: :ref:`signed-byte`. Number of fret.

        -   Dynamic: :ref:`byte`. Dynamic of a grace note, as in
            :attr:`guitarpro.base.Note.velocity`.

        -   Transition: :ref:`byte`. See
            :class:`guitarpro.base.GraceEffectTransition`.

        -   Duration: :ref:`byte`. Values are:

            -   *1*: Thirty-second note.
            -   *2*: Twenty-fourth note.
            -   *3*: Sixteenth note.

        -   Flags: :ref:`byte`.

            -   *0x01*: grace note is muted (dead)
            -   *0x02*: grace note is on beat

        """
        grace = gp.GraceEffect()
        grace.fret = self.readByte()
        grace.velocity = self.unpackVelocity(self.readByte())
        grace.transition = gp.GraceEffectTransition(self.readByte())
        grace.duration = 1 << (7 - self.readByte())
        flags = self.readByte()
        grace.isDead = bool(flags & 0x01)
        grace.isOnBeat = bool(flags & 0x02)
        return grace
Пример #18
0
    def __init__(
            self,
            host=None,
            port=6379,
            unix_sock=None,
            database=0,
            password=None,
            encoding=None,
            conn_timeout=2,
            read_timeout=2,
            sentinel=False):

        if not bool(host) != bool(unix_sock):
            raise PyRedisError('Ether host or unix_sock has to be provided')
        self._closed = False
        self._conn_timeout = conn_timeout
        self._read_timeout = read_timeout
        self._encoding = encoding
        self._reader = None
        self._sentinel = sentinel
        self._writer = writer
        self._sock = None
        self.host = host
        self.port = port
        self.unix_sock = unix_sock
        self.password = password
        self.database = database
Пример #19
0
    def keep_item(self, wrapped):
        user = c.user if c.user_is_loggedin else None

        if not c.user_is_admin:
            if self._spam and (not user or (user and self.author_id != user._id)):
                return False

            # author_karma = wrapped.author.link_karma
            # if author_karma <= 0 and random.randint(author_karma, 0) != 0:
            # return False

        if user and not c.ignore_hide_rules:
            if user.pref_hide_ups and wrapped.likes == True and self.author_id != user._id:
                return False

            if user.pref_hide_downs and wrapped.likes == False and self.author_id != user._id:
                return False

            if wrapped._score < user.pref_min_link_score:
                return False

            if wrapped.hidden:
                return False

        # hide NSFW links from non-logged users and under 18 logged users
        # if they're not explicitly visiting an NSFW subreddit
        if (not c.user_is_loggedin and c.site != wrapped.subreddit) or (c.user_is_loggedin and not c.over18):
            is_nsfw = bool(wrapped.over_18)
            is_from_nsfw_sr = bool(wrapped.subreddit.over_18)

            if is_nsfw or is_from_nsfw_sr:
                return False

        return True
Пример #20
0
 def simple_check(self, filename, format, alphabet):
     id_list = [rec.id for rec in SeqIO.parse(open(filename), format, alphabet)]
     rec_dict = SeqIO.indexed_dict(filename, format, alphabet)
     self.assertEqual(set(id_list), set(rec_dict.keys()))
     # This is redundant, I just want to make sure len works:
     self.assertEqual(len(id_list), len(rec_dict))
     # Make sure boolean evaluation works
     self.assertEqual(bool(id_list), bool(rec_dict))
     for key in id_list:
         self.assert_(key in rec_dict)
         self.assertEqual(key, rec_dict[key].id)
         self.assertEqual(key, rec_dict.get(key).id)
     # Check non-existant keys,
     try:
         rec = rec_dict[chr(0)]
         raise ValueError("Accessing a non-existant key should fail")
     except KeyError:
         pass
     self.assertEqual(rec_dict.get(chr(0)), None)
     self.assertEqual(rec_dict.get(chr(0), chr(1)), chr(1))
     # Now check iteritems...
     for key, rec in rec_dict.iteritems():
         self.assert_(key in id_list)
         self.assert_(isinstance(rec, SeqRecord))
         self.assertEqual(rec.id, key)
     # Now check non-defined methods...
     self.assertRaises(NotImplementedError, rec_dict.values)
     self.assertRaises(NotImplementedError, rec_dict.popitem)
     self.assertRaises(NotImplementedError, rec_dict.pop, chr(0))
     self.assertRaises(NotImplementedError, rec_dict.pop, chr(0), chr(1))
     self.assertRaises(NotImplementedError, rec_dict.clear)
     self.assertRaises(NotImplementedError, rec_dict.__setitem__, "X", None)
     self.assertRaises(NotImplementedError, rec_dict.copy)
     self.assertRaises(NotImplementedError, rec_dict.fromkeys, [])
Пример #21
0
def file_group_executable(path):
    """Check if a file should be group executable"""
    mode = path.stat().mode
    if stat.S_ISDIR(mode):
        return
    if bool(stat.S_IXUSR & mode) and not bool(stat.S_IXGRP & mode):
        return "PROB_FILE_NOT_GRPEXEC"
Пример #22
0
    def set_options(
        self,
        port,
        ip=0,
        seed_id=None,
        supportcrypto=True,
        requirecrypto=False,
        cryptostealth=False,
        no_peer_id=True,
        compact=True,
    ):
        """Prepare query parameters according to state variables. Crypto
        parameters will be set to the *least secure* logically consistent
        configuration.

        Called during __init__(), so only use this if changing parameters
        DURING program execution."""
        # Enforce logical consistency
        requirecrypto &= supportcrypto
        cryptostealth &= requirecrypto

        # Port is required; IP if specified; seed_id if specified
        self.client = (
            [("ip", str(IPv4(ip)))][: bool(ip)]
            + [("port", port if not cryptostealth else 0)]
            + [("seed_id", seed_id)][: bool(seed_id)]
        )
        # Compact precludes peer_id, so don't bother with no_peer_id
        self.peer_options = [("compact", int(compact))] + [("no_peer_id", 1)][: (no_peer_id and not compact)]

        self.crypto_options = [("supportcrypto", int(supportcrypto)), ("requirecrypto", int(requirecrypto))] + [
            ("cryptoport", port)
        ][:cryptostealth]
Пример #23
0
    def add_props(cls, user, wrapped):
        names = ("subscriber", "moderator", "contributor")
        rels = SRMember._fast_query(wrapped, [user], names) if c.user_is_loggedin else {}
        defaults = Subreddit.default_subreddits()
        for item in wrapped:
            if not user or not user.has_subscribed:
                item.subscriber = item._id in defaults
            else:
                item.subscriber = bool(rels.get((item, user, "subscriber")))
            item.moderator = bool(rels.get((item, user, "moderator")))
            item.contributor = bool(item.type != "public" and (item.moderator or rels.get((item, user, "contributor"))))

            # Don't reveal revenue information via /r/lounge's subscribers
            if g.lounge_reddit and item.name == g.lounge_reddit and not c.user_is_admin:
                item._ups = 0

            item.score = item._ups

            # override "voting" score behavior (it will override the use of
            # item.score in builder.py to be ups-downs)
            item.likes = item.subscriber or None
            base_score = item.score - (1 if item.likes else 0)
            item.voting_score = [(base_score + x - 1) for x in range(3)]
            item.score_fmt = Score.subscribers

            # will seem less horrible when add_props is in pages.py
            from r2.lib.pages import UserText

            item.usertext = UserText(item, item.description)

        Printable.add_props(user, wrapped)
Пример #24
0
Файл: dill.py Проект: mindw/dill
def dump(obj, file, protocol=None, byref=None, fmode=None, recurse=None):  # , strictio=None):
    """pickle an object to a file"""
    from .settings import settings

    strictio = False  # FIXME: strict=True needs cleanup
    if protocol is None:
        protocol = settings["protocol"]
    if byref is None:
        byref = settings["byref"]
    if fmode is None:
        fmode = settings["fmode"]
    if recurse is None:
        recurse = settings["recurse"]
    pik = Pickler(file, protocol)
    pik._main = _main_module
    # apply kwd settings
    pik._byref = bool(byref)
    pik._strictio = bool(strictio)
    pik._fmode = fmode
    pik._recurse = bool(recurse)
    # hack to catch subclassed numpy array instances
    if NumpyArrayType and ndarraysubclassinstance(obj):

        @register(type(obj))
        def save_numpy_array(pickler, obj):
            log.info("Nu: (%s, %s)" % (obj.shape, obj.dtype))
            npdict = getattr(obj, "__dict__", None)
            f, args, state = obj.__reduce__()
            pik.save_reduce(_create_array, (f, args, state, npdict), obj=obj)
            return

    # end hack
    pik.dump(obj)
    return
Пример #25
0
    def __init__(self, id, name, logX, logY, xDataReference, yDataReference):
        sedmlBase.__init__(self, id, name)

        self.logX = bool(logX)
        self.logY = bool(logY)
        self.xDataReference = xDataReference
        self.yDataReference = yDataReference
Пример #26
0
    def from_dict(d):
        """Recursively convert a dict representing a ParseTreeNode to a ParseTreeNode.

        This function creates a ParseTreeNode from a dict whose contents are the
        attributes and values of the object. It recursively performs this operation
        on the "children" key.

        This is the inverse function of the function jsonify.

        :param d: A dictionary that corresponds to a ParseTreeNode object
        :type d: dict
        :rtype: ParseTreeNode
        """
        p = ParseTreeNode("")
        role = d["role"]
        nodetype = d.get("nodetype", None)
        if nodetype is None:
            nodetype = d.get("type", None)  # assbackward-compatability
        raw = d["raw"]
        p = ParseTreeNode(role, raw=raw, nodetype=nodetype)
        p.is_associative = bool(d["is_associative"])
        p.is_argument = bool(d["is_argument"])
        p.values = d["values"]
        p.corrected = bool(d["corrected"])
        p.bound = bool(d["bound"])
        p.datatype = d["datatype"]
        p.add_children([ParseTreeNode.from_dict(c) for c in d["children"]])
        # TODO: Add code to make sure all keys are set as attributes.
        return p
Пример #27
0
def create_subnet_group(name, description, subnet_ids, tags=None, region=None, key=None, keyid=None, profile=None):
    """
    Create an RDS subnet group

    CLI example to create an RDS subnet group::

        salt myminion boto_rds.create_subnet_group my-subnet-group \
            "group description" '[subnet-12345678, subnet-87654321]' \
            region=us-east-1
    """
    res = __salt__["boto_rds.subnet_group_exists"](name, tags, region, key, keyid, profile)
    if res.get("exists"):
        return {"exists": bool(res)}

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        if not conn:
            return {"results": bool(conn)}

        taglist = _tag_doc(tags)
        rds = conn.create_db_subnet_group(
            DBSubnetGroupName=name, DBSubnetGroupDescription=description, SubnetIds=subnet_ids, Tags=taglist
        )

        return {"created": bool(rds)}
    except ClientError as e:
        return {"error": salt.utils.boto3.get_error(e)}
Пример #28
0
def unlock(request):

    try:
        key = request.GET["key"].strip()
        court = request.GET["court"].strip()
        casenum = request.GET["casenum"].strip()
        modified = bool(int(request.GET["modified"]))
        ignore_nonce = bool(int(request.GET["nononce"]))
    except KeyError:
        # Fail.  Missing required arguments.
        return HttpResponse("0<br>Missing arguments.")
    except ValueError:
        return HttpResponse("0<br>Invalid integer boolean for 'modified'.")

    authquery = Uploader.objects.filter(key=key)

    # Authenticate the uploader.
    try:
        uploader = authquery[0]
    except IndexError:
        # Fail. No auth key match.
        return HttpResponse("0<br>Authentication failed.")
    else:
        uploaderid = uploader.id

    dropped, errmsg = BucketLockManager.drop_lock(
        court, casenum, uploaderid, modified=modified, ignore_nonce=ignore_nonce
    )

    if dropped:
        return HttpResponse("1")
    else:
        return HttpResponse("0<br>%s" % errmsg)
Пример #29
0
def get_endpoint(name, tags=None, region=None, key=None, keyid=None, profile=None):
    """
    Return the endpoint of an RDS instance.

    CLI example::

        salt myminion boto_rds.get_endpoint myrds

    """
    endpoint = "None"
    res = __salt__["boto_rds.exists"](name, tags, region, key, keyid, profile)
    if not res:
        return {"exists": bool(res), "message": "RDS instance {0} does not exist.".format(name)}

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        if not conn:
            return {"results": bool(conn)}

        rds = conn.describe_db_instances(DBInstanceIdentifier=name)

        if rds:
            inst = rds["DBInstances"][0]["Endpoint"]
            endpoint = "{0}:{1}".format(inst.get("Address"), inst.get("Port"))
            return endpoint

    except ClientError as e:
        return {"error": salt.utils.boto3.get_error(e)}
Пример #30
0
 def __cmp__(self, other):
     return (
         cmp(other.critical, self.critical)
         or cmp(other.non_critical, self.non_critical)
         or cmp(bool(other.combined), bool(self.combined))
         or cmp(self.name, other.name)
     )