Ejemplo n.º 1
0
    def _clean(self, ar):
        nchan = ar.get_nchan()
        nsub = ar.get_nsubint()
        weights = (ar.get_weights() > 0)

        nchan_masked = np.sum(weights.sum(axis=0) == 0)
        nsub_masked = np.sum(weights.sum(axis=1) == 0)

        sub_badfrac = 1 - weights.sum(axis=1) / float(nchan - nchan_masked)
        chan_badfrac = 1 - weights.sum(axis=0) / float(nsub - nsub_masked)

        sub_is_bad = np.argwhere(sub_badfrac > self.configs.badchantol)
        utils.print_debug(
            "Number of subints to mask because too many "
            "channels are already masked: %d (%.1f %%)" %
            (sub_is_bad.size, 100.0 * sub_is_bad.size / nsub), 'clean')
        for isub in sub_is_bad:
            clean_utils.zero_weight_subint(ar, isub)

        chan_is_bad = np.argwhere(chan_badfrac > self.configs.badsubtol)
        utils.print_debug(
            "Number of channels to mask because too many "
            "subints are already masked: %d (%.1f %%)" %
            (chan_is_bad.size, 100.0 * chan_is_bad.size / nchan), 'clean')
        for ichan in chan_is_bad:
            clean_utils.zero_weight_chan(ar, ichan)
Ejemplo n.º 2
0
def signup():
    form = SignUpForm()
    if form.validate_on_submit():
        acct = Account(company_name=form.company_name.data)
        db.session.add(acct)
        db.session.commit()
        user = User(acct_id=acct.id,
                    first_name=form.first_name.data,
                    last_name=form.last_name.data,
                    email=form.email.data,
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()
        token = user.generate_token()
        print_debug(url_for('auth.confirm', token=token, _external=True))
        log_message(f'acct_id: {acct.id} just signed up')
        send_email(user.email,
                   'Confirm Your Account',
                   'confirm',
                   '*****@*****.**',
                   user=user,
                   token=token)
        flash(
            'You have been registered. A confirmation email is sent to your email address. \
               You have 24 hours to verify your account.')
        login_user(user)
        return redirect(url_for('dash.index'))
    return render_template('auth/signup.html.j2', form=form)
Ejemplo n.º 3
0
    def __init__(self, bike_routine: BikeRoutine) -> None:
        super().__init__(daemon=True)
        print_debug('New Timer Thread')

        self.bike_routine = bike_routine
        self.stop = False
        self.is_running = False
Ejemplo n.º 4
0
def clean_hot_bins(ar, thresh=2.0):
    subintdata = get_subints(ar, remove_prof=True)
    subintweights = get_subint_weights(ar).astype(bool)

    # re-disperse archive because subintdata is at DM=0
    orig_dm = ar.get_dispersion_measure()
    ar.set_dispersion_measure(0)
    ar.dedisperse()

    # Clean hot bins
    for isub, subintweight in enumerate(subintweights):
        if subintweight:
            # Identify hot bins
            subint = subintdata[isub, :]
            hot_bins = get_hot_bins(subint, normstat_thresh=thresh)[0]
            utils.print_info(
                "Cleaning %d bins in subint# %d" % (len(hot_bins), isub), 2)
            if len(hot_bins):
                clean_subint(ar, isub, hot_bins)
        else:
            # Subint is masked. Nothing to do.
            pass

    # Re-dedisperse data using original DM
    utils.print_debug("Re-dedispersing data", 'clean')
    ar.set_dispersion_measure(orig_dm)
    ar.dedisperse()
    utils.print_debug("Done re-dedispersing data", 'clean')
Ejemplo n.º 5
0
    def start(self, cmd=['crate'], ports={}, env=[], volumes={}):
        if self.is_running:
            raise InvalidState('Container is still running.')

        ulimits = [dict(name='memlock', soft=-1, hard=-1)]
        host_conf = self.cli.create_host_config(
            port_bindings=ports,
            binds=volumes,
            ulimits=ulimits,
        )

        self.assertTrue(len(cmd) >= 1)
        self.assertEquals(cmd[0], 'crate')

        cmd[1:1] = [
            '-Cbootstrap.memory_lock=true',
        ]
        env[0:0] = [
            'CRATE_HEAP_SIZE=128m',
        ]

        self.container = self.cli.create_container(image=self._layer.tag,
                                                   command=cmd,
                                                   ports=list(ports.keys()),
                                                   host_config=host_conf,
                                                   environment=env,
                                                   volumes=['/data'],
                                                   name=self.name)
        self.cli.start(self.container_id)
        process = self.crate_process()
        print_debug('Waiting for Docker container ...')
        while not process:
            time.sleep(0.1)
            process = self.crate_process()
        self.is_running = True
Ejemplo n.º 6
0
    def _clean(self, ar):
        reference = ar.clone()
        reference.pscrunch()
        if self.configs.fscrunchfirst:
            if ar.get_dedispersed():
                raise errors.CleanError("The 'hotbins' cleaner 'fscrunchfirst' " \
                                "can only be used on non-dedispersed data.")
            utils.print_debug("Determining hotbins based on f-scrunched data",
                              'clean')
            reference.set_dispersion_measure(0)
            reference.fscrunch()
        if self.configs.tscrunchfirst:
            utils.print_debug("Determining hotbins based on t-scrunched data",
                              'clean')
            reference.tscrunch()

        if self.configs.iscal:
            calbins = self.__locate_cal(ar)
            # Clean on-cal region
            self.__find_and_replace_hotbins(ar, reference, calbins)
            # Clean off-cal region
            self.__find_and_replace_hotbins(ar, reference, ~calbins)
        else:
            offbins = np.ones(ar.get_nbin(), dtype='bool')
            for lobin, hibin in self.configs.onpulse:
                offbins[lobin:hibin] = False
            self.__find_and_replace_hotbins(ar, reference, offbins)
Ejemplo n.º 7
0
    def _calculate_values_from_rev(self, time_in_seconds):
        self.total_time += time_in_seconds
        distance_in_metres = properties.bike.revolution_distance
        metres_per_seconds = distance_in_metres / time_in_seconds
        metres_per_seconds_history.append(metres_per_seconds)
        average_metres_per_seconds = mean(metres_per_seconds_history)

        total_average_speed = (self.revolutions *
                               distance_in_metres) / self.total_time

        x = {
            "last_rev_time": time_in_seconds,
            "total_revs": self.revolutions,
            "distance": self.revolutions * distance_in_metres / 1000,
            "rpm": 60 / time_in_seconds,
            "current_speed": average_metres_per_seconds * 3.6,
            "total_average_speed": total_average_speed * 3.6,
            "gear": self.gear,
            "duration": self.duration,
            "time": current_millis() * 1000000
        }

        if self.heart_rate_updated and self.heart_rate > 0:
            x['heartrate'] = self.heart_rate
            self.heart_rate = 0

        print_debug(x)

        self.data_points.append(x)

        return x
Ejemplo n.º 8
0
    def __remove_bad_channels(self, ar):
        """Zero-weight bad channels and channels containing bad
            frequencies. However, zero-weighting 
            is used for trimming, so the process is reversible.

            Inputs:
                ar: The psrchive archive object to clean.
        
            Outputs:
                None
        """
        if self.configs.badchans:
            nremoved = 0
            for tozap in self.configs.badchans:
                if type(tozap) is types.IntType:
                    # A single bad channel to zap
                    clean_utils.zero_weight_chan(ar, tozap)
                    nremoved += 1
                else:
                    # An (inclusive) interval of bad channels to zap
                    lochan, hichan = tozap
                    for xx in xrange(lochan, hichan):
                        clean_utils.zero_weight_chan(ar, tozap)
                        nremoved += 1
            utils.print_debug("Removed %d channels due to bad chans " \
                            "(%s) in %s" % (nremoved, self.configs.badfreqs, \
                            ar.get_filename()), 'clean')
        if self.configs.badfreqs:
            nremoved = 0
            # Get a list of frequencies
            nchan = ar.get_nchan()
            lofreqs = np.empty(nchan)
            hifreqs = np.empty(nchan)
            chanbw = ar.get_bandwidth() / nchan
            for ichan in xrange(nchan):
                prof = ar.get_Profile(0, 0, ichan)
                ctr = prof.get_centre_frequency()
                lofreqs[ichan] = ctr - chanbw / 2.0
                hifreqs[ichan] = ctr + chanbw / 2.0

            for tozap in self.configs.badfreqs:
                if type(tozap) is types.FloatType:
                    # A single bad freq to zap
                    for ichan in np.argwhere((lofreqs <= tozap)
                                             & (hifreqs > tozap)):
                        ichan = ichan.squeeze()
                        clean_utils.zero_weight_chan(ar, ichan)
                        nremoved += 1
                else:
                    # An (inclusive) interval of bad freqs to zap
                    flo, fhi = tozap
                    for ichan in np.argwhere((hifreqs >= flo)
                                             & (lofreqs <= fhi)):
                        ichan = ichan.squeeze()
                        clean_utils.zero_weight_chan(ar, ichan)
                        nremoved += 1
            utils.print_debug("Removed %d channels due to bad freqs " \
                            "(%s) in %s" % (nremoved, self.configs.badfreqs, \
                            ar.get_filename()), 'clean')
Ejemplo n.º 9
0
 def crate_process(self):
     proc = self.info(u'Processes')
     if not proc:
         return ''
     for p in proc[0]:
         if p.startswith('java'):
             print_debug('>>>', p)
             return p
     return ''
Ejemplo n.º 10
0
 def wait_for_cluster(self):
     print_debug('Waiting for CrateDB to start ...')
     for line in self.cli.logs(self.name, stream=True):
         l = line.decode("utf-8").strip('\n').strip()
         print_debug(l)
         if "[ERROR" in l:
             self.fail("Error in logs")
         if l.endswith('started'):
             break
Ejemplo n.º 11
0
 def wait_for_cluster(self):
     print_debug('Waiting for CrateDB to start ...')
     for line in self.cli.logs(self.name, stream=True):
         l = line.decode("utf-8").strip('\n').strip()
         print_debug(l)
         if "[ERROR" in l:
             self.fail("Error in logs")
         if l.endswith('started'):
             break
Ejemplo n.º 12
0
def get_hot_bins(data, normstat_thresh=6.3, max_num_hot=None, \
                    only_decreasing=True):
    """Return a list of indices that are bin numbers causing the
        given data to be different from normally distributed.
        The bins returned will contain the highest values in 'data'.

        Inputs:
            data: A 1-D array of data.
            normstat_thresh: The threshold for the Omnibus K^2
                statistic used to determine normality of data.
                (Default 6.3 -- 95% quantile for 50-100 data points)
            max_num_hot: The maximum number of hot bins to return.
                (Default: None -- no limit)
            only_decreasing: If True, stop collecting "hot" bins and return
                the current list if the K^2 statistic begins to increase
                as bins are removed. (Default: True)

        Outputs:
            hot_bins: A list of "hot" bins.
            status: A return status.
                    0 = Statistic is below threshold (success)
                    1 = Statistic was found to be increasing (OK)
                    2 = Max number of hot bins reached (not good)
    """
    masked_data = np.ma.masked_array(data, mask=np.zeros_like(data))

    prev_stat = scipy.stats.normaltest(masked_data.compressed())[0]
    while masked_data.count():
        if prev_stat < normstat_thresh:
            # Statistic is below threshold
            return (np.flatnonzero(masked_data.mask), 0)
        elif (max_num_hot is not None) and (len(hot_bins) >= max_num_hot):
            # Reached maximum number of hot bins
            return (np.flatnonzero(masked_data.mask), 2)

        imax = np.argmax(masked_data)
        imin = np.argmin(masked_data)
        median = np.median(masked_data)
        # find which (max or min) has largest deviation from the median
        median_to_max = masked_data[imax] - median
        median_to_min = median - masked_data[imin]

        if median_to_max > median_to_min:
            to_mask = imax
        else:
            to_mask = imin
        masked_data.mask[to_mask] = True
        curr_stat = scipy.stats.normaltest(masked_data.compressed())[0]
        utils.print_debug("hottest bin: %d, stat before: %g, stat after: %g" % \
                        (to_mask, prev_stat, curr_stat), 'clean')
        if only_decreasing and (curr_stat > prev_stat):
            # Stat is increasing and we don't want that!
            # Undo what we just masked and return the mask
            masked_data.mask[to_mask] = False
            return (np.flatnonzero(masked_data.mask), 1)
        # Iterate
        prev_stat = curr_stat
Ejemplo n.º 13
0
    def forward(self, src, tgt):
        src_seq_length, N = src.shape
        tgt_seq_length, N = tgt.shape
        

        #need to check
        print_debug(str(src.shape))
        #src = self.src_encoder(src) * math.sqrt(self.ninp)
        #src = self.pos_encoder(src)

        #tgt = self.tgt_encoder(tgt) * math.sqrt(self.ninp)
        #tgt = self.pos_encoder(tgt) 


        src_positions = (
            torch.arange(0, src_seq_length)
            .unsqueeze(1)
            .expand(src_seq_length, N)
            .to(self.device)
        )

        tgt_positions = (
            torch.arange(0, tgt_seq_length)
            .unsqueeze(1)
            .expand(tgt_seq_length, N)
            .to(self.device)
        )

        embed_src = self.dropout(
            (self.src_encoder(src) + self.pos_encoder(src_positions))
        )
        embed_tgt = self.dropout(
            (self.tgt_encoder(tgt) + self.pos_encoder(tgt_positions))
        )

        src_mask = self.make_src_mask(src)
        tgt_mask = nn.Transformer.generate_square_subsequent_mask(self, sz=tgt_seq_length).to(self.device)
        
        print_debug(str(str(src.shape) + " " + str(src_mask.transpose(0, 1).shape)))

        memory = self.transformer_encoder(embed_src, src_key_padding_mask=src_mask)
        decoder_output = self.transformer_decoder(embed_tgt, memory, tgt_mask=tgt_mask)
        
        #output = self.dropout(self.fc_out(decoder_output))
        """
        output = self.transformer(
            embed_src,
            embed_tgt,
            #src_key_padding_mask=src_padding_mask,
            tgt_mask=tgt_mask,
        )
        out = self.fc_out(out)
        """
        output = self.fc_out(decoder_output)
        return output
Ejemplo n.º 14
0
	def data_requested(self, service, send_callback, error_callback):
		"""
		data-requested-callback from the dbus service
		"""
		print_debug("Data requested from %s" % service)
		items = self.data_controller.get_items()
		datas, types = [], []
		for item in items:
			datas.append(item.get_object())
			types.append(item.get_type())
		send_callback(datas, types)
Ejemplo n.º 15
0
	def dbus_send(self, files, texts):
		"""
		Sends files, texts and activates
		"""
		# Send data to running Service
		iface = self.dbus_connection.get_interface()
		if files: iface.send_files(files)
		if texts: iface.send_texts(texts)
		iface.activate()
		send_success = True
		print_debug("Sent data to %s" % iface)
Ejemplo n.º 16
0
def tear_down(exception=None):
    """
    当请求结束的时候执行
    """
    try:
        if exception:
            g.db.rollback()
            g.db.close()
            logging.error(utils.print_debug(exception))
    except Exception, e:
        logging.error(utils.print_debug(e))
Ejemplo n.º 17
0
    def crate_process(self):
        procs = self.info(u'Processes')
        if not procs:
            return ''

        for proc in procs:
            for p in proc:
                if p.startswith('/opt/jdk'):
                    print_debug('>>>', p)
                    return p
        return ''
Ejemplo n.º 18
0
def resend_confirm():
    token = current_user.generate_token()
    print_debug(url_for('auth.confirm', token=token, _external=True))
    send_email(current_user.email,
               'Confirm Your Account',
               'confirm',
               '*****@*****.**',
               user=current_user,
               token=token)
    flash('A new confirmation email is sent to your email address. \
            You have 24 hours to verify your account.')
    log_message(f'user_id: {current_user.id} resent their confirmation email')
    return redirect(url_for('main.index'))
Ejemplo n.º 19
0
    def push_heartrate_request(self, start: bool) -> None:
        # The topic name can be optionally prefixed with "/topics/".
        topic = f"exercise"

        # See documentation on defining a message payload.
        message = messaging.Message(
            data={'started': str(start)},
            topic=topic,
        )

        print_debug(message)
        # Send a message to the devices subscribed to the provided topic.
        response = messaging.send(message)
        print_debug(response)
Ejemplo n.º 20
0
    def __find_and_replace_hotbins(self, ar, reference, offbins):
        nbins = ar.get_nbin()
        indices = np.arange(nbins)
        offbin_indices = indices[offbins]
        for isub in np.arange(reference.get_nsubint()):
            for ichan in np.arange(reference.get_nchan()):
                # Always use first polarization channel
                # (i.e. use total intensity - data are p-scrunched)
                prof = reference.get_Profile(int(isub), 0, int(ichan))
                data = prof.get_amps()
                offdata = data[offbins]
                med = np.median(offdata)
                mad = np.median(np.abs(offdata - med))
                std = mad * 1.4826  # This is the approximate relation between the
                # standard deviation and the median absolute
                # deviation (assuming normally distributed data).
                ioffbad = np.abs(offdata - med) > std * self.configs.threshold
                ibad = offbin_indices[ioffbad]
                igood = offbin_indices[~ioffbad]
                nbad = np.sum(ioffbad)
                utils.print_debug('isub: %d, ichan: %d, ipol: %d\n' \
                            '    med: %g, mad: %g\n' \
                            '    %d hotbins found (ibin: %s)' % \
                            (isub, ichan, 0, med, mad, nbad, ibad), 'clean')
                # Replace data in cleaned archive with noise
                if self.configs.fscrunchfirst:
                    chans_to_clean = np.arange(ar.get_nchan())
                else:
                    chans_to_clean = [int(ichan)]
                if self.configs.tscrunchfirst:
                    subints_to_clean = np.arange(ar.get_nsubint())
                else:
                    subints_to_clean = [int(isub)]
                # We always p-scrunch
                pols_to_clean = np.arange(ar.get_npol())

                for jsub in subints_to_clean:
                    for jchan in chans_to_clean:
                        for jpol in pols_to_clean:
                            cleanedprof = ar.get_Profile(
                                int(jsub), int(jpol), int(jchan))
                            cleaneddata = cleanedprof.get_amps()
                            gooddata = cleaneddata[igood]
                            avg = gooddata.mean()
                            std = gooddata.std()
                            if std > 0:
                                noise = np.random.normal(
                                    avg, std, size=nbad).astype('float32')
                                cleaneddata[ibad] = noise
Ejemplo n.º 21
0
	def start_dbus_service(self):
		"""
		Create a dbus Service object

		Set up signals for the service
		return the created service or None
		"""
		import dbuscontrol
		try:
			dserver = dbuscontrol.make_service(self.identifier)
		except Exception, info:
			from utils import print_debug, print_error
			print_debug(info)
			print_error("Failed to use dbus, might not be available")
			dbus_service = None
Ejemplo n.º 22
0
def _clear_dbus_environment():
	"""
	This is an evil run-on-import function to reset
	dbus' environment

	Here we try unsetting DBUS_SESSION_BUS_ADDRESS to
	make dbus recover it from the current X session.
	(debian bug #475448)
	"""
	from os import unsetenv, getenv
	from utils import print_debug
	bus_address_env_name = "DBUS_SESSION_BUS_ADDRESS"

	print_debug("Unsetting %s, to defend against stale environment" %
			bus_address_env_name)
	unsetenv(bus_address_env_name)
Ejemplo n.º 23
0
	def cb_stick_pref_changed(client, connection, entry, user_info):
		"""
		Callback from stick preference change
		
		@param client: gconf_client
		@type client: an object.
		
		@param connection:
		@type connection: an object.
		
		@param entry: The gconf entry
		@type entry: a string object.
		"""
		from utils import print_debug
		print_debug("In window sticky callback")
		self.window.set_sticky(client.get_bool(entry))
Ejemplo n.º 24
0
def reset_email():
    if request.method == "POST":
        form = EmailForm(request.form)
        if form.validate():
            ul = serv.login(g.user['email'], form.password.data)
            if ul:
                #TODO:发送确认邮件
                try:
                    uri = serv.send_lock_request("user.confirm_email", ul.id)
                    up = g.db.query(UserProfile).filter(
                        UserProfile.user_id == ul.id).one()
                    up.email = form.email.data
                    g.db.flush()
                    g.db.commit()
                    success = u"确认邮箱的邮件已经发出,请登录邮箱点击确认链接,然后才能使用新邮箱登陆"
                    msg = Message(u"登陆邮箱变更确认邮件",
                                  sender="*****@*****.**",
                                  recipients=["*****@*****.**"])
                    msg.html = "点击下面链接确认登陆邮件变更,点击后用新邮箱登陆爱普云平台<br/><a href=\"http://%s%s\">%s</a>" % (
                        settings.SERVER, uri, uri)
                    g.mail.send(msg)
                except Exception, e:
                    g.db.rollback()
                    log.error(print_debug(e))
                    errors = [u"未知异常"]
            else:
                errors = [u"登陆密码输入不正确"]
        else:
            errors = [v[0] for k, v in form.errors.iteritems()]
Ejemplo n.º 25
0
def reset_email():
    if request.method == "POST":
        form = EmailForm(request.form)
        if form.validate():
            ul = serv.login(g.user['email'],form.password.data)
            if ul:
                #TODO:发送确认邮件
                try:
                    uri = serv.send_lock_request("user.confirm_email", ul.id)
                    up = g.db.query(UserProfile).filter(UserProfile.user_id==ul.id).one()
                    up.email = form.email.data
                    g.db.flush()
                    g.db.commit()
                    success = u"确认邮箱的邮件已经发出,请登录邮箱点击确认链接,然后才能使用新邮箱登陆"
                    msg = Message(u"登陆邮箱变更确认邮件", sender="*****@*****.**", recipients=["*****@*****.**"])
                    msg.html = "点击下面链接确认登陆邮件变更,点击后用新邮箱登陆爱普云平台<br/><a href=\"http://%s%s\">%s</a>"%(settings.SERVER, uri, uri)
                    g.mail.send(msg)
                except Exception, e:
                    g.db.rollback()
                    log.error(print_debug(e))
                    errors = [u"未知异常"]
            else:
                errors = [u"登陆密码输入不正确"]
        else:
            errors = [v[0] for k, v in form.errors.iteritems()]
Ejemplo n.º 26
0
def main():
    if len(sys.argv)>1:
        mod_name = sys.argv[1]
        if mod_name.endswith(".py"):
            mod_name = mod_name.split(".")[0]

        mod = __import__(mod_name)
        setattr(mod,"db" ,Session())
        try:
            rs = mod.main()
            if rs:
                print "work done with error %s"%rs
            else:
                print "work done"
        except Exception, e:
            print "woops!!\n--------------------------------------"
            print print_debug(e)
Ejemplo n.º 27
0
 def server_ip(self):
     try:
         for addr_group in self.server_data["server"]["addresses"]:
             for addr in addr_group:
                 return addr["addr"]
         return ""
     except Exception,e:
         log.error(print_debug(e))
Ejemplo n.º 28
0
    def post(self, workspace):
        ws_name = utils.get_workspace(workspace=workspace)
        options_path = current_path + \
            '/storages/{0}/options.json'.format(ws_name)
        self.options = utils.reading_json(options_path)

        module = request.args.get('module')

        ws_name = os.path.basename(os.path.normpath(workspace))
        ws_name_encode = utils.url_encode(ws_name)

        utils.print_debug(ws_name)

        if ws_name in os.listdir(self.options['WORKSPACES']):
            ws_json = self.options['WORKSPACES'] + "/{0}/log.json".format(
                ws_name)
            raw_logs = utils.reading_json(ws_json)

        elif ws_name_encode in os.listdir(self.options['WORKSPACES']):
            ws_json = self.options['WORKSPACES'] + "/{0}/log.json".format(
                utils.url_encode(ws_name))
            # utils.print_debug(ws_json_encode)
            raw_logs = utils.reading_json(ws_json)

        if raw_logs:
            all_commands = []

            for k in raw_logs.keys():
                for item in raw_logs[k]:
                    cmd_item = item
                    cmd_item["module"] = k
                    cmd_item['std_path'] = utils.replace_argument(
                        self.options, item.get('std_path')).replace(
                            self.options['WORKSPACES'], '')
                    cmd_item['output_path'] = utils.replace_argument(
                        self.options, item.get('output_path')).replace(
                            self.options['WORKSPACES'], '')
                    cmd_item["module"] = k
                    all_commands.append(cmd_item)

            return {"commands": all_commands}
        else:
            return {
                "error":
                "Not found logs file for {0} workspace".format(ws_name)
            }
Ejemplo n.º 29
0
 def server_ip(self):
     try:
         for addr_group in self.server_data["server"]["addresses"]:
             for addr in addr_group:
                 return addr["addr"]
         return ""
     except Exception, e:
         log.error(print_debug(e))
Ejemplo n.º 30
0
def remove_from_card():
    try:
        card_id = request.args["id"].strip()
        serv.remove_from_card(card_id)
        return json_response(True, "")
    except Exception, e:
        log.error(print_debug(e))
        return json_response(False, u"未知异常")
Ejemplo n.º 31
0
def remove_from_card():
    try:
        card_id = request.args["id"].strip()
        serv.remove_from_card(card_id)
        return json_response(True,"")
    except Exception, e:
        log.error(print_debug(e))
        return json_response(False,u"未知异常")
Ejemplo n.º 32
0
def initialise_routine():
    print_debug('Initialise routine')
    global gear
    global routine

    if routine: 
        print_debug("stopping existing")
        routine.stop()

    routine = BikeRoutine(gear, lambda: BikeSensor(**vars(properties.revolution_sensor)))

    routine.on_update = server.emit_exercise_data
    routine.on_idle_cb = server.emit_idle_state
    routine.on_duration_update = server.emit_duration
    
    server.on_reset_exercise = lambda _: initialise_routine()
    server.on_paused = lambda _: routine.force_pause()
    server.on_resumed = lambda _: routine.resume()
    
    def increase_gear():
        global gear
        gear += 1
        server.emit_gear(gear)
        routine.gear = gear
    
    def decrease_gear():
        global gear
        gear -= 1
        server.emit_gear(gear)
        routine.gear = gear

    server.on_gear_increased = lambda _: increase_gear()
    server.on_gear_decreased = lambda _: decrease_gear()
    server.on_heart_rate_received = lambda heart_rate: routine.publish_heartrate(heart_rate)
    
    def toggle_pause():
        if routine.paused:
            routine.resume()
        else:
            routine.force_pause()
        
    server.on_toggle_pause = lambda _: toggle_pause()

    server.emit_gear(gear)

    threading.Thread(target=routine.start, daemon=True).start()
Ejemplo n.º 33
0
def create_one_order():
    try:
        user = get_user_login(g.current_login_id)
        order = serv.create_oneitem(user, request.form["key"], int(request.form["pay_type"]),int(request.form["pay_count"]),int(request.form["count"]))
        return redirect(url_for("product.order_done",order_id=order.id))
    except Exception, e:
        g.db.rollback()
        log.error(print_debug(e))
        return woops(u"创建订单失败")
Ejemplo n.º 34
0
def prune_band(infn, response=None):
    """Prune the edges of the band. This is useful for
        removing channels where there is no response.
        The file is modified in-place. However, zero-weighting 
        is used for pruning, so the process is reversible.

        Inputs:
            infn: name of file to trim.
            response: A tuple specifying the range of frequencies 
                outside of which should be de-weighted.

        Outputs:
            None
    """
    if response is None:
        response = config.cfg.rcvr_response_lims

    if response is None:
        utils.print_info(
            "No freq range specified for band pruning. Skipping...", 2)
    else:
        # Use absolute value in case band is flipped (BW<0)
        lofreq = infn['freq'] - np.abs(0.5 * infn['bw'])
        hifreq = infn['freq'] + np.abs(0.5 * infn['bw'])
        utils.print_info("Pruning frequency band to (%g-%g MHz)" % response, 2)
        utils.print_debug("Archive's freq band (%g-%g MHz)" % \
                            (lofreq, hifreq), 'clean')
        pazcmd = 'paz -m %s ' % infn.fn
        runpaz = False  # Only run paz if either of the following clauses are True
        if response[0] > lofreq:
            # Part of archive's low freqs are outside rcvr's response
            pazcmd += '-F "%f %f" ' % (lofreq, response[0])
            runpaz = True
        if response[1] < hifreq:
            # Part of archive's high freqs are outside rcvr's response
            pazcmd += '-F "%f %f" ' % (response[1], hifreq)
            runpaz = True
        if runpaz:
            utils.execute(pazcmd)
        else:
            warnings.warn("Not pruning band edges! All data are " \
                            "within the receiver's response.", \
                            errors.CoastGuardWarning)
Ejemplo n.º 35
0
def change_item_count():
    try:
        card_id = request.form.get("id")
        count = int(request.form.get("c"))
        pay_type = int(request.form.get("pt"))
        pay_count = int(request.form.get("pc"))
        fee,favor_fee = serv.set_item_count(card_id, count, pay_type, pay_count)
        return json_response(True,{'fee':fee,'favor_fee':favor_fee})
    except Exception, e:
        log.error(print_debug(e))
        return json_response(False,u"未知异常")
Ejemplo n.º 36
0
def operate_order(order_id):
    action = int(request.args.get("status"))
    order = g.db.query(Order).filter(Order.serial_number==order_id).one()
    if action==2:
        try:
            serv.finish_order(order)
            return "ok"
        except Exception, e:
            g.db.rollback()
            log.error(print_debug(e))
            return woops(u"完成订单失败")
Ejemplo n.º 37
0
def operate_order(order_id):
    action = int(request.args.get("status"))
    order = g.db.query(Order).filter(Order.serial_number == order_id).one()
    if action == 2:
        try:
            serv.finish_order(order)
            return "ok"
        except Exception, e:
            g.db.rollback()
            log.error(print_debug(e))
            return woops(u"完成订单失败")
Ejemplo n.º 38
0
def add_to_card():
    try:
        product_key = request.form["p"]
        count = int(request.form["c"])
        pay_type = int(request.form['t'])
        pay_count = int(request.form["tl"])
        serv.add_to_card(product_key, count, pay_type, pay_count)
        return json_response(True, "")
    except Exception, e:
        log.error(print_debug(e))
        return json_response(False, u"未知异常%s" % request.form["c"])
Ejemplo n.º 39
0
def add_to_card():
    try:
        product_key = request.form["p"]
        count = int(request.form["c"])
        pay_type = int(request.form['t'])
        pay_count = int(request.form["tl"])
        serv.add_to_card(product_key, count,pay_type,pay_count)
        return json_response(True,"")
    except Exception, e:
        log.error(print_debug(e))
        return json_response(False,u"未知异常%s"%request.form["c"])
Ejemplo n.º 40
0
def create_one_order():
    try:
        user = get_user_login(g.current_login_id)
        order = serv.create_oneitem(user, request.form["key"],
                                    int(request.form["pay_type"]),
                                    int(request.form["pay_count"]),
                                    int(request.form["count"]))
        return redirect(url_for("product.order_done", order_id=order.id))
    except Exception, e:
        g.db.rollback()
        log.error(print_debug(e))
        return woops(u"创建订单失败")
Ejemplo n.º 41
0
def create_order():
    try:
        user = get_user_login(g.current_login_id)
        cards = serv.Cards()
        cards.from_session()
        order_id = cards.create_order(user)
        cards.clear()
        return redirect(url_for("product.order_done",order_id=order_id))
    except Exception, e:
        g.db.rollback()
        log.error(print_debug(e))
        return woops(u"创建订单失败")
Ejemplo n.º 42
0
def send_reset():
    form = SendResetForm()
    if form.validate_on_submit():
        log_message(
            f'{form.email.data} attempted to send password reset email')
        user = User.get(form.email.data)
        if user:
            token = user.generate_token()
            print_debug(url_for('auth.reset', token=token, _external=True))
            send_email(user.email,
                       'Reset your password',
                       'reset-pw',
                       '*****@*****.**',
                       token=token)
            log_message(f'user_id: {user.id} sent password reset')
        else:
            log_message(f'{form.email.data} is an invalid email')
        flash('An email will be sent with a link to reset your password',
              'success')
        return redirect(url_for('dash.index'))
    return render_template('auth/send-reset.html.j2', form=form)
Ejemplo n.º 43
0
def change_item_count():
    try:
        card_id = request.form.get("id")
        count = int(request.form.get("c"))
        pay_type = int(request.form.get("pt"))
        pay_count = int(request.form.get("pc"))
        fee, favor_fee = serv.set_item_count(card_id, count, pay_type,
                                             pay_count)
        return json_response(True, {'fee': fee, 'favor_fee': favor_fee})
    except Exception, e:
        log.error(print_debug(e))
        return json_response(False, u"未知异常")
Ejemplo n.º 44
0
def create_order():
    try:
        user = get_user_login(g.current_login_id)
        cards = serv.Cards()
        cards.from_session()
        order_id = cards.create_order(user)
        cards.clear()
        return redirect(url_for("product.order_done", order_id=order_id))
    except Exception, e:
        g.db.rollback()
        log.error(print_debug(e))
        return woops(u"创建订单失败")
Ejemplo n.º 45
0
def create_server():
    user_product_id = int(request.form.get("up_id"))
    server_name = request.form.get("name")
    image_id = request.form.get("image_id")
    secure = request.form.get("secure")
    try:
        serv.create_server(user_product_id, server_name, image_id, secure)
        return json_response(True,{})
    except Exception, ex:
        log.error(print_debug(ex))
        g.db.rollback()
        return json_response(False,u"未知异常")
Ejemplo n.º 46
0
    def start(self):
        if self.recording:
            return
        print_debug("Start recording bike sensor")

        self.recording = True

        if not self.debug_sensor:
            if not self.previous_handled_time:
                self.previous_handled_time = current_millis()

            while self.recording:
                if not self._handle_new_state(GPIO.input(self.pin)):
                    if current_millis(
                    ) - self.previous_handled_time > self.idle_time:
                        if self.on_idle and not self.is_idle:
                            print_debug('idle')
                            self.is_idle = True
                            self.initialise()
                            self.on_idle(True)
                else:
                    self.previous_handled_time = current_millis()
        else:
            i = 0
            while self.recording:
                if self.is_idle:
                    self.is_idle = False
                    self.on_idle(False)
                if i % 2 != 0 and i != 0:
                    self._handle_new_state(1)
                else:
                    self._handle_new_state(0)
                i += 1
                sleep(0.5)
        print_debug("End recording bike sensor")
Ejemplo n.º 47
0
def perform_check():
    if dry_run:
        print_info('Running check.py in dry run (not sending any SMS)')

    service = AvailabilityService()
    manager = StateManager()

    service.query_api()

    service.parse_data()
    print_debug(service.servers)

    manager.load_state()
    print_debug(manager.state)

    offers = service.fetch_available(manager.state)
    print_debug(offers)

    for offer in offers:
        message = '{} is now available in {} at {}.'.format(offer['server'], offer['stock'], offer['dc'])
        print_info(message)
        if not dry_run:
            notify(message)

    if sold_out:
        offers = service.fetch_sold_out(manager.state)
        print_debug(offers)

        for offer in offers:
            message = '{} is no longer available at {}.'.format(offer['server'], offer['dc'])
            print_info(message)
            if not dry_run:
                notify(message)

    manager.update_state(service.servers)
    print_debug(manager.state)

    manager.save_state()
Ejemplo n.º 48
0
    def start(self, cmd=['crate'], ports={}, env=[], volumes={}):
        if self.is_running:
            raise InvalidState('Container is still running.')

        ulimits = [dict(name='memlock', soft=-1, hard=-1)]
        host_conf = self.cli.create_host_config(
            port_bindings=ports,
            binds=volumes,
            ulimits=ulimits,
        )

        self.assertTrue(len(cmd) >= 1)
        self.assertEquals(cmd[0], 'crate')

        cmd[1:1] = [
            '-Cbootstrap.memory_lock=true',
        ]
        env[0:0] = [
            'CRATE_HEAP_SIZE=128m',
        ]

        self.container = self.cli.create_container(
            image=self._layer.tag,
            command=cmd,
            ports=list(ports.keys()),
            host_config=host_conf,
            environment=env,
            volumes=['/data'],
            name=self.name
        )
        self.cli.start(self.container_id)
        process = self.crate_process()
        print_debug('Waiting for Docker container ...')
        while not process:
            time.sleep(0.1)
            process = self.crate_process()
        self.is_running = True
Ejemplo n.º 49
0
	def create_window(self, name=None):
		"""
		create a new window
		"""
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		window_display = self.window.get_display()
		print_debug("Window display is %s" % window_display)
		if not window_display:
			from utils import quit_dragbox
			print_error("Could not get X Display")
			quit_dragbox()

		if name:
			self.window.set_title(name)

		self.window.connect("destroy", self.quit_all)
		self.window.connect("button-press-event", self.cb_window_click)

		self.vbox = gtk.VBox(False, 0)

		# Add a scrollbox around the vbox
		# scrolls the list when it's too long
		scrollbox = gtk.ScrolledWindow()
		scrollbox.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
		scrollbox.set_border_width(0)
		self.window.add(scrollbox)
		scrollbox.add_with_viewport(self.vbox)
		
		# Add placeholder for newbies
		self.make_placeholder()
		pixbuf = self.window.render_icon(gtk.STOCK_DND_MULTIPLE, gtk.ICON_SIZE_DIALOG)
		self.window.set_icon(pixbuf)
		
		# Setup window as a drag TARGET
		from shelfitem import file_targets, text_targets
		self.window.drag_dest_set(gtk.DEST_DEFAULT_ALL, file_targets+text_targets, gtk.gdk.ACTION_DEFAULT | gtk.gdk.ACTION_COPY )
		self.window.connect("drag-data-received", self.cb_drag_data_received)
Ejemplo n.º 50
0
def create_server():
    user_product_id = int(request.form.get("up_id"))
    server_name = request.form.get("name")
    image_id = request.form.get("image_id")
    secure = request.form.get("secure")
    key_name = request.form.get("key_name","")
    try:
        if not key_name:
            key_name = serv.get_only_key(g.current_login_id)
        server_id = serv.create_server(user_product_id, server_name, image_id, secure, key_name)
        log.error(server_id)
        return json_response(True,server_id)
    except Exception, ex:
        log.error(print_debug(ex))
        g.db.rollback()
        return json_response(False,u"未知异常")
Ejemplo n.º 51
0
def create_server():
    user_product_id = int(request.form.get("up_id"))
    server_name = request.form.get("name")
    image_id = request.form.get("image_id")
    secure = request.form.get("secure")
    key_name = request.form.get("key_name", "")
    try:
        if not key_name:
            key_name = serv.get_only_key(g.current_login_id)
        server_id = serv.create_server(user_product_id, server_name, image_id,
                                       secure, key_name)
        log.error(server_id)
        return json_response(True, server_id)
    except Exception, ex:
        log.error(print_debug(ex))
        g.db.rollback()
        return json_response(False, u"未知异常")
Ejemplo n.º 52
0
def down_key():
    from json import loads
    from tempfile import NamedTemporaryFile
    key_id = request.args.get("key_id")
    try:
        userkey = g.db.query(UserKey).get(key_id)
        keypair = loads(userkey.key_content)
        private_key = keypair["keypair"]["private_key"]
        f = NamedTemporaryFile()
        f.write(private_key)
        userkey.has_down =True
        g.db.flush()
        g.db.commit()
        return send_file(f.name,attachment_filename="private_key.pem",mimetype="application/octet-stream",as_attachment=True)
    except Exception, e:
        log.error(print_debug(e))
        g.db.rollback()
        return ""
Ejemplo n.º 53
0
	def __init__(self):
		"""
		Set up the preferences window
		
		Find the glade file as it was installed, or search for custom
		DESTDIR or check if not installed at all.
		"""
		glade_filename = "preferences.glade"
		glade_file = path.normpath(path.join(glade_directory, glade_filename))

		if not path.exists(glade_file):
			# Try to find if installed with DESTDIR
			from utils import guess_destdir
			while glade_file[0] == "/":
				glade_file = glade_file[1:]
			destdir = guess_destdir()
			if destdir:
				glade_file = path.join(destdir, glade_file)
				print_debug(glade_file)
		if not path.exists(glade_file):
			# try to find if not installed
			from sys import argv
			prog_location = path.abspath(argv[0])
			(head, tail) = path.split(prog_location)
			glade_file = path.join(head, "data", glade_filename)
			print_debug(glade_file)
			
		print_debug("Loading %s" % glade_file)
		try:
			self.ui = XML(glade_file)
		except:
			from utils import print_error
			print_error("Failed to load UI file for preferences window!")
			print_error("File: %s" % glade_file)
			self.win = None
			return
			
		self.win = self.ui.get_widget("prefswindow")
		self.check_stick = self.ui.get_widget("check_stick")
		self.check_open = self.ui.get_widget("check_open")
		self.check_remove = self.ui.get_widget("check_remove")
		
		# signals from .glade file
		signals = {
			"on_check_stick_toggled" : self.cb_stick_toggled,
			"on_check_open_toggled" : self.cb_open_toggled,
			"on_close_clicked" : self.cb_close_clicked,
			"on_check_remove_toggled" : self.cb_remove_toggled,
			"on_prefswindow_delete_event" : self.cb_delete_event,
		}
		# connect signals
		self.ui.signal_autoconnect(signals)
		
		# Set check boxes to prefs values
		stick = preferences.get_bool("stick", if_none=True)
		self.check_stick.set_active(stick)
		
		open = preferences.get_bool("open", if_none=False)
		self.check_open.set_active(open)
		
		remove = preferences.get_bool("remove", if_none=False)
		self.check_remove.set_active(remove)
		
		# set window icon
		from gtk import STOCK_DND_MULTIPLE, ICON_SIZE_DIALOG 
		pixbuf = self.win.render_icon(STOCK_DND_MULTIPLE, ICON_SIZE_DIALOG)
		self.win.set_icon(pixbuf)
		
		# hide window -- only show it if asked for
		self.win.hide()
Ejemplo n.º 54
0
def after_request(response):
    try:
        g.db.flush()
        g.db.commit()
    except Exception, e:
        g.db.rollback(utils.print_debug(e))
Ejemplo n.º 55
0
def init():
    try:
        from models import Base
        Base.metadata.create_all(bind=DB)
    except Exception, e:
        print print_debug(e)