Example #1
1
def imagesearch(request, page_num):
    if page_num == "":
        page_num = "1"
    page_num = int(page_num)
    num_per_page = 15

    q = request.GET.get("q", None)
    if q:
        image_server = settings.FDFS_HTTP_SERVER
        index_stories = SearchStory.query(q)[:500]
        response_images = []
        for index_story in index_stories:
            story = MStory.objects(id=index_story["db_id"]).first()
            if story and story.image_ids:
                for image_id in story.image_ids:
                    if len(image_id) > 20:
                        # print image_id
                        image = MImage.objects(id=image_id).first()
                        imagedict = dict(
                            image_url=image_server + image.image_remote_id,
                            story_url=story.story_guid,
                            story_title=story.story_title,
                        )
                        response_images.append(imagedict)
                        if len(response_images) >= 50:
                            return render(request, "imagesearch.html", locals())
    return render(request, "imagesearch.html", locals())
def tell_story(template):
    """ Run input grab and story based upon loop"""
    story_line = template
    if template == story:
        adjective = raw_input("Enter an adjective ")
        noun = raw_input("Enter a noun ")
        verb = raw_input("Enter a verb ")
        name = raw_input("Enter your name ")
        number = raw_input("Enter a number between 1-10 ")
        number_two = raw_input("Enter a number between 10-20 ")
        year = raw_input("Enter a year (Example: 1986) ")
        magic = template.format(**locals())
        print magic
        response = raw_input("Ready for the next Madlib? (yes or no) ")
        return response
    elif template == story2 and tell_next == "y":
        adjective = raw_input("Enter an adjective ")
        noun = raw_input("Enter a noun ")
        verb = raw_input("Enter a verb (past tense) ")
        name = raw_input("Enter your name ")
        magic = template.format(**locals())
        print magic
        response = raw_input("Ready for the next Madlib? (yes or no) ")
        return response
    else:
        name = raw_input("Enter a name ")
        noun = raw_input("Enter a noun ")
        verb = raw_input("Enter a verb ")
        magic = template.format(**locals())
        print magic
        print ("Thanks so much for playing. There are no more Madlibs to do.")
Example #3
1
    def autoinc_sql(self, table, column):
        # To simulate auto-incrementing primary keys in Oracle, we have to
        # create a sequence and a trigger.
        sq_name = self._get_sequence_name(table)
        tr_name = self._get_trigger_name(table)
        tbl_name = self.quote_name(table)
        col_name = self.quote_name(column)
        sequence_sql = (
            """
DECLARE
    i INTEGER;
BEGIN
    SELECT COUNT(*) INTO i FROM USER_CATALOG
        WHERE TABLE_NAME = '%(sq_name)s' AND TABLE_TYPE = 'SEQUENCE';
    IF i = 0 THEN
        EXECUTE IMMEDIATE 'CREATE SEQUENCE "%(sq_name)s"';
    END IF;
END;
/"""
            % locals()
        )
        trigger_sql = (
            """
CREATE OR REPLACE TRIGGER "%(tr_name)s"
BEFORE INSERT ON %(tbl_name)s
FOR EACH ROW
WHEN (new.%(col_name)s IS NULL)
    BEGIN
        SELECT "%(sq_name)s".nextval
        INTO :new.%(col_name)s FROM dual;
    END;
/"""
            % locals()
        )
        return sequence_sql, trigger_sql
def getWeather(place):
    if (re.match("[a-zA-Z]+,* [a-zA-Z]{2}", place)) != None:
        city = re.search("[a-zA-Z]+ ", place).string.strip()  # Doesn't actually seperate city/state. Needs to!
        state = re.search(" [a-zA-Z]{2}", place).string.strip()

        print "city, state = " + city + ", " + state
    elif re.match("\d{5}", place) != None:
        zip = place
        print "zip code = ", zip
    else:
        return "Please enter a real location"

    if "city" in locals() and "state" in locals():
        content = urllib.urlopen("http://www.rssweather.com/wx/us/" + state + "/" + city + "/rss.php")
    else:
        content = urllib.urlopen("http://www.rssweather.com/zipcode/" + zip + "/wx.php")

    xmldoc = minidom.parse(content)

    try:
        pubDate = xmldoc.getElementsByTagName("pubDate")[0].firstChild.data
    except:
        return "I can't find the weather for that city."
    pubDate = pubDate.split(" ")[4] + " GMT " + pubDate.split(" ")[5]
    summary = xmldoc.getElementsByTagName("description")[1].firstChild.data
    reply = summary + " (" + pubDate + ")"

    return reply
Example #5
1
def _detect_duplicates(bam_file, out_dir, data):
    """
    count duplicate percentage
    """
    out_file = os.path.join(out_dir, "dup_metrics.txt")
    if not utils.file_exists(out_file):
        dup_align_bam = dedup_bam(bam_file, data)
        num_cores = dd.get_num_cores(data)
        with file_transaction(out_file) as tx_out_file:
            sambamba = config_utils.get_program("sambamba", data, default="sambamba")
            dup_count = (
                "{sambamba} view --nthreads {num_cores} --count "
                "-F 'duplicate and not unmapped' "
                "{bam_file} >> {tx_out_file}"
            )
            message = "Counting duplicates in {bam_file}.".format(bam_file=bam_file)
            do.run(dup_count.format(**locals()), message)
            tot_count = (
                "{sambamba} view --nthreads {num_cores} --count " "-F 'not unmapped' " "{bam_file} >> {tx_out_file}"
            )
            message = "Counting reads in {bam_file}.".format(bam_file=bam_file)
            do.run(tot_count.format(**locals()), message)
    with open(out_file) as in_handle:
        dupes = float(in_handle.next().strip())
        total = float(in_handle.next().strip())
    return {"Duplication Rate of Mapped": dupes / total}
Example #6
1
    def delete(self, req, id):
        """
        Deletes the image and all its chunks from the Glance

        :param req: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :raises HttpBadRequest if image registry is invalid
        :raises HttpNotFound if image or any chunk is not available
        :raises HttpUnauthorized if image or any chunk is not
                deleteable by the requesting user
        """
        self._enforce(req, "delete_image")

        image = self.get_image_meta_or_404(req, id)
        if image["protected"]:
            msg = _("Image is protected")
            LOG.debug(msg)
            raise HTTPForbidden(explanation=msg, request=req, content_type="text/plain")

        if image["status"] == "pending_delete":
            msg = _("Forbidden to delete a %s image.") % image["status"]
            LOG.debug(msg)
            raise HTTPForbidden(explanation=msg, request=req, content_type="text/plain")
        elif image["status"] == "deleted":
            msg = _("Image %s not found." % id)
            LOG.debug(msg)
            raise HTTPNotFound(explanation=msg, request=req, content_type="text/plain")

        if image["location"] and CONF.delayed_delete:
            status = "pending_delete"
        else:
            status = "deleted"

        try:
            # Delete the image from the registry first, since we rely on it
            # for authorization checks.
            # See https://bugs.launchpad.net/glance/+bug/1065187
            registry.update_image_metadata(req.context, id, {"status": status})
            registry.delete_image_metadata(req.context, id)

            # The image's location field may be None in the case
            # of a saving or queued image, therefore don't ask a backend
            # to delete the image if the backend doesn't yet store it.
            # See https://bugs.launchpad.net/glance/+bug/747799
            if image["location"]:
                upload_utils.initiate_deletion(req, image["location"], id, CONF.delayed_delete)
        except exception.NotFound as e:
            msg = _("Failed to find image to delete: %(e)s") % locals()
            for line in msg.split("\n"):
                LOG.info(line)
            raise HTTPNotFound(explanation=msg, request=req, content_type="text/plain")
        except exception.Forbidden as e:
            msg = _("Forbidden to delete image: %(e)s") % locals()
            for line in msg.split("\n"):
                LOG.info(line)
            raise HTTPForbidden(explanation=msg, request=req, content_type="text/plain")
        else:
            self.notifier.info("image.delete", redact_loc(image))
            return Response(body="", status=200)
 def input_conversion(self, cpp_type, argument_var, arg_num):
     temp_var = "v%d" % arg_num
     t = self.inner_cpp_type
     ltype = self.openms_type
     code = Code().add(
         """
             |cdef libcpp_vector[$t] _$temp_var = $argument_var
             |cdef _$ltype $temp_var = _$ltype(_$temp_var)
             """,
         locals(),
     )
     cleanup = ""
     if cpp_type.is_ref:
         cleanup_code = Code().add(
             """
                 |replace = []
                 |cdef int i, n
                 |n = $temp_var.size()
                 |for i in range(n):
                 |    replace.append(<$t>$temp_var.at(i))
                 |$argument_var[:] = replace
                 """,
             locals(),
         )
     # here we inject special behavoir for testing if this converter
     # was called !
     call_as = "(%s)" % temp_var
     return code, call_as, cleanup
 def input_conversion(self, cpp_type, argument_var, arg_num):
     temp_var = "v%d" % arg_num
     item = "item%d" % arg_num
     code = Code().add(
         """
         |cdef libcpp_set[_String] * $temp_var = new libcpp_set[_String]()
         |cdef bytes $item
         |for $item in $argument_var:
         |   $temp_var.insert(_String(<char *>$item))
         """,
         locals(),
     )
     if cpp_type.is_ref:
         cleanup_code = Code().add(
             """
             |cdef replace = set()
             |cdef libcpp_set[_String].iterator it = $temp_var.begin()
             |while it != $temp_var.end():
             |   replace.add(<char*>deref(it).c_str())
             |   inc(it)
             |$argument_var.clear()
             |$argument_var.update(replace)
             |del $temp_var
             """,
             locals(),
         )
     else:
         cleanup_code = "del %s" % temp_var
     return code, "deref(%s)" % temp_var, cleanup_code
Example #9
1
 def serialize_numpy(self, buff, numpy):
     """
 serialize message with numpy array types into buffer
 :param buff: buffer, ``StringIO``
 :param numpy: numpy python module
 """
     try:
         buff.write(_struct_B.pack(self.success))
         _x = self.status_message
         length = len(_x)
         if python3 or type(_x) == unicode:
             _x = _x.encode("utf-8")
             length = len(_x)
         if python3:
             buff.write(struct.pack("<I%sB" % length, length, *_x))
         else:
             buff.write(struct.pack("<I%ss" % length, length, _x))
     except struct.error as se:
         self._check_types(
             struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get("_x", self))))
         )
     except TypeError as te:
         self._check_types(
             ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get("_x", self))))
         )
Example #10
0
File: misc.py Project: gperciva/gub
def map_command_dir(os_commands, dir, command, predicate):
    if not os.path.isdir(dir):
        raise Exception("warning: no such dir: %(dir)s" % locals())
    (root, dirs, files) = next(os.walk(dir))
    for file in files:
        if predicate(os.path.join(root, file)):
            os_commands.system("%(command)s %(root)s/%(file)s" % locals(), ignore_errors=True)
Example #11
0
    def test_basics(self):
        class Node(Generic[T]):
            def __init__(self, label: T):
                self.label = label
                self.left = self.right = None

            def add_both(self, left: "Optional[Node[T]]", right: "Node[T]" = None, stuff: int = None, blah=None):
                self.left = left
                self.right = right

            def add_left(self, node: Optional["Node[T]"]):
                self.add_both(node, None)

            def add_right(self, node: "Node[T]" = None):
                self.add_both(None, node)

        t = Node[int]
        both_hints = get_type_hints(t.add_both, globals(), locals())
        assert both_hints["left"] == both_hints["right"] == Optional[Node[T]]
        assert both_hints["stuff"] == Optional[int]
        assert "blah" not in both_hints

        left_hints = get_type_hints(t.add_left, globals(), locals())
        assert left_hints["node"] == Optional[Node[T]]

        right_hints = get_type_hints(t.add_right, globals(), locals())
        assert right_hints["node"] == Optional[Node[T]]
Example #12
0
def get_ebook_count(field, key, publish_year=None):
    ebook_count_db = get_ebook_count_db()

    # Handle the case of ebook_count_db_parametres not specified in the config.
    if ebook_count_db is None:
        return 0

    def db_lookup(field, key, publish_year=None):
        sql = "select sum(ebook_count) as num from subjects where field=$field and key=$key"
        if publish_year:
            if isinstance(publish_year, (tuple, list)):
                sql += " and publish_year between $y1 and $y2"
                (y1, y2) = publish_year
            else:
                sql += " and publish_year=$publish_year"
        return list(ebook_count_db.query(sql, vars=locals()))[0].num

    total = db_lookup(field, key, publish_year)
    if total:
        return total
    elif publish_year:
        sql = "select ebook_count as num from subjects where field=$field and key=$key limit 1"
        if len(list(ebook_count_db.query(sql, vars=locals()))) != 0:
            return 0
    years = find_ebook_count(field, key)
    if not years:
        return 0
    for year, count in sorted(years.iteritems()):
        ebook_count_db.query(
            "insert into subjects (field, key, publish_year, ebook_count) values ($field, $key, $year, $count)",
            vars=locals(),
        )

    return db_lookup(field, key, publish_year)
Example #13
0
    def testIterateState(self):
        cmd.fragment("ala")
        cmd.create("ala", "ala", 1, 2)
        self.assertEqual(2, cmd.count_states())

        v_count = cmd.count_atoms("all")
        expr = "v_xyz.append(((model,index), (x,y,z)))"

        # current state
        v_xyz = []
        cmd.iterate_state(-1, "all", expr, space=locals())
        self.assertEqual(len(v_xyz), v_count)

        # all states
        v_xyz = []
        cmd.iterate_state(0, "all", expr, space=locals())
        self.assertEqual(len(v_xyz), v_count * 2)

        # atomic=0
        stored.v_xyz = []
        cmd.iterate_state(1, "all", "stored.v_xyz.append((x,y,z))", atomic=0)
        self.assertEqual(len(stored.v_xyz), v_count)

        space = {"self": self, "NameError": NameError, "v_list": []}
        cmd.iterate_state(1, "all", "v_list.append(self.assertRaises(NameError, lambda: (model, index)))", space=space)
        self.assertEqual(len(space["v_list"]), v_count)
Example #14
0
 def serialize(self, buff):
     """
 serialize message into buffer
 :param buff: buffer, ``StringIO``
 """
     try:
         _x = self.key
         length = len(_x)
         if python3 or type(_x) == unicode:
             _x = _x.encode("utf-8")
             length = len(_x)
         if python3:
             buff.write(struct.pack("<I%sB" % length, length, *_x))
         else:
             buff.write(struct.pack("<I%ss" % length, length, _x))
         _x = self.value
         length = len(_x)
         if python3 or type(_x) == unicode:
             _x = _x.encode("utf-8")
             length = len(_x)
         if python3:
             buff.write(struct.pack("<I%sB" % length, length, *_x))
         else:
             buff.write(struct.pack("<I%ss" % length, length, _x))
     except struct.error as se:
         self._check_types(
             struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get("_x", self))))
         )
     except TypeError as te:
         self._check_types(
             ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get("_x", self))))
         )
Example #15
0
    def __call__(self, track, slice=None):
        edir = EXPORTDIR
        method = "utr_extension"

        filepath = "%(edir)s/%(method)s/%(track)s.readextension_%(region)s_%(direction)s.%(slice)s.png"

        toc_text = []
        link_text = []

        for region, direction in itertools.product(("downstream", "upstream"), ("sense", "antisense", "anysense")):

            filename = filepath % locals()
            if not os.path.exists(filename):
                continue

            linktext = "%(track)s-%(region)s-%(direction)s-%(slice)s" % locals()

            toc_text.append("* %(linktext)s_" % locals())
            link_text.append(".. _%(linktext)s: %(filename)s" % locals())

        toc_text = "\n".join(toc_text)
        link_text = "\n".join(link_text)

        rst_text = (
            """
%(toc_text)s

%(link_text)s
"""
            % locals()
        )

        return odict((("text", rst_text),))
Example #16
0
    def __call__(self, track, slice=None):
        edir = EXPORTDIR
        method = "utr_extension"

        blocks = ResultBlocks()

        filepath = "%(edir)s/%(method)s/%(track)s.readextension_%(region)s_%(direction)s.%(slice)s.png"

        block = """
.. figure:: %(filename)s
   :height: 300 
"""
        # append spaces for file extension
        block = "\n".join([x + " " * 200 for x in block.split("\n")])

        for region, direction in itertools.product(("downstream", "upstream"), ("sense", "antisense", "anysense")):

            filename = filepath % locals()

            if os.path.exists(filename):
                blocks.append(ResultBlock(text=block % locals(), title="%(track)s %(region)s %(direction)s" % locals()))
            # else:
            #     blocks.append( ResultBlock( "",
            # title = "%(track)s %(region)s %(direction)s" % locals() ) )

        return odict((("rst", "\n".join(Utils.layoutBlocks(blocks, layout="columns-3"))),))
Example #17
0
def main():
    util2.chdir_top()

    tags = [(name, getEnumName(name, "Tag")) for name in sorted(List_HTML_Tags.split() + List_Other_Tags.split())]
    attrs = [(name, getEnumName(name, "Attr")) for name in sorted(List_HTML_Attrs.split() + List_Other_Attrs.split())]
    aligns = [(name, getEnumName(name, "Align")) for name in sorted(List_Align_Values.split())]
    cssProps = [(name, getEnumName(name, "Css")) for name in sorted(List_CSS_Props.split())]
    cssColors = [(name, "MKRGB(%s)" % value) for (name, value) in sorted(List_CSS_Colors)]

    enum_htmltag = createTypeEnum(tags, "HtmlTag", "Tag_NotFound")
    enum_htmlattr = createTypeEnum(attrs, "HtmlAttr", "Attr_NotFound")
    enum_alignattr = createTypeEnum(aligns, "AlignAttr", "Align_NotFound")
    enum_cssprop = createTypeEnum(cssProps, "CssProp", "Css_Unknown")

    code_defines = Template_Defines
    code_htmltag = createFastFinder(tags, "HtmlTag", "Tag_NotFound", True)
    code_htmlattr = createFastFinder(attrs, "HtmlAttr", "Attr_NotFound", True)
    code_selfclosing = createFastSelector(tags, List_Self_Closing_Tags.split(), "IsTagSelfClosing", "HtmlTag")
    code_inlinetag = createFastSelector(tags, List_Inline_Tags.split(), "IsInlineTag", "HtmlTag")
    code_alignattr = createFastFinder(aligns, "AlignAttr", "Align_NotFound", True)
    code_htmlentity = (
        Template_Entities_Comment
        + "\n"
        + createFastFinder(List_HTML_Entities, "uint32_t", "(uint32_t)-1", False, "HtmlEntityRune")
    )
    code_cssprop = createFastFinder(cssProps, "CssProp", "Css_Unknown", True)
    code_csscolor = createFastFinder(cssColors, "ARGB", "MKRGBA(0,0,0,0)", True, "CssColor")

    content = Template_Lookup_Header % locals()
    open("src/utils/HtmlParserLookup.h", "wb").write(content.replace("\n", "\r\n"))
    content = Template_Lookup_Code[:-1] % locals()
    open("src/utils/HtmlParserLookup.cpp", "wb").write(content.replace("\n", "\r\n"))
Example #18
0
    def __call__(self, track, slice=None):
        edir = EXPORTDIR

        toc_text = []
        link_text = []

        filenames = sorted([x.asFile() for x in TRACKS])

        for fn in filenames:
            toc_text.append("* %(fn)s_" % locals())
            link_text.append(".. _%(fn)s: %(edir)s/fastqc/%(fn)s.genome_fastqc/fastqc_report.html" % locals())

        toc_text = "\n".join(toc_text)
        link_text = "\n".join(link_text)

        rst_text = (
            """
%(toc_text)s

%(link_text)s
"""
            % locals()
        )

        return odict((("text", rst_text),))
Example #19
0
def get_id_from_href(href):
    """Return the id portion of a url as an int.

    Given: 'http://www.foo.com/bar/123?q=4'
    Returns: 123

    In order to support local hrefs, the href argument can be just an id:
    Given: '123'
    Returns: 123

    """
    LOG.debug(_("Attempting to treat %(href)s as an integer ID.") % locals())

    try:
        return int(href)
    except ValueError:
        pass

    LOG.debug(_("Attempting to treat %(href)s as a URL.") % locals())

    try:
        return int(urlparse.urlsplit(href).path.split("/")[-1])
    except ValueError as error:
        LOG.debug(_("Failed to parse ID from %(href)s: %(error)s") % locals())
        raise
def status():
    with open(PROJECTS_FILE) as file:
        projects = json.load(file)

    try:
        for project in projects:
            _, host, path, _, _, _ = urlparse(project["travis url"])
            api_url = "https://api.{host}/repos{path}".format(**locals())
            resp = get(api_url)

            # See if the Github URL has moved.
            if resp.status_code == 404:
                github_url = "https://github.com{path}".format(**locals())
                resp = get(github_url)

                if resp.status_code == 200:
                    _, _, github_path, _, _, _ = urlparse(resp.url)

                    if github_path != path:
                        message = "Error in {guid}: {path} has moved to {github_path}"
                        kwargs = dict(guid=project["guid"], **locals())
                        raise Exception(message.format(**kwargs))

            if resp.status_code != 200:
                message = "Missing {guid}: no {travis url}"
                raise Exception(message.format(**project))
    except Exception as e:
        status = str(e)
    else:
        status = "ok"

    return jsonify(dict(status=status, updated=int(time()), dependencies=["Travis", "Github"], resources={}))
Example #21
0
    def create_snapshot(cls, session, instance_id, vm_ref, label):
        """ Creates Snapshot (Template) VM, Snapshot VBD, Snapshot VDI,
        Snapshot VHD
        """
        # TODO(sirp): Add quiesce and VSS locking support when Windows support
        # is added
        LOG.debug(_("Snapshotting VM %(vm_ref)s with label '%(label)s'...") % locals())

        vm_vdi_ref, vm_vdi_rec = get_vdi_for_vm_safely(session, vm_ref)
        vm_vdi_uuid = vm_vdi_rec["uuid"]
        sr_ref = vm_vdi_rec["SR"]

        original_parent_uuid = get_vhd_parent_uuid(session, vm_vdi_ref)

        task = session.call_xenapi("Async.VM.snapshot", vm_ref, label)
        template_vm_ref = session.wait_for_task(instance_id, task)
        template_vdi_rec = get_vdi_for_vm_safely(session, template_vm_ref)[1]
        template_vdi_uuid = template_vdi_rec["uuid"]

        LOG.debug(_("Created snapshot %(template_vm_ref)s from" " VM %(vm_ref)s.") % locals())

        parent_uuid = wait_for_vhd_coalesce(session, instance_id, sr_ref, vm_vdi_ref, original_parent_uuid)

        # TODO(sirp): we need to assert only one parent, not parents two deep
        return template_vm_ref, [template_vdi_uuid, parent_uuid]
Example #22
0
            def run(self):
                n = self.dst_nut
                host = n.host()
                port = n.port()

                src_path = self.src_redis.args["path"]
                if prefix:
                    cmd = TT(
                        "~/redis-replay-aof --pipe_cmds 100 --file $src_path/data/appendonly.aof --dest $host:$port --filter $prefix",
                        locals(),
                    )
                else:
                    cmd = TT(
                        "~/redis-replay-aof --pipe_cmds 100 --file $src_path/data/appendonly.aof --dest $host:$port",
                        locals(),
                    )

                remotecmd = self.src_redis._remote_cmd(cmd, chdir=False)
                for line in piperun(remotecmd):
                    logging.debug(line)
                    if not strstr(line, "diff:"):
                        continue
                    # progress: [scanned:0] [processed:0] [skipped:0] [unsupported:0] [filesize:0] [postion:0] [diff:0]
                    x = line.split()[-1]

                    try:
                        self.delay = int(x.replace("[diff:", "").replace("]", ""))
                    except:
                        self.deplay = -2

                self.delay = -3  # remote replayer is killed
    def run(self):
        request = cherrypy.serving.request
        response = cherrypy.serving.response

        path = request.path_info
        if path.endswith("login_screen"):
            self._debug_message("routing %(path)r to login_screen", locals())
            response.body = self.login_screen()
            return True
        elif path.endswith("do_login"):
            if request.method != "POST":
                response.headers["Allow"] = "POST"
                self._debug_message("do_login requires POST")
                raise cherrypy.HTTPError(405)
            self._debug_message("routing %(path)r to do_login", locals())
            return self.do_login(**request.params)
        elif path.endswith("do_logout"):
            if request.method != "POST":
                response.headers["Allow"] = "POST"
                raise cherrypy.HTTPError(405)
            self._debug_message("routing %(path)r to do_logout", locals())
            return self.do_logout(**request.params)
        else:
            self._debug_message("No special path, running do_check")
            return self.do_check()
Example #24
0
def add(request):
    current_page = "jobs"
    page_title = u"发布招聘信息"

    # 检查用户选择的城市是否存在
    if check_city(request.GET.get("city_name", False)):
        request.session["job_city"] = request.GET.get("city_name")
    else:
        return index(request=request)

    # 打印表单
    if request.method == "GET":
        form = JobForm()
        return render("jobs_add.html", locals(), context_instance=RequestContext(request))

    # 处理提交数据
    form = JobForm(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        new_job = Job()
        new_job.title = data["title"]
        new_job.city = request.session.get("job_city", "北京")
        new_job.company = data["company"]
        new_job.website = data["website"]
        new_job.email = data["email"]
        new_job.content = data["content"]
        try:
            new_job.save()
        except Exception, e:
            return HttpResponse("保存招聘信息时出现错误:" + str(e))
        else:
            msg = "提交成功,正在等待管理员审核..."
            # 发送信号
            new_job_was_post.send(sender=new_job.__class__, job=new_job)
        return render("posted.html", locals(), context_instance=RequestContext(request))
Example #25
0
 def check_server_disallowed(self):
     """
     Check if server domain name or IP is disallowed in settings.py.
     """
     hostname = self.netloc_parts[2].lower()
     if (hasattr(settings, 'DISALLOWED_DOMAIN_LIST') and
         settings.DISALLOWED_DOMAIN_LIST):
         for domain in settings.DISALLOWED_DOMAIN_LIST:
             if hostname == domain or hostname.endswith('.' + domain):
                 raise ValidationError(unicode(
                     _("Domain name %(domain)s is disallowed.") % locals()))
     try:
         ip = socket.gethostbyname(hostname)
     except socket.error:
         raise ValidationError(unicode(
             _("Could not resolve IP address for %(hostname)s.") %
             locals()))
     if (not hasattr(settings, 'DISALLOWED_SERVER_IP_LIST') or
         not settings.DISALLOWED_SERVER_IP_LIST):
         return
     server = long_ip(ip)
     # print 'server', server, dotted_ip(server), ip
     for disallowed in settings.DISALLOWED_SERVER_IP_LIST:
         disallowed = disallowed.strip()
         if disallowed == '' or disallowed.startswith('#'):
             continue
         mask = bit_mask(32)
         if '/' in disallowed:
             disallowed, bits = disallowed.split('/', 1)
             mask = slash_mask(int(bits))
         identifier = long_ip(disallowed) & mask
         masked = server & mask
         if masked == identifier:
             raise ValidationError(unicode(
                 _("Server IP address %(ip)s is disallowed.") % locals()))
Example #26
0
def find_iso_sr(session):
    """Return the storage repository to hold ISO images"""
    host = session.get_xenapi_host()
    sr_refs = session.get_xenapi().SR.get_all()
    for sr_ref in sr_refs:
        sr_rec = session.get_xenapi().SR.get_record(sr_ref)

        LOG.debug(_("ISO: looking at SR %(sr_rec)s") % locals())
        if not sr_rec["content_type"] == "iso":
            LOG.debug(_("ISO: not iso content"))
            continue
        if not "i18n-key" in sr_rec["other_config"]:
            LOG.debug(_("ISO: iso content_type, no 'i18n-key' key"))
            continue
        if not sr_rec["other_config"]["i18n-key"] == "local-storage-iso":
            LOG.debug(_("ISO: iso content_type, i18n-key value not " "'local-storage-iso'"))
            continue

        LOG.debug(_("ISO: SR MATCHing our criteria"))
        for pbd_ref in sr_rec["PBDs"]:
            LOG.debug(_("ISO: ISO, looking to see if it is host local"))
            pbd_rec = session.get_xenapi().PBD.get_record(pbd_ref)
            pbd_rec_host = pbd_rec["host"]
            LOG.debug(_("ISO: PBD matching, want %(pbd_rec)s, have %(host)s") % locals())
            if pbd_rec_host == host:
                LOG.debug(_("ISO: SR with local PBD"))
                return sr_ref
    return None
 def input_conversion(self, cpp_type, argument_var, arg_num):
     temp_var = "v%d" % arg_num
     temp_it = "it_%d" % arg_num
     item = "item%d" % arg_num
     code = Code().add(
         """
         |cdef libcpp_vector[_String] * $temp_var = new libcpp_vector[_String]()
         |cdef bytes $item
         |for $item in $argument_var:
         |   $temp_var.push_back(_String(<char *>$item))
         """,
         locals(),
     )
     if cpp_type.is_ref:
         cleanup_code = Code().add(
             """
             |replace = []
             |cdef libcpp_vector[_String].iterator $temp_it = $temp_var.begin()
             |while $temp_it != $temp_var.end():
             |   replace.append(<char*>deref($temp_it).c_str())
             |   inc($temp_it)
             |$argument_var[:] = replace
             |del $temp_var
             """,
             locals(),
         )
     else:
         cleanup_code = "del %s" % temp_var
     return code, "deref(%s)" % temp_var, cleanup_code
Example #28
0
def user():
    "login, registration, etc."
    searchstring = session.searchstring or ""
    rpx = ""
    registerurl = URL("default", "user", args="register")
    if request.vars.token:
        auth.settings.login_form = rpxform
        form = auth()
        return locals()

    if "login" in request.args:
        rpx = rpxform.login_form()
        html = DIV(
            DIV(
                H2(A("Click here to register", _href=registerurl), _id="extra_register"),
                H3("Or login if you already have an account"),
                auth(),
                SPAN(A("Forgot My Password", _href=URL(r=request, args="request_reset_password"))),
                _id="login_auth",
            ),
            DIV(BR(), H3("You can also make use of existing identities"), rpx, _id="login_rpx"),
        )
    else:
        html = DIV(auth(), _id="user_form")

    form = html

    latest_users = []

    return locals()
Example #29
0
    def __call__(self, track, slice=None):

        edir = EXPORTDIR

        toc_text = []
        link_text = []

        tracks = sorted([x.asFile() for x in TRACKS])
        print tracks
        print "hello"
        for track in tracks:

            for x, fn in enumerate(glob.glob(os.path.join(EXPORTDIR, "fastqc", "%s*_fastqc" % track))):
                y = x + 1
                toc_text.append("* %(track)s-%(y)i_" % locals())
                link_text.append(".. _%(track)s-%(y)i: %(fn)s/fastqc_report.html" % locals())

        print toc_text
        toc_text = "\n".join(toc_text)
        print toc_text
        print link_text
        link_text = "\n".join(link_text)
        print link_text
        rst_text = "\n%(toc_text)s\n\n%(link_text)s\n" % locals()

        print rst_text
        return odict((("text", rst_text),))
Example #30
0
    def __call__(self, req):
        if not self.has_authentication(req):
            return self.authenticate(req)
        user = self.get_user_by_authentication(req)
        accounts = self.auth.get_projects(user=user)
        if not user:
            token = req.headers["X-Auth-Token"]
            msg = _("%(user)s could not be found with token '%(token)s'")
            LOG.warn(msg % locals())
            return faults.Fault(webob.exc.HTTPUnauthorized())

        if accounts:
            # we are punting on this til auth is settled,
            # and possibly til api v1.1 (mdragon)
            account = accounts[0]
        else:
            return faults.Fault(webob.exc.HTTPUnauthorized())

        if not self.auth.is_admin(user) and not self.auth.is_project_member(user, account):
            msg = _("%(user)s must be an admin or a member of %(account)s")
            LOG.warn(msg % locals())
            return faults.Fault(webob.exc.HTTPUnauthorized())

        req.environ["nova.context"] = context.RequestContext(user, account)
        return self.application