Example #1
2
 def debug(self, msg, traceback=1):
     msg = str(msg)
     curframe = None
     """
     for x in xrange(0,100):
         frame = inspect.currentframe(x)
         print "trying frame["+str(x)+"]"
         if frame.f_back is None:
             print "this frame is none, will use frame["+str(x-1)+"] instead"
             break
         else:
             curframe = frame
             lineno = curframe.f_lineno
     """
     curframe = inspect.currentframe(traceback)
     lineno = curframe.f_lineno
     self.curframe = curframe
     frame_code = curframe.f_code
     frame_globals = curframe.f_globals
     functype = type(lambda: 0)
     funcs = []
     for func in gc.get_referrers(frame_code):
         if type(func) is functype:
             if getattr(func, "func_code", None) is frame_code:
                 if getattr(func, "func_globals", None) is frame_globals:
                     funcs.append(func)
                     if len(funcs) > 1:
                         return None
         cur_method = funcs[0].func_name if funcs else ""
     for line in msg.split("\n"):
         self.tester.debug("(" + str(cur_method) + ":" + str(lineno) + "): " + line.strip())
Example #2
1
    def pct(self, so_far, total=None):
        percentage = str(int(self.percentage * 100)) + "%"
        if self.num_files_left > 1:
            message = _("Uploading %(number)d files to %(service)s") % {
                "number": self.num_files_left,
                "service": '"' + service["name"] + '"',
            }
            title = _("%(percentage)s of %(number)d files - Uploading to %(service)s") % {
                "percentage": percentage,
                "number": self.num_files_left,
                "service": '"' + service["name"] + '"',
            }
        else:
            message = _("Uploading 1 file to %(service)s") % {"service": '"' + service["name"] + '"'}
            title = _("%(percentage)s of 1 file - Uploading to %(service)s") % {
                "percentage": percentage,
                "service": '"' + service["name"] + '"',
            }

        self.percentage = float(self.size_so_far) / float(self.total_size)
        Gdk.threads_enter()
        try:
            self.progressbar.set_fraction(self.percentage)
            self.progressbar.set_text(str(int(self.percentage * 100)) + "%")
            self.builder.get_object("upload_label").set_text(message)
            self.builder.get_object("main_window").set_title(title)
        finally:
            Gdk.threads_leave()
        pass
 def __str__(self):
     msg = []
     msg.append("Choreo Execution")
     msg.append("Path: " + str(self.choreo_uri))
     msg.append("Execution ID: " + str(self.exec_id))
     msg.append("Status: " + str(self.status))
     return "\n".join(msg)
 def __init__(self, objeto=None, usuario=None):
     """
     Constructor. objeto puede ser un objeto de pclases con el que
     comenzar la ventana (en lugar del primero de la tabla, que es
     el que se muestra por defecto).
     """
     global fin
     Ventana.__init__(self, "consulta_albaranesFacturados.glade", objeto, usuario=usuario)
     connections = {
         "b_salir/clicked": self.salir,
         "b_buscar/clicked": self.buscar,
         "b_imprimir/clicked": self.imprimir,
         "b_fecha_inicio/clicked": self.set_inicio,
         "b_fecha_fin/clicked": self.set_fin,
         "b_exportar/clicked": self.exportar,
     }
     self.add_connections(connections)
     cols = (
         ("Fecha", "gobject.TYPE_STRING", False, True, False, None),
         ("Nº Albarán", "gobject.TYPE_STRING", False, True, True, None),
         ("Cliente", "gobject.TYPE_STRING", False, True, False, None),
         ("Num. Factura", "gobject.TYPE_STRING", False, True, False, None),
         ("Idalbaran", "gobject.TYPE_INT64", False, False, False, None),
     )
     utils.preparar_listview(self.wids["tv_datos"], cols)
     self.wids["tv_datos"].connect("row-activated", self.abrir_albaran)
     temp = time.localtime()
     self.fin = str(temp[0]) + "/" + str(temp[1]) + "/" + str(temp[2])
     self.wids["e_fechafin"].set_text(utils.str_fecha(temp))
     self.wids["rb_salida"].set_active(True)
     gtk.main()
Example #5
1
    def processAlgorithm(self, progress):
        commands = []
        commands.append(os.path.join(TauDEMUtils.mpiexecPath(), "mpiexec"))

        processNum = ProcessingConfig.getSetting(TauDEMUtils.MPI_PROCESSES)
        if processNum <= 0:
            raise GeoAlgorithmExecutionException(
                self.tr(
                    "Wrong number of MPI processes used. Please set " "correct number before running TauDEM algorithms."
                )
            )

        commands.append("-n")
        commands.append(str(processNum))
        commands.append(os.path.join(TauDEMUtils.taudemPath(), self.cmdName))
        commands.append("-ad8")
        commands.append(self.getParameterValue(self.D8_CONTRIB_AREA_GRID))
        commands.append("-p")
        commands.append(self.getParameterValue(self.D8_FLOW_DIR_GRID))
        commands.append("-fel")
        commands.append(self.getParameterValue(self.PIT_FILLED_GRID))
        commands.append("-ssa")
        commands.append(self.getParameterValue(self.ACCUM_STREAM_SOURCE_GRID))
        commands.append("-o")
        commands.append(self.getParameterValue(self.OUTLETS_SHAPE))
        commands.append("-par")
        commands.append(str(self.getParameterValue(self.MIN_TRESHOLD)))
        commands.append(str(self.getParameterValue(self.MAX_THRESHOLD)))
        commands.append(str(self.getParameterValue(self.TRESHOLD_NUM)))
        commands.append(str(self.getParameterValue(self.STEPS)))
        commands.append("-drp")
        commands.append(self.getOutputValue(self.DROP_ANALYSIS_FILE))

        TauDEMUtils.executeTauDEM(commands, progress)
Example #6
1
def main():
    socket_protocol = socket.IPPROTO_ICMP
    sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
    sniffer.bind((HOST, 0))
    sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

    while 1:
        raw_buffer = sniffer.recvfrom(65565)[0]
        ip_header = raw_buffer[0:20]
        iph = struct.unpack("!BBHHHBBH4s4s", ip_header)

        version_ihl = iph[0]
        version = version_ihl >> 4
        ihl = version_ihl & 0xF
        iph_length = ihl * 4
        ttl = iph[5]
        protocol = iph[6]
        s_addr = socket.inet_ntoa(iph[8])
        d_addr = socket.inet_ntoa(iph[9])
        print "IP->Version:" + str(version) + ",Header Length:" + str(ihl) + ",TTL:" + str(ttl) + ",Protocol:" + str(
            protocol
        ) + ",Source:" + str(s_addr) + ",Destination:" + str(d_addr)
        buf = raw_buffer[iph_length : iph_length + ctypes.sizeof(ICMP)]
        icmp_header = ICMP(buf)

        print "ICMP->Type:%d,Code:%d" % (icmp_header.type, icmp_header.code) + "\n"
Example #7
1
File: base.py Project: grigi/talkey
    def play(self, filename, translate=False):  # pragma: no cover
        """
        Plays the sounds.

        :filename: The input file name
        :translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV.
        """
        # FIXME: Use platform-independent and async audio-output here
        # PyAudio looks most promising, too bad about:
        #  --allow-external PyAudio --allow-unverified PyAudio
        if translate:
            with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
                fname = f.name
            with audioread.audio_open(filename) as f:
                with contextlib.closing(wave.open(fname, "w")) as of:
                    of.setnchannels(f.channels)
                    of.setframerate(f.samplerate)
                    of.setsampwidth(2)
                    for buf in f:
                        of.writeframes(buf)
            filename = fname

        if winsound:
            winsound.PlaySound(str(filename), winsound.SND_FILENAME)
        else:
            cmd = ["aplay", str(filename)]
            self._logger.debug("Executing %s", " ".join([pipes.quote(arg) for arg in cmd]))
            subprocess.call(cmd)

        if translate:
            os.remove(fname)
Example #8
1
 def make_nonce(self, request):
     "A digest-authentication <nonce>, constructed as suggested in RFC 2069"
     ip = request.channel.server.ip
     now = str(long(time.time()))[:-1]
     private_key = str(id(self))
     nonce = string.join([ip, now, private_key], ":")
     return self.apply_hash(nonce)
Example #9
1
 def run_test_case_list(self, list, eof=True, clean_on_exit=True, printresults=True):
     """
     wrapper to execute a list of ebsTestCase objects
     """
     try:
         for test in list:
             self.debug("Running list method:" + str(test.name))
             try:
                 test.run()
             except Exception, e:
                 self.debug("Testcase:" + str(test.name) + " error:" + str(e))
                 if eof:
                     raise e
                 else:
                     pass
     finally:
         try:
             if clean_on_exit:
                 self.clean_created_resources()
         except:
             pass
         if printresults:
             try:
                 self.print_test_list_results()
             except:
                 pass
def linear_check_wind(year, month, day, hour):
    yday = day_of_year(year, month, day)
    nldas_fn = (
        "NLDAS_data/"
        + str(year)
        + "/"
        + yday
        + "/"
        + "NLDAS_FORA0125_H.A"
        + str(year)
        + str(month).zfill(2)
        + str(day).zfill(2)
        + "."
        + str(hour).zfill(2)
        + "00.002.grb"
    )
    nldas_ds = gdal.Open(nldas_fn, GA_ReadOnly)
    nldas_gt = nldas_ds.GetGeoTransform()
    u_raster = find_band_raster(nldas_ds, "UGRD")
    v_raster = find_band_raster(nldas_ds, "VGRD")
    wind_raster = np.sqrt(u_raster ** 2 + v_raster ** 2)
    dem, bilinear_result = bilinear_interpolation(wind_raster, nldas_gt)
    # plt.imshow(bilinear_result)
    plt.plot(dem.flatten(), bilinear_result.flatten(), ".b")
    plt.show()
Example #11
0
def ScanFiles(theFile, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files):
    """ For theFile (a Node) update any file_tests and search for graphics files
    then find all included files and call ScanFiles recursively for each of them"""

    content = theFile.get_text_contents()
    if Verbose:
        print " scanning ", str(theFile)

    for i in range(len(file_tests_search)):
        if file_tests[i][0] is None:
            file_tests[i][0] = file_tests_search[i].search(content)

    incResult = includeOnly_re.search(content)
    if incResult:
        aux_files.append(os.path.join(targetdir, incResult.group(1)))
    if Verbose:
        print "\include file names : ", aux_files
    # recursively call this on each of the included files
    inc_files = []
    inc_files.extend(include_re.findall(content))
    if Verbose:
        print "files included by '%s': " % str(theFile), inc_files
    # inc_files is list of file names as given. need to find them
    # using TEXINPUTS paths.

    for src in inc_files:
        srcNode = FindFile(src, [".tex", ".ltx", ".latex"], paths, env, requireExt=False)
        if srcNode is not None:
            file_tests = ScanFiles(
                srcNode, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files
            )
    if Verbose:
        print " done scanning ", str(theFile)
    return file_tests
Example #12
0
    def block_locator_hashes(self):
        "Return a list of hashes suitable as a block locator hash."

        # Find the height of the block chain
        hashes = []

        # First 10...
        offset = 0
        cursor = self._cursor()
        cursor.execute(
            "select hash, height from blocks where mainchain = 1 and height > 0 order by height desc limit 10"
        )
        rows = cursor.fetchall()
        hashes.extend([str(hash) for (hash, offset) in rows])
        offset -= 1

        # ...then step down by twice the previous step...
        if offset > 0:
            for i in xrange(1, int(math.log(2 * offset, 2))):
                if offset <= 1:
                    break
                cursor.execute("select hash from blocks where mainchain = 1 and height = ?", (offset,))
                hashes.append(str(cursor.fetchone()[0]))
                offset -= 1 << i

        # ...finally the genesis hash
        hashes.append(self.coin.genesis_block_hash)

        return hashes
Example #13
0
    def _read_input(self):
        log_entry = {}
        while True:
            try:
                line = self.input_stream.readline()
            except KeyboardInterrupt:
                return

            if not line:
                time.sleep(0.2)
            else:
                line = line.strip()
                if line == "end":
                    return log_entry
                elif line == "quit":
                    return
                else:
                    try:
                        field, value = line.split("=", 1)
                        if field.find(":") > -1:
                            field, validator = field.split(":", 1)
                            if validator == "timestamp":
                                value = int(float(value) * 1000)
                            else:
                                value = str(value)
                        log_entry[field] = value
                    except Exception, e:
                        self.logger.critical(str(e))
                        pass
                self.logger.debug(line)
Example #14
0
def sow_dev(pr_id):
    u = user_check_project_access(pr_id)
    check_project_stage(pr_id, 4)
    latest = [i for i in Sow.select().where(Sow.pid == pr_id).order_by(Sow.edit_time.desc()).limit(1)]
    if not len(latest):
        redirect("/projects/" + str(pr_id))
    latest = latest[0]
    headers = [i for i in Header.select().where(Header.sowid == latest.id).order_by(Header.nlevel.asc())]
    data = {}
    num_by_id = {}
    for i in headers:
        if i.nlevel == 1:
            data[i.num] = {}
            data[i.num]["h1"] = i
            num_by_id[i.id] = i.num
        else:
            data[num_by_id[i.parent]][i.num] = i
    for k, i in data.items():
        data[k] = sorted(i.values(), key=lambda x: (x.nlevel, x.num))
    return template2(
        "andrew/stage4",
        data=data,
        pr_id=pr_id,
        ver=PROJECT_VERSION,
        date=str(datetime.now())[:-7],
        cur_author=u.nickname,
    )
Example #15
0
def sow_dev_load(pr_id, header_id):
    u = user_check_project_access(pr_id)
    check_project_stage(pr_id, 4)
    header = Header.get(Header.id == header_id)
    res = []
    for i in Ticket.select().where(Ticket.hid == header_id).order_by(Ticket.add_time.asc()):
        comments = []
        for j in Comment.select().where(Comment.tid == i.id).order_by(Comment.add_time.asc()):
            cur = dict(
                id=j.id,
                nick=str(j.nick),
                tid=j.tid,
                msg=md2html_line(fix_string(str(j.msg))),
                add_time=str(j.add_time),
                edit_time=str(j.edit_time),
                pid=str(j.pid),
            )
            comments.append(cur)
        cur = dict(
            id=i.id,
            name=md2html_line(fix_string(str(i.name))),
            content=md2html_line(fix_string(str(i.content))),
            add_time=i.add_time,
            hid=i.hid,
            category=i.category,
            closed=str(i.closed).lower(),
            close_time=i.close_time,
            nickname=i.nickname,
            pid=i.pid,
            comments=comments,
        )
        res.append(cur)
    my_priv = check_user_rights(u.id, pr_id, "w")
    data = {"ro": str(not my_priv), "html": header.html, "tickets": res}
    return str(data).replace("'", '"')
Example #16
0
    def pprint_getters(self):
        """
        Return the getters and actual values as list of strings.
        """

        o = self.oorig
        getters = [name for name in dir(o) if name.startswith("get_") and callable(getattr(o, name))]
        # print getters
        getters.sort()
        lines = []
        for name in getters:
            func = getattr(o, name)
            if self.is_alias(func):
                continue

            try:
                val = func()
            except:
                continue
            if getattr(val, "shape", ()) != () and len(val) > 6:
                s = str(val[:6]) + "..."
            else:
                s = str(val)
            s = s.replace("\n", " ")
            if len(s) > 50:
                s = s[:50] + "..."
            name = self.aliased_name(name[4:])
            lines.append("    %s = %s" % (name, s))
        return lines
Example #17
0
    def _iprange_to_glob(lb, ub):
        #   Internal function to process individual IP globs.
        t1 = [int(_) for _ in str(lb).split(".")]
        t2 = [int(_) for _ in str(ub).split(".")]

        tokens = []

        seen_hyphen = False
        seen_asterisk = False

        for i in range(4):
            if t1[i] == t2[i]:
                #   A normal octet.
                tokens.append(str(t1[i]))
            elif (t1[i] == 0) and (t2[i] == 255):
                #   An asterisk octet.
                tokens.append("*")
                seen_asterisk = True
            else:
                #   Create a hyphenated octet - only one allowed per IP glob.
                if not seen_asterisk:
                    if not seen_hyphen:
                        tokens.append("%s-%s" % (t1[i], t2[i]))
                        seen_hyphen = True
                    else:
                        raise AddrConversionError("only 1 hyphenated octet" " per IP glob allowed!")
                else:
                    raise AddrConversionError(
                        "asterisks are not allowed' \
                        ' before hyphenated octets!"
                    )

        return ".".join(tokens)
Example #18
0
    def updateState(self, set):
        c = self

        bytes_sent = c.getBytesSent()
        bytes_received = c.getBytesReceived()
        uptime = c.getUptime()

        set("stream-mime", c.get_mime())
        set("stream-url", c.getUrl())
        set("stream-uptime", formatting.formatTime(uptime))
        bitspeed = bytes_received * 8 / uptime
        currentbitrate = self.getCurrentBitrate()
        set("stream-bitrate", formatting.formatStorage(bitspeed) + "bit/s")
        set("stream-current-bitrate", formatting.formatStorage(currentbitrate) + "bit/s")
        set("stream-totalbytes", formatting.formatStorage(bytes_received) + "Byte")
        set("stream-bitrate-raw", bitspeed)
        set("stream-totalbytes-raw", bytes_received)

        set("clients-current", str(c.getClients()))
        set("clients-max", str(c.getMaxClients()))
        set("clients-peak", str(c.getPeakClients()))
        set("clients-peak-time", c.getPeakEpoch())
        set("clients-average", str(int(c.getAverageClients())))

        bitspeed = bytes_sent * 8 / uptime
        set("consumption-bitrate", formatting.formatStorage(bitspeed) + "bit/s")
        set("consumption-bitrate-current", formatting.formatStorage(currentbitrate * c.getClients()) + "bit/s")
        set("consumption-totalbytes", formatting.formatStorage(bytes_sent) + "Byte")
        set("consumption-bitrate-raw", bitspeed)
        set("consumption-totalbytes-raw", bytes_sent)
Example #19
0
    def rescue(self, error_list, sleep_interval):
        error_files = []
        error_msg = []

        for city in error_list:
            try:
                print "[start ] fetching deals in", city
                page_num = self.crawler.fetch_deal_in(city)
                print "[finish] fetching deals in", city

                if page_num == 1 or page_num == None:
                    self.parser.parse(os.path.join(self.source, city))
                else:
                    for i in xrange(1, page_num + 1):
                        if i == 1:
                            self.parser.parse(os.path.join(self.source, city))
                        else:
                            self.parser.parse(os.path.join(self.source, city + "_" + str(i)))

                wait_time = random.randint(sleep_interval[0], sleep_interval[1])
                print "wait", wait_time, "seconds"
                time.sleep(wait_time)

            except Exception, e:
                error_files.append(city)
                error_msg.append(str(e))
                print "Error in parsing data in", city
                print e
Example #20
0
def _dosave(request, viewName):
    profile = getProfile(request)
    # First find our View
    log.info("Saving view '%s' under profile '%s'" % (viewName, profile.user.username))
    try:
        view = profile.view_set.get(name=viewName)
    except ObjectDoesNotExist:
        view = View(profile=profile, name=viewName)
        view.save()
    # Now re-associate the view with the correct Windows
    view.window_set.all().delete()
    for windowName, encodedString in request.GET.items():
        try:
            if windowName in ("_", "commandInput"):
                continue
            paramString = urllib.unquote_plus(encodedString)
            queryParams = cgi.parse_qs(paramString)
            modelParams = {}
            for key, value in queryParams.items():  # Clean up the window params
                key = str(key)
                value = str(value[0])
                if key in ("top", "left"):
                    value = int(float(value.replace("px", "")))
                if key in ("width", "height", "interval"):
                    value = int(float(value))
                modelParams[key] = value
            if "interval" not in modelParams:
                modelParams["interval"] = None
            win = Window(view=view, name=windowName, **modelParams)
            win.save()
        except:
            log.exception("Failed to process parameters for window '%s'" % windowName)
    return stdout("Saved view %s" % viewName)
Example #21
0
def is_effective_user(user_id_or_name):
    """Returns True if user_id_or_name is effective user (id/name)."""
    euid = os.geteuid()
    if str(user_id_or_name) == str(euid):
        return True
    effective_user_name = pwd.getpwuid(euid).pw_name
    return user_id_or_name == effective_user_name
Example #22
0
            def cb(ec, history, order):

                # Debug
                # self._log.info('%s %s' % (ec, history))

                if ec is not None:
                    self._log.error("Error fetching history: %s" % ec)
                    # TODO: Send error message to GUI
                    return

                unspent = [row[:4] for row in history if row[4] is None]

                # Send all unspent outputs (everything in the address) minus the fee
                inputs = []
                for row in unspent:
                    assert len(row) == 4
                    inputs.append(str(row[0].encode("hex")) + ":" + str(row[1]))

                seller_signatures = []
                print "private key ", self._transport.settings["privkey"]
                for x in range(0, len(inputs)):
                    ms = multisign(tx, x, script, self._transport.settings["privkey"])
                    print "seller sig", ms
                    seller_signatures.append(ms)

                tx2 = pybitcointools.apply_multisignatures(tx, 0, script, seller_signatures[0], msg["signatures"][0])

                print "FINAL SCRIPT: %s" % tx2
                print "Sent", pybitcointools.eligius_pushtx(tx2)
    def test_get_versions(self):

        # get_versions calls distutils.spawn.find_executable on
        # 'gcc', 'ld' and 'dllwrap'
        self.assertEquals(get_versions(), (None, None, None))

        # Let's fake we have 'gcc' and it returns '3.4.5'
        self._exes["gcc"] = b"gcc (GCC) 3.4.5 (mingw special)\nFSF"
        res = get_versions()
        self.assertEquals(str(res[0]), "3.4.5")

        # and let's see what happens when the version
        # doesn't match the regular expression
        # (\d+\.\d+(\.\d+)*)
        self._exes["gcc"] = b"very strange output"
        res = get_versions()
        self.assertEquals(res[0], None)

        # same thing for ld
        self._exes["ld"] = b"GNU ld version 2.17.50 20060824"
        res = get_versions()
        self.assertEquals(str(res[1]), "2.17.50")
        self._exes["ld"] = b"@(#)PROGRAM:ld  PROJECT:ld64-77"
        res = get_versions()
        self.assertEquals(res[1], None)

        # and dllwrap
        self._exes["dllwrap"] = b"GNU dllwrap 2.17.50 20060824\nFSF"
        res = get_versions()
        self.assertEquals(str(res[2]), "2.17.50")
        self._exes["dllwrap"] = b"Cheese Wrap"
        res = get_versions()
        self.assertEquals(res[2], None)
Example #24
0
def test_get_template_statistics_for_service(notify_db, notify_db_session, notify_api, sample_service):
    sms = sample_template(notify_db, notify_db_session, service=sample_service)
    email = sample_email_template(notify_db, notify_db_session, service=sample_service)
    today = datetime.now()
    sample_notification(notify_db, notify_db_session, created_at=today, service=sample_service, template=sms)
    sample_notification(notify_db, notify_db_session, created_at=today, service=sample_service, template=sms)
    sample_notification(notify_db, notify_db_session, created_at=today, service=sample_service, template=email)
    sample_notification(notify_db, notify_db_session, created_at=today, service=sample_service, template=email)

    with notify_api.test_request_context():
        with notify_api.test_client() as client:
            auth_header = create_authorization_header()

            response = client.get(
                "/service/{}/template-statistics".format(sample_service.id),
                headers=[("Content-Type", "application/json"), auth_header],
            )

            assert response.status_code == 200
            json_resp = json.loads(response.get_data(as_text=True))
            assert len(json_resp["data"]) == 2
            assert json_resp["data"][0]["count"] == 2
            assert json_resp["data"][0]["template_id"] == str(email.id)
            assert json_resp["data"][0]["template_name"] == email.name
            assert json_resp["data"][0]["template_type"] == email.template_type
            assert json_resp["data"][1]["count"] == 2
            assert json_resp["data"][1]["template_id"] == str(sms.id)
            assert json_resp["data"][1]["template_name"] == sms.name
            assert json_resp["data"][1]["template_type"] == sms.template_type
Example #25
0
def plot_value_function(agent_class, run, i):
    """ Plot the value functions for run i. """
    plt.clf()
    agent = load(agent_class, run)
    state0 = simulator.Simulator().get_state()
    values, qval1, qval2 = [], [], []
    min_range = -SHIFT_VECTOR[i]
    max_range = SCALE_VECTOR[i]
    variables = []
    for j in range(VALUE_STEPS):
        var = max_range * (1.0 * j / VALUE_STEPS) + min_range
        state0[i] = var
        values.append(agent.value_function(state0))
        feat = agent.action_features[0](state0)
        qval1.append(agent.action_weights[0].dot(feat))
        qval2.append(agent.action_weights[1].dot(feat))
        variables.append(var)
    max_val = max(max(qval1), max(qval2), min(values))
    min_val = min(min(qval1), min(qval2), min(values))
    plt.plot(variables, values, "-b", label="$V(s)$")
    plt.plot(variables, qval1, "-r", label="$Q(s, a_1)$")
    plt.plot(variables, qval2, "-g", label="$Q(s, a_2)$")
    plt.axis([min_range, max_range, min_val, max_val])
    plt.legend(loc="lower right")
    plt.xlabel(str(i))
    plt.ylabel("$V$")
    plt.savefig("./runs/" + agent.name + "/value_functions/s" + str(i), bbox_inches="tight")
Example #26
0
def integrate_map(
    band,
    skypos,
    tranges,
    skyrange,
    width=False,
    height=False,
    verbose=0,
    memlight=False,
    hdu=False,
    retries=20,
    response=False,
):
    """ Integrate an image over some number of time ranges. Use a reduced
	memory optimization (at the expense of more web queries) if requested.
	"""
    imsz = gxt.deg2pix(skypos, skyrange)
    img = np.zeros(imsz)
    for trange in tranges:
        # If memlight is requested, break the integration into
        #  smaller chunks.
        # FIXME: memlight gives slightly wrong answers right now
        # This is probably due to a quirk of SQL, per issue #140.
        # Deprecating memlight until this can be resolved.
        step = memlight if memlight else trange[1] - trange[0]
        for i in np.arange(trange[0], trange[1], step):
            t0, t1 = i, i + step
            if verbose:
                mc.print_inline("Coadding " + str(t0) + " to " + str(t1))
            img += makemap(band, skypos, [t0, t1], skyrange, response=response, verbose=verbose)
        if response:  # This is an intensity map.
            img /= dbt.compute_exptime(band, trange, skypos=skypos, verbose=verbose)

    return img
Example #27
0
    def test_database_record(self):
        """Convert worksheet row contents to proper types."""
        self.test_row = {
            "appointmentdate1": "02/09/2011",
            "fileno": "63601",
            "appointmentstatus1": "Scheduled",
            "phonenumber": "969577542",
        }
        self.modified_row = self.reader.database_record(self.test_row)
        self.app_date = self.modified_row["appointmentdate1"]
        self.app_status = self.modified_row["appointmentstatus1"]
        self.file_no = self.modified_row["fileno"]
        self.phone = self.modified_row["phonenumber"]

        # test if the fields where converted correctly
        self.assertEquals(self.app_date, date(2011, 9, 2))
        self.assertEquals(self.app_status, self.test_row["appointmentstatus1"])
        self.assertEquals(self.file_no, "63601")
        self.assertEquals(self.phone, 969577542)

        # test if the received fields are equal to those sent
        self.app_date = str(self.app_date)
        self.app_date = self.reader.date_format(self.app_date)
        self.assertEquals(self.app_date, self.test_row["appointmentdate1"])
        self.app_status = str(self.app_status)
        self.assertEquals(self.app_status, self.test_row["appointmentstatus1"])
        self.file_no = str(self.file_no)
        self.assertEquals(self.file_no, self.test_row["fileno"])
        self.phone = str(self.phone)
        self.assertEquals(self.phone, self.test_row["phonenumber"])
Example #28
0
    def run(self):
        while not self.__stop:
            val = readMessage(self.__sock)
            if val is None:
                time.sleep(0.01)
                continue
            (data, addr) = val

            env = parseEnvelope(data)

            mid = env.getMessageId()
            if self.__midMap.has_key(mid):
                continue
            else:
                self.__midMap[mid] = 0

            iid = env.getInstanceId()
            mid = env.getMessageId()
            if iid > 0:
                mnum = env.getMessageNumber()
                key = addr[0] + ":" + str(addr[1]) + ":" + str(iid)
                if mid is not None and len(mid) > 0:
                    key = key + ":" + mid
                if not self.__iidMap.has_key(key):
                    self.__iidMap[key] = iid
                else:
                    tmnum = self.__iidMap[key]
                    if mnum > tmnum:
                        self.__iidMap[key] = mnum
                    else:
                        continue

            self.__observer.envReceived(env, addr)
Example #29
0
def saveCoursesFile(fileName, dataStructure):  # exception flag.
    fileOut = open(fileName, "w")  # open file in write mode.

    headerOfFile = "First name," + "Surname," + "ID number,"  # builds the first line
    i = 1
    while i <= len(courses.items()[0][1]) - 3:
        headerOfFile = headerOfFile + "Assignment: Laboratory " + str(i) + ","
        i = i + 1

    headerOfFile = headerOfFile[:-1] + "\n"
    fileOut.write(headerOfFile)

    for ID in dataStructure:  # writting into file sequence.
        line = (
            dataStructure[ID]["firstName"]
            + ","
            + dataStructure[ID]["surname"]
            + ","
            + dataStructure[ID]["IDNumber"]
            + ","
        )

        i = 1
        while i <= len(courses.items()[0][1]) - 3:
            field = "lab" + str(i)
            line = line + dataStructure[ID][field] + ","
            i = i + 1
        line = line[:-1] + "\n"

        if debug == 1:
            print line

        fileOut.write(line)

    fileOut.close()  # close file.
Example #30
0
    def read(cls, ids, fields_names=None):
        if fields_names:
            fields_names2 = [x for x in fields_names if not x.startswith("analytic_account_")]
        else:
            fields_names2 = fields_names

        res = super(SaleLine, cls).read(ids, fields_names=fields_names2)

        if not fields_names:
            fields_names = cls._fields.keys()

        root_ids = []
        for field in fields_names:
            if field.startswith("analytic_account_") and "." not in field:
                root_ids.append(int(field[len("analytic_account_") :]))
        if root_ids:
            id2record = {}
            for record in res:
                id2record[record["id"]] = record
            lines = cls.browse(ids)
            for line in lines:
                for root_id in root_ids:
                    id2record[line.id]["analytic_account_" + str(root_id)] = None
                if line.type != "line":
                    continue
                if not line.analytic_accounts:
                    continue
                for account in line.analytic_accounts.accounts:
                    if account.root.id in root_ids:
                        id2record[line.id]["analytic_account_" + str(account.root.id)] = account.id
                        for field in fields_names:
                            if field.startswith("analytic_account_" + str(account.root.id) + "."):
                                ham, field2 = field.split(".", 1)
                                id2record[line.id][field] = account[field2]
        return res