Exemplo n.º 1
0
def add_new_record():
   """ Add new record to students.db"""
   rec = {
         "id":223445,
         "firstName": "Mike",
         "lastName": "Wong",
         "class":"3 A",
         "nationality": "Singapore"
         }

   id = rec.get('id')
   firstname = rec.get('firstName')
   lastname = rec.get('lastName')
   _class = rec.get('class')
   nationality = rec.get('nationality')

   sql = "INSERT INTO students VALUES(%s, '%s', '%s', '%s', '%s')"%(id,firstname,lastname,_class,nationality)

   try:
      conn = sqlite3.connect('students.db')
      cur = conn.cursor()

      cur.execute(sql)
      conn.commit()
   except:
      print traceback.format_exec()
   finally:
      cur.close()
      conn.close()
      return render_template("home.html")
Exemplo n.º 2
0
def get_concept_classified():
    """
        获取概念分类数据
    Return
    --------
    DataFrame
        code :股票代码
        name :股票名称
        c_name :概念名称
    """
    try:
        ct._write_head()
        df = _get_type_data(
            ct.SINA_CONCEPTS_INDEX_URL %
            (ct.P_TYPE['http'], ct.DOMAINS['sf'], ct.PAGES['cpt']))
        data = []
        name_list = df.values
        for row in df.values:
            rowDf = _get_detail(row[0], pause=0.1)
            if rowDf is not None:
                rowDf['c_name'] = row[1]
                data.append(rowDf)
        if len(data) > 0:
            data = pd.concat(data, ignore_index=True)
    except:
        print(traceback.format_exec())
    return data, name_list
Exemplo n.º 3
0
def role_select(auth_info, **kwargs):
    if auth_info['code'] == 1:
        return json.dumps(auth_info)
    username = auth_info['username']
    if '1' not in auth_info['r_id']
        return json.dumps({'code':1, 'errmsg':'you are not admin, no power'})
    try:
        output = ['id', 'username', 'name_cn', 'p_id', 'info']
        data = request.get_json()['params']
        fields = data.get('output', output)
        # 查询权限表,生成id2name的字典
        # 取得power的id,和name
        result = app.config['db'].get_results('power', ['id', 'name'])
        power_name = dict([(str(x['id']) , x['name']) for x in result ])
        
        # 查询role表,取得role的信息
        res = app.config['db'].get_results('role', fields)

        #将角色对应的p_id都转换为name,最终返回的结果p_id的值都是name
        result = []
        for x in res:
            p_name = [power_name[p_id] for p_id in x['p_id'].split(',') if p_id in power_name]
            x['p_id'] = ','.join(p_name)   # 将原有的x['p_id']中的内容转换成为name
            result.append(x)

        utils.write_log('api').info('%s select role list success' % username)
        return json.dumps({'code':0, 'result':result , 'count':len(result)})
    except:
        utils.write_log('api').error('get  role list  error: %s' % (traceback.format_exec()))
        return json.dumps({'code':1, 'errmsg':'get role list failed'})
Exemplo n.º 4
0
 def get_distribution_config(self, distribution_id):
     try:
         func = partial(self.client.get_distribution_config,Id=distribution_id)
         return self.paginated_response(func)
     except Exception as e:
         self.module.fail_json(msg="Error describing distribution configuration - " + str(e),
                               exception=traceback.format_exec())
Exemplo n.º 5
0
def new():
    try:
        if request.GET.get('save', '').strip():
            task = request.GET.get('task', '').strip()
            description = request.GET.get('description', '').strip()
            status = request.GET.get('status', '').strip()
            if status == "Yes":
                status = "Yes"
            else:
                status = "No"

            conn = sqlite3.connect('checklist.db')
            cl = conn.cursor()
            cl.execute("INSERT INTO checklist (task,description,status)\
                        VALUES (?,?,?)", (task, description, status))
            new_id = cl.lastrowid
            conn.commit()
            cl.close()
            return '<p>The new task (ID = %s) was inserted.</p>' % new_id
        else:
            return template('create_task.tpl')
    except:
        error = traceback.format_exec()
        print('An error has occurred:\n', error)
        open('error.log', 'a').write(error)
        raise SystemExit
    def get_loader_filename_from_comp (self, loaders, comp_path, the_type):
        loader_list = []
        try:
            for a in loaders:
                loader_list.append ({'node': a, 'type': the_type})

            total_to_find = len (loaders)
            total_found = 0

            check_comp = open (comp_path, "r")
            looking = False
            selected = 0
            for a in check_comp:
                if total_found >= total_to_find:
                    break
                counter = 0
                if not looking:
                    for b in loaders:
                        if b in a:
                            looking = True
                            selected = counter
                            break
                        counter += 1
                else:
                    if 'Filename = ' in a:
                        total_found += 1
                        added_line = a.split ('"')[1]
                        loader_list[selected]['path'] = added_line
                        looking = False
        except:
            import traceback
            error = traceback.format_exec()
            raise TankError("Failed trying to read loader from comp source file: \n%s" % error)

        return loader_list
Exemplo n.º 7
0
 def get_distribution_config(self, distribution_id):
     try:
         func = partial(self.client.get_distribution_config,
                        Id=distribution_id)
         return self.paginated_response(func)
     except botocore.exceptions.ClientError as e:
         self.module.fail_json(
             msg="Error describing distribution configuration - " + str(e),
             exception=traceback.format_exec(e),
             **camel_dict_to_snake_dict(e.response))
Exemplo n.º 8
0
def save_prediction_examples(num_examples=1,
                             validation_image_generator=None,
                             model=None,
                             folder_path='results/',
                             model_name='name'):
    """Helper method to save examples of images and prediction probabilities"""
    X_val_sample, _ = next(validation_image_generator)
    y_pred = model.predict(X_val_sample)
    for idx, x, y in zip(range(num_examples), X_val_sample[:num_examples],
                         y_pred.flatten()[:num_examples]):
        s = pd.Series(y)
        axes = s.plot(kind='bar')
        axes.set_xlabel('Class')
        axes.set_ylabel('Probability')
        axes.set_ylim([0, 1])

        try:
            np.save(
                os.path.join(folder_path, model_name + "_result_guess_" +
                             str(idx) + ".npy"), y)
        except Exception as e:
            logging.error(traceback.format_exec())
        try:
            np.save(
                os.path.join(
                    folder_path,
                    model_name + "_prediction_sample_" + str(idx) + ".npy"), x)
        except Exception as e:
            logging.error(traceback.format_exec())
        try:
            plt.savefig(
                os.path.join(folder_path, model_name + "_result_graph_" +
                             str(idx) + ".png"))
        except Exception as e:
            logging.error(traceback.format_exec())
        try:
            plt.imsave(
                os.path.join(
                    folder_path,
                    model_name + "_prediction_sample_" + str(idx) + ".png"), x)
        except Exception as e:
            logging.error(traceback.format_exec())
Exemplo n.º 9
0
def buildInstrument(cfg):
    """Given a config object, construct the instrument.
    This will give the user a graphic way to handle initialization
    errors, as well.

    Arguments:
        cfg - ConfigObj
    Returns:
        instrument object
    """

    #Build instrument
    ################################################################
    try:
        instrument = Instrument(cfg)
    except Exception as e:
        wx.MessageBox('An unknown error was raised during the'
                      ' initialization of the instrument. See log'
                      ' for details. NESSI will shut down.', 
                      'UNKNOWN INITIALIZATION ERROR!', 
                      wx.OK | wx.ICON_ERROR)
        logging.critical(traceback.format_exc())
        shutdown()

    #Check for components that did not initialize
    ################################################################
    failedComponents = [compName for compName, comp in 
                        instrument.components.items() if comp == None]
    
    if failedComponents:
        dlg = wx.MessageDialog(None, 'The following instrument components'
                               ' did not initialize: ' + str(failedComponents) + '\n'
                               'Would you like to continue anyway?',
                               'Instrument Partially Initialized!',
                               wx.YES_NO | wx.ICON_QUESTION)
        moveon = dlg.ShowModal() == wx.ID_YES
        dlg.Destroy()
        
        if not moveon:
            shutdown()

    #Connect to telescope
    ################################################################
    try:
        #instrument.connectTelescope()
        pass
    except:
        wx.MessageBox('Unable to connect to telescope! NESSI must shut'
                      ' down!', 'TELESCOPE CONNECTION ERROR!',
                      wx.OK | wx.ICON_ERROR)
        logging.critical(traceback.format_exec())
        shutdown()

    return instrument
Exemplo n.º 10
0
 def _update(self, sql):
     try:
         db = Database()
         db.executeWithoutQuery(sql)
         return None
     except Exception, e:
         # TODO:if have any duplicated account
         log = Log()
         errmsg = traceback.format_exec()
         log.error(errmsg)
         return str(e)
Exemplo n.º 11
0
 def load(self):
     with open(self.config_file, "a+") as f:
         content = f.read()
         if content is None or content is "" or len(content) is 0:
             pass
         else:
             try:
                 json_dict = json.loads(content)[0]['datapoints']
                 self.unmarshal(json_dict)
             except Exception as e:
                 Logger.error("Failed to load .derrick_application_conf,because of %s" % e)
                 Logger.debug("Stack Information:%s" % traceback.format_exec())
Exemplo n.º 12
0
def __dump(X, path):
    if os.path.exists(path):
        msg.timemsg('Will overite file {} with new pickle dump'.format(path))
    else:
        try:
            msg.timemsg("Dump to {}".format(path))
            with open(path, "wb") as f:
                pickle.dump(X, f, protocol=pickle.HIGHEST_PROTOCOL)
            msg.timemsg("Dump done")
        except:
            msg.timemsg('Exception during dump of {}'.format(path))
            msg.timemsg(traceback.format_exec())
Exemplo n.º 13
0
    def __iter__(self):
        try:
            x = self.delegate()
            self.start(self.status, self._headers)
        except:
            headers = [('Content-type', 'text/plain')]
            self.start('500 Internal Error', headers)
            x = 'Internal Error:\n\n' + traceback.format_exec()

        if isinstance(x, str):
            return iter([x])
        else:
            return iter(x)
Exemplo n.º 14
0
def load_collectors_from_entry_point(path):
    """
    Load collectors that were installed into an entry_point.
    """
    collectors = {}
    for ep in pkg_resources.iter_entry_points(path):
        try:
            mod = ep.load()
        except Exception:
            logger.error('Failed to import entry_point: %s. %s', ep.name,
                         traceback.format_exec())
        else:
            collectors.update(get_collectors_from_module(mod))
    return collectors
Exemplo n.º 15
0
def create(auth_info, **kwargs):
    username = auth_info['username']
    if '1' not in auth_info['r_id']
        return json.dumps({'code':1, 'errmsg':'you are not admin, no power'})
    try:
        data = request.get_json()['params']
        if not utils.check_name(data['name'])
            return json.dumps({'code':1, 'errmsg':'name must be stirng or num'})
        app.config['db'].execute_insert_sql('power', data)
        utils.write_log('api').info('%s create power %s success' % (username, data['name']))
        return json.dumps({'code':0 , 'result': '%s create %s success' % (username, data[name]}))
    except:
        utils.write_log('api').error('create power error' % traceback.format_exec())
        return json.dumps({'code':1 , 'errmsg': 'create power failed' })
Exemplo n.º 16
0
def run():
    global stock_list, all_stock_tracker
    activate_stock_list = list(all_stock_tracker.keys())
    # deal history data
    for stock_code in activate_stock_list:
        try:
            for strategy in all_stock_tracker[stock_code]:
                if not strategy.init_flag:
                    del all_stock_tracker[stock_code]
                else:
                    print('*********************** Success init {}  ***********************'.format(stock_code))
        except Exception as e:
            #print('*********************** {}\'s History Data is not prepared. ***********************'.format(stock_code))
            print(traceback.format_exec())
            del all_stock_tracker[stock_code]

    while True:
        if not is_stock_trading_time():
           print("********** not in trading time **********")
           time.sleep(60)
           continue
        #deal current market data
        current_market_data = __get_current_market_data(activate_stock_list)
        print(''.join(('-' * 100)))
        for stock_code in activate_stock_list:
            all_strategy = all_stock_tracker[stock_code]
            if len(current_market_data.keys()) < 1:
                continue
            buy_signal = False
            sell_signal = False
            for single_strategy in all_strategy:
                single_strategy._main_calc_func(current_market_data[stock_code]['current_price'], current_market_data[stock_code]['date'] + ' ' + current_market_data[stock_code]['time'])
                buy_signal = buy_signal and single_strategy._realtime_has_buy_signal(current_market_data[stock_code]['current_price'])
                sell_signal = sell_signal and single_strategy._realtime_has_sell_signal(current_market_data[stock_code]['current_price'])
            #print('{} {}'.format(stock_code, all_stock_tracker[stock_code][1].price_queues))
            print('^^^^^^^^^^^^^^^^^^^^^ {} ^^^^^^^^^^^^^^^^^^^^^^^^^^'.format(current_market_data[stock_code]['date'] + ' ' + current_market_data[stock_code]['time']))
            print('********** {} ma : {} {} current_close : {} **********'.format(stock_code, all_stock_tracker[stock_code][1].ma_list[0][-1], all_stock_tracker[stock_code][1].ma_list[0][-2], current_market_data[stock_code]['current_price']))
            print('********** {} macd : {} {} current_close : {} **********'.format(stock_code, all_stock_tracker[stock_code][0].all_macd_value[-1], all_stock_tracker[stock_code][0].all_macd_value[-2], current_market_data[stock_code]['current_price']))
            print('****************** {} ma_delta: {}, macd_delta: {} **********************'.format(
                stock_code, all_stock_tracker[stock_code][1].ma_list[0][-1] - all_stock_tracker[stock_code][1].ma_list[0][-2],
                all_stock_tracker[stock_code][0].all_macd_value[-1] - all_stock_tracker[stock_code][0].all_macd_value[-2]))

            if buy_signal:
                print('********** {} {} has buy signal **********'.format(stock_code, current_market_data[stock_code]['chinese_name']))
            if sell_signal:
                print('********** {} {} has sell signal **********'.format(stock_code, current_market_data[stock_code]['chinese_name']))
        print("********** end of analyze single round **********")
        print(''.join(('-' * 101)))
        time.sleep(4)
Exemplo n.º 17
0
def load_collectors_from_entry_point(path):
    """
    Load collectors that were installed into an entry_point.
    """
    collectors = {}
    for ep in pkg_resources.iter_entry_points(path):
        try:
            mod = ep.load()
        except Exception:
            logger.error('Failed to import entry_point: %s. %s',
                         ep.name,
                         traceback.format_exec())
        else:
            collectors.update(get_collectors_from_module(mod))
    return collectors
Exemplo n.º 18
0
def _get_type_data(url):
    try:
        resp = requests.get(url)
        resp.encoding = 'gbk'
        #request = Request(url)
        data_str = resp.text
        #data_str = data_str.decode('GBK')
        data_str = data_str.split('=')[1]
        data_json = json.loads(data_str)
        df = pd.DataFrame(
            [[row.split(',')[0], row.split(',')[1]]
             for row in data_json.values()],
            columns=['tag', 'name'])
        return df
    except Exception as er:
        print(traceback.format_exec())
Exemplo n.º 19
0
Arquivo: mbx.py Projeto: mattmb/spoke
 def __init__(self):
     """Get config, setup logging and cyrus connection."""
     self.config = config.setup()
     self.log = logger.setup(__name__)
     server = self.config.get('IMAP', 'server')
     port = int(self.config.get('IMAP', 'port', 143))
     self.user = self.config.get('IMAP', 'user')
     password = self.config.get('IMAP', 'password')
     self.mailbox_group = self.config.get('IMAP', 'mailbox_group', 'user')
     self.sep = '/'
     try:
         self.imap = imaplib.IMAP4(server, port)
     except imaplib.socket.error:
         trace = traceback.format_exec()
         msg = '%s: %s' % ('IMAP connection error')
         raise error.SpokeIMAPError(msg, trace)
     self.imap.login(self.user, password)
Exemplo n.º 20
0
 def __init__(self):
     """Get config, setup logging and cyrus connection."""
     self.config = config.setup()
     self.log = logging.getLogger(__name__)
     server = self.config.get('IMAP', 'server')
     port = int(self.config.get('IMAP', 'port', 143))
     self.user = self.config.get('IMAP', 'user')
     password = self.config.get('IMAP', 'password')
     self.mailbox_group = self.config.get('IMAP', 'mailbox_group', 'user')
     self.sep = '/'
     try:
         self.imap = imaplib.IMAP4(server, port)
     except imaplib.socket.error:
         trace = traceback.format_exec()
         msg = '%s: %s' % ('IMAP connection error')
         raise error.SpokeIMAPError(msg, trace)
     self.imap.login(self.user, password)
Exemplo n.º 21
0
 def set(self, setting, value):
     setting = str(setting)
     new_value = str(value)
     current_setting = Setting.query.filter(Setting.name==setting).first()
     try:
         if current_setting:
             current_setting.value = new_value
             db.session.commit()
             return True
         else:
             logging.error('Setting %s does not exist' % setting)
             return False
     except:
         logging.error('Cannot edit setting %s' % setting)
         logging.debug(traceback.format_exec())
         db.session.rollback()
         return False
Exemplo n.º 22
0
 def set(self, setting, value):
     setting = str(setting)
     new_value = str(value)
     current_setting = Setting.query.filter(Setting.name==setting).first()
     try:
         if current_setting:
             current_setting.value = new_value
             db.session.commit()
             return True
         else:
             logging.error('Setting %s does not exist' % setting)
             return False
     except:
         logging.error('Cannot edit setting %s' % setting)
         logging.debug(traceback.format_exec())
         db.session.rollback()
         return False
Exemplo n.º 23
0
 def set(cls, setting, value):
     """Set Setting."""
     setting = str(setting)
     new_value = str(value)
     current_setting = Setting.query.filter(Setting.name == setting).first()
     try:
         if current_setting:
             current_setting.value = new_value
             db.session.commit()
             return True
         else:
             LOGGING.error('Setting %s does not exist', setting)
             return False
     except Exception:
         LOGGING.error('Cannot edit setting %s', setting)
         LOGGING.debug(traceback.format_exec())
         db.session.rollback()
         return False
Exemplo n.º 24
0
def upload_to_everstore(fileName):

    try:
        with open(fileName, 'rb') as inputFile:
            serviceRouter = ServiceRouter()
            client = serviceRouter.getClient2(Everstore.Client, 'dfsrouter.common')

            handle = client.write(
                blob=inputFile.read(),
                fbtype=EVERSTORE_HACK_CRASH_LOGS,
                extension='txt',
            )
        return handle

    except Exception:
        logging.error('Exception while uploading to everstore: {}'.format(
            traceback.format_exec()))
        return 'NoHandle'
Exemplo n.º 25
0
    def set(self, setting, value):
        current_setting = Setting.query.filter(Setting.name == setting).first()

        if current_setting is None:
            current_setting = Setting(name=setting, value=None)
            db.session.add(current_setting)

        value = str(value)

        try:
            current_setting.value = value
            db.session.commit()
            return True
        except Exception as e:
            current_app.logger.error(
                'Cannot edit setting {0}. DETAIL: {1}'.format(setting, e))
            current_app.logger.debug(traceback.format_exec())
            db.session.rollback()
            return False
Exemplo n.º 26
0
 def toggle(self, setting):
     setting = str(setting)
     current_setting = Setting.query.filter(Setting.name==setting).first()
     try:
         if current_setting:
             if current_setting.value == "True":
                 current_setting.value = "False"
             else:
                 current_setting.value = "True"
             db.session.commit()
             return True
         else:
             logging.error('Setting %s does not exist' % setting)
             return False
     except:
         logging.error('Cannot toggle setting %s' % setting)
         logging.debug(traceback.format_exec())
         db.session.rollback()
         return False
Exemplo n.º 27
0
 def toggle(self, setting):
     setting = str(setting)
     current_setting = Setting.query.filter(Setting.name==setting).first()
     try:
         if current_setting:
             if current_setting.value == "True":
                 current_setting.value = "False"
             else:
                 current_setting.value = "True"
             db.session.commit()
             return True
         else:
             logging.error('Setting %s does not exist' % setting)
             return False
     except:
         logging.error('Cannot toggle setting %s' % setting)
         logging.debug(traceback.format_exec())
         db.session.rollback()
         return False
Exemplo n.º 28
0
	def __del__(self):
		print('Fim do programa.')
		i = input('Deseja salvar alteracoes: S | N\n')
		save = True if (i=='S' or i=='s') else False
		try:
			# Fecha a visualizacao do Excel
			self.excel.Visible = False
			# Fecha o workbook e salva as alteracoes caso seja requisitado
			self.workbook.Close(SaveChanges=save)
			# Fecha a aplicacao Excel
			self.excel.Quit()
			# Destroi o objeto workbook
			del self.workbook
			# Destroi o objeto aplicacao Excel
			del self.excel
		except:
			print('Ocorreu algum erro ao fechar a aplicacao.')
			print(traceback.format_exec())
			pass
		print("Modelo destruido com sucesso.")
Exemplo n.º 29
0
def role_create(auth_info, **kwargs):
    if auth_info['code'] == 1:
        return json.dumps(auth_info)
    username = auth_info['username']
    if '1' not in auth_info['r_id']
        return json.dumps({'code':1, 'errmsg': 'you are not admin, no power'})
    try:
        data = request.get_json()['params']
        if not data.has_key('p_id'):
            return json.dumps({"code":1, "errmsg":"must have a p_id!"})
        if not app.config['db'].if_id_exist("power",data['p_id'].split(',')):
            return json.dumps({"code":1, "errmsg":"p_id not exist!"})
        if not utils.check_name(data['username']):
            return json.dumps({"code":1, "errmsg":"username must be string or num!"})
        app.config['db'].execute_insert_sql('role', data)
        utils.write_log('api').info('%s create role %s success' % (username, data['name']))
        return json.dumps({'code':0 , 'result': '%s create role %s success' % (username, data[name]}))
    except:
        utils.write_log('api').error('create role error' % traceback.format_exec())
        return json.dumps({'code':1 , 'errmsg': 'create role failed' })
Exemplo n.º 30
0
 def toggle(cls, setting):
     """Toggle Setting."""
     setting = str(setting)
     current_setting = Setting.query.filter(Setting.name == setting).first()
     try:
         if current_setting:
             if current_setting.value == "True":
                 current_setting.value = "False"
             else:
                 current_setting.value = "True"
             db.session.commit()
             return True
         else:
             LOGGING.error('Setting %s does not exist', setting)
             return False
     except Exception:
         LOGGING.error('Cannot toggle setting %s', setting)
         LOGGING.debug(traceback.format_exec())
         db.session.rollback()
         return False
Exemplo n.º 31
0
def getbyid(auth_info, **kwargs):
    if auth_info['code'] == 1:
        return json.dumps(auth_info)
    username = auth_info['username']
    if '1' not in auth_info['r_id']
        return json.dumps({'code':1, 'errmsg':'you are not admin, no power'})
    try:
        output = ['id', 'username', 'name_cn', 'p_id', 'info']
        data = request.get_json()['params']
        fields = data.get('output', output)
        where = data.get('where', None)
        if not where:
            return json.dumps({'code':1, 'errmsg':'must need a condition'})
        result = app.config['db'].get_one_result('role', fields, where)
        if not result:
            return json.dumps({'code':1, 'errmsg':'data not exists'})
        utils.write_log('api').info('%s select role by id success' % username)
        return json.dumps({'code':0, 'result':result })
    except:
        utils.write_log('api').error('select role by id error: %s' % (traceback.format_exec()))
        return json.dumps({'code':1, 'errmsg':'get role by id failed'})
Exemplo n.º 32
0
    def toggle(self, setting):
        current_setting = Setting.query.filter(Setting.name == setting).first()

        if current_setting is None:
            value = self.defaults[setting]
            current_setting = Setting(name=setting, value=str(value))
            db.session.add(current_setting)

        try:
            if current_setting.value == "True":
                current_setting.value = "False"
            else:
                current_setting.value = "True"
            db.session.commit()
            return True
        except Exception as e:
            current_app.logger.error(
                'Cannot toggle setting {0}. DETAIL: {1}'.format(setting, e))
            current_app.logger.debug(traceback.format_exec())
            db.session.rollback()
            return False
Exemplo n.º 33
0
    def analyze(self, dataSource, fileManager, context):
        """
            Extract, Transform and Load all TSK contact, message
            and calllog artifacts from the WhatsApp databases.
        """

        try:
            contact_dbs = AppSQLiteDB.findAppDatabases(
                dataSource, "wa.db", True, self._WHATSAPP_PACKAGE_NAME)
            calllog_and_message_dbs = AppSQLiteDB.findAppDatabases(
                dataSource, "msgstore.db", True, self._WHATSAPP_PACKAGE_NAME)

            #Extract TSK_CONTACT information
            for contact_db in contact_dbs:
                current_case = Case.getCurrentCaseThrows()
                helper = CommunicationArtifactsHelper(
                    current_case.getSleuthkitCase(), self._PARSER_NAME,
                    contact_db.getDBFile(), Account.Type.WHATSAPP)
                self.parse_contacts(contact_db, helper)

            for calllog_and_message_db in calllog_and_message_dbs:
                current_case = Case.getCurrentCaseThrows()
                helper = CommunicationArtifactsHelper(
                    current_case.getSleuthkitCase(), self._PARSER_NAME,
                    calllog_and_message_db.getDBFile(), Account.Type.WHATSAPP)
                self.parse_calllogs(calllog_and_message_db, helper)
                self.parse_messages(dataSource, calllog_and_message_db, helper,
                                    current_case)

        except NoCurrentCaseException as ex:
            #If there is no current case, bail out immediately.
            self._logger.log(Level.WARNING, "No case currently open.", ex)
            self._logger.log(Level.WARNING, traceback.format_exec())

        #Clean up open file handles.
        for contact_db in contact_dbs:
            contact_db.close()

        for calllog_and_message_db in calllog_and_message_dbs:
            calllog_and_message_db.close()
Exemplo n.º 34
0
def move(args):
    command = args['button']['command']
    print(args)
    print(command)

    try:
        if command == 'F' or command == 'f':
            # your hardware movement code for forward goes here
            motors(128, 128)
            time.sleep(0.5)
            motors(0, 0)
            print("F")
            return
        elif command == 'B' or command == 'b':
            # your hardware movement code for backwards goes here
            motors(-128, -128)
            time.sleep(0.5)
            motors(0, 0)
            print("B")
            return
        elif command == 'L' or command == 'l':
            # your hardware movement code for left goes here
            motors(-128, 128)
            time.sleep(0.05)
            motors(0, 0)
            print("L")
            return
        elif command == 'R' or command == 'r':
            # your hardware movement code for right goes here
            motors(128, -128)
            time.sleep(0.05)
            motors(0, 0)
            print("R")
            return
        elif command == 'w':
            rvr.wake()
    except:
        import traceback
        print(traceback.format_exec())
    return
Exemplo n.º 35
0
    def set_maintenance(self, mode):
        maintenance = Setting.query.filter(
            Setting.name == 'maintenance').first()

        if maintenance is None:
            value = self.defaults['maintenance']
            maintenance = Setting(name='maintenance', value=str(value))
            db.session.add(maintenance)

        mode = str(mode)

        try:
            if maintenance.value != mode:
                maintenance.value = mode
                db.session.commit()
            return True
        except Exception as e:
            current_app.logger.error(
                'Cannot set maintenance to {0}. DETAIL: {1}'.format(mode, e))
            current_app.logger.debug(traceback.format_exec())
            db.session.rollback()
            return False
Exemplo n.º 36
0
    try:
        request = urllib2.Request(url, headers={'User-Agent': useragent})
        response = urllib2.urlopen(request)
        json = j.loads(response.read())
        response.close()
        return Results(json)
    except urllib2.HTTPError, err:
        print 'HTTPError = ' + str(err.code)
    except urllib2.URLError, err:
        print 'URLError = ' + str(err.reason)
    except urllib2.HTTPException:
        print 'HTTPException'
    except Exception:
        import traceback
        print traceback.format_exec()
    import sys
    sys.exit("Error attempting to search " + url)


class Results(object):
    def __init__(self, json):
        self.json = j.dumps(json, indent=2)
        self.type = {'A': 'article', 'D': 'disambiguation',
                     'C': 'category', 'N': 'name',
                     'E': 'exclusive', '': 'nothing'}[json['Type']]
        self.answer = Answer(json)
        self.result = Result(json.get('Results', None))
        self.abstract = Abstract(json)
        self.definition = Definition(json)
        self.redirect = Redirect(json)
Exemplo n.º 37
0
import email_sender
import urls

import logging
import datetime
import traceback

from tornado.options import options

if __name__ == "__main__":
    # Load settings
    settings.load_settings()

    application = tornado.web.Application(urls.urls, **options.as_dict())
    application.listen(options.port)
    server_instance = tornado.ioloop.IOLoop.instance()
    # tornado.autoreload.add_reload_hook(database.release)

    try:
        server_instance.start()
    except KeyboardInterrupt:
        logging.error("Existing")
        exit_error = u'Keyboard Exit'
    except Exception, e:
        logging.exception(e)
        exit_error = traceback.format_exec()
    finally:
        server_instance.add_callback(server_instance.stop)
        exit_error = str(datetime.datetime.now()) + '\n' + exit_error
        email_sender.send(title='Server exit unexpectly', message=exit_error)
Exemplo n.º 38
0
def format_exeception():
    """Format the exception traceback.

    :return: The traceback string.
    """
    return traceback.format_exec().rstrip()
Exemplo n.º 39
0
parser.add_argument('-l', '--burst-latency', nargs=1,
                    help='The period between bursts.', type=int, default=3000)
parser.add_argument('-s', '--burst-size', nargs=1,
                    help='The height of your bursts.', type=int, default=1024)
parser.add_argument('-u', '--users', nargs=2, help='The user names you would like to use.',
                    default=[new_name(), new_name()])
parser.add_argument(
    'command', nargs=1, help='The process you would like to run.')
parser.add_argument(
	'-c', '--content', nargs=1, help='The ASCII content of the message you would like to send.')

args = parser.parse_args()

commands = {
    'client': client,
    'server': server
}

users = []

for name in args.users:
	users.append(register_name(name))

try:
    commands[args.command].run(args.burst_latency, args.burst_size, users.)
except KeyError:
    print('Invalid command type.')
except StandardError as e:
    print('Unknown error. Printing traceback.')
    print(traceback.format_exec())
def start_adc_one(d,n,dx,data,key):
    """
        d is device handle
        n is the number of samples needed
        dx is the distance between samples
        data is the data dictionary
        key is the keyword specifier
    """
    d.streamStart()
    missed = 0
    try:
        for r in d.streamData():
            if r is not None:
                #if dataCount >= packetRequest:
                    #break
                if r['errors'] != 0:
                    print ("Error: %s ; " % r['errors'])
                if r['numPackets'] != d.packetsPerRequest:
                    print ("----- UNDERFLOW : %s : " % r['numPackets'])
                if r['missed'] !=0:
                    missed += r['missed']
                try:
                    wlf
                except NameError:
                    sig = r['AIN0']
                    scan = r['AIN2']
                    wlf = r['AIN3']
                else:
                    sig = np.append(sig, r['AIN0'])
                    scan = np.append(scan, r['AIN2'])
                    wlf = np.append(wlf, r['AIN3'])
                    if sig.size >= n:
                        break
            else:
                print ("No data - stream sample rate slower than USB timeout")
    except:
        print "".join(i for i in traceback.format_exec())
    finally:
        d.streamStop()
        if missed != 0: print 'missed ',missed,' samples!!'
        #wlf=np.append(wlf,wlf[-1])
        la=np.array([sig.size,wlf.size,scan.size])
        l=la.min()
        sig=sig[:l-1]
        wlf=wlf[:l-1]
        scan=scan[:l-1]
        iidex=np.where(scan > 2.5)
        #print 'before cut ',sig.size
        #sig=sig[iidex]
        #print 'after cut' ,sig.size
        #wlf=wlf[iidex]
        #scan=scan[iidex]
        delay = np.arange(len(wlf))*dx
        dwlf=wlf-np.roll(wlf,1)
        dwlf[0] = dwlf[1]
        dwlf[-1]=dwlf[-2]
        dwlf = abs(dwlf)
        pos = delay[np.where(dwlf == np.max(dwlf))]
        delay = delay - pos[0]
        data['sig'+key] = sig
        data['scan'+key] = scan
        data['wlf'+key] = wlf
        data['delay'+key] = delay
    return
Exemplo n.º 41
0
def format_exeception():
    """Format the exception traceback.

    :return: The traceback string.
    """
    return traceback.format_exec().rstrip()
Exemplo n.º 42
0
                if LOG_LEVEL == 4: log_probe(*data)
                alerts[bssid] = datetime.now()
                call_alerts(bssid=bssid, rssi=rssi, essid=essid, oui=resolve_oui(bssid))

# connect to the wuds database
# wuds runs as root and should be able to write anywhere
with sqlite3.connect(LOG_FILE) as conn:
    with closing(conn.cursor()) as cur:
        # build the database schema if necessary
        cur.execute('CREATE TABLE IF NOT EXISTS probes (dtg TEXT, mac TEXT, rssi INT, ssid TEXT, oui TEXT)')
        cur.execute('CREATE TABLE IF NOT EXISTS messages (dtg TEXT, lvl TEXT, msg TEXT)')
        conn.commit()
        log_message(0, 'WUDS started.')
        # set up the sniffer
        cap = pcapy.open_live(IFACE, 1514, 1, 0)
        alerts = {}
        ouis = {}
        # start the sniffer
        while True:
            try:
                (header, pkt) = cap.next()
                if cap.datalink() == 0x7F:
                    packet_handler(pkt)
            except KeyboardInterrupt:
                break
            except:
#DES-feb1-2016--thiskeeps hanging on format_exec call?#                if DEBUG: print traceback.format_exec()
		if DEBUG: print traceback.format_exec()
                continue
        log_message(0, 'WUDS stopped.')
Exemplo n.º 43
0
#/usr/bin/env python
#coding: utf-8

from flask import request
from . import app
import json, traceback
import utils

def auth_login(func):
    def wrapper(*arg, **kwargs)
        try:
            authorization = request.headers.get('authorization': None)
            res = utils.validate(authorization, app.config['passport_key'])
            res = json.loads(res)
            if int(res['code']) == 1:
                utils.write_log('api').warning('Request forbinden: %s' % res['errmsg'])
                return json.dumps({'code':1, 'errmsg': result['errmsg']})
        except:
            utils.write_log('api').warning('Validate error: %s' % traceback.format_exec())
            return json.dumps({'code':1, 'errmsg': '验证异常'})
        return func(res, *arg, **kwargs)
    wrapper.__name__ = '%s_wrapper' % func.__name__
    return wrapper