download log of current python script from EV3
766405
def download_log_of_current_script():
    """"""

    try:
        #Return None, if script is not saved and user closed file saving window, otherwise return file name.
        src_file = get_workbench().get_current_editor().get_filename(False)
        if src_file is None:
            return
        download_log(src_file)
    except Exception:
        error_msg = traceback.format_exc(0)+'\n'
        showerror("Error", error_msg)
1369825
def upload_current_script():
    """"""
    current_editor = get_workbench().get_editor_notebook().get_current_editor()
    code = current_editor.get_text_widget().get("1.0", "end")
    try:
        filename= current_editor.get_filename()
        if (not filename) or (not filename.endswith(".py")):
            return

        ast.parse(code)

        if not code.startswith('#!'):
            if tkMessageBox.askokcancel("Shebang", "To make a python file on the EV3 executable Thonny prepends the shebang line:\n\n      !#/usr/bin/env python3\n"):
                current_editor.get_text_widget().direct_insert("1.0", "#!/usr/bin/env python3\n")
            else:
               return

        # automatically save file (without confirm dialog, nor dialog for asking filename )
        # save_file does return None, if script is not saved and user closed file saving window, otherwise return file name.
        py_file = current_editor.save_file(False)
        if py_file is None:
            return

        upload(py_file)
    except Exception:
        error_msg = traceback.format_exc(0)+'\n'
        showerror("Error", error_msg)
277063
def download_script(script_file_name):
    ''''''
    return "Sorry! Temporarily disabled."
    if script_file_name[:-3] in registered_modules:
        loaded_module = registered_modules[script_file_name[:-3]]
        package_path = os.sep.join(loaded_module.__package__.split('.')[1:])
        return send_from_directory(directory=os.path.join(
                                      app.config['SCRIPTS_DIR'],
                                      package_path),
                                   filename=script_file_name)
    else:
        return "ERROR"
207457
def _get_scripts_resource(pe):
    """"""
    res = None
    for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries:
        if entry.name and entry.name.string == b"PYTHONSCRIPT":
            res = entry.directory.entries[0].directory.entries[0]
            break
    return res
617667
def get_script_from_egg(name, dist):
  """"""
  if dist.metadata_isdir('scripts') and name in dist.metadata_listdir('scripts'):
    return (
        os.path.join(dist.egg_info, 'scripts', name),
        dist.get_metadata('scripts/%s' % name).replace('\r\n', '\n').replace('\r', '\n'))
  return None, None
234035
def scrape(cls, start, end, output):
        
        # Logger setting
        logging.basicConfig(
            level=logging.INFO,
            format="time:%(asctime)s.%(msecs)03d" + "\tmessage:%(message)s",
            datefmt="%Y-%m-%d %H:%M:%S"
        )

        # validate
        for param_day in ({'name': 'Start Day', 'value': start}, {'name': 'End Day', 'value': end}):
            try:
                cls._validate_datetime(param_day['value'])
            except (validators.Invalid, MlbAmException) as e:
                raise MlbAmException('{msg} a {name}.'.format(name=param_day['name'], msg=e.msg))
        cls._validate_datetime_from_to(start, end)

        # Download
        logging.info('->- MLBAM dataset download start')
        mlb = MlbAm(os.path.dirname(os.path.abspath(__file__)), output, cls._days(start, end))
        mlb.download()
        logging.info('-<- MLBAM dataset download end')
1050932
function getEnv() {
    var ua = navigator.userAgent;

    env = {
      // True if this browser supports disabling async mode on dynamically
      // created script nodes. See
      // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
      async: doc.createElement('script').async === true
    };

    (env.webkit = /AppleWebKit\//.test(ua))
      || (env.ie = /MSIE/.test(ua))
      || (env.opera = /Opera/.test(ua))
      || (env.gecko = /Gecko\//.test(ua))
      || (env.unknown = true);
  }
1269129
def cleanup_files_on_ev3():
    """"""

    list = get_base_ev3dev_cmd() + ['cleanup']

    env = os.environ.copy()
    env["PYTHONUSERBASE"] = THONNY_USER_BASE
    proc = subprocess.Popen(list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                            universal_newlines=True, env=env)
    dlg = MySubprocessDialog(get_workbench(), proc, "Delete files in homedir on EV3", autoclose=False)
    dlg.wait_window()
1248095
def _dbg_dump_virtual_outputs(imgObjList):
    
    global _fidx
    tag = 'virtual'
    log.info((tag+'  ')*7)
    for iii in imgObjList:
        log.info('-'*80)
        log.info(tag+'  orig nm: '+iii._original_file_name)
        log.info(tag+'  names.data: '+str(iii.outputNames["data"]))
        log.info(tag+'  names.orig: '+str(iii.outputNames["origFilename"]))
        log.info(tag+'  id: '+str(id(iii)))
        log.info(tag+'  in.mem: '+str(iii.inmemory))
        log.info(tag+'  vo items...')
        for vok in sorted(iii.virtualOutputs.keys()):
            FITSOBJ = iii.virtualOutputs[vok]
            log.info(tag+': '+str(vok)+' = '+str(FITSOBJ))
            if vok.endswith('.fits'):
                if not hasattr(FITSOBJ, 'data'):
                    FITSOBJ = FITSOBJ[0] # list of PrimaryHDU ?
                if not hasattr(FITSOBJ, 'data'):
                    FITSOBJ = FITSOBJ[0] # was list of HDUList ?
                dbgname = 'DEBUG_%02d_'%(_fidx,)
                dbgname+=os.path.basename(vok)
                _fidx+=1
                FITSOBJ.writeto(dbgname)
                log.info(tag+'  wrote: '+dbgname)
                log.info('\n'+vok)
                if hasattr(FITSOBJ, 'data'):
                    log.info(str(FITSOBJ._summary()))
                    log.info('min and max are: '+str( (FITSOBJ.data.min(),
                                                       FITSOBJ.data.max()) ))
                    log.info('avg and sum are: '+str( (FITSOBJ.data.mean(),
                                                       FITSOBJ.data.sum()) ))
#                    log.info(str(FITSOBJ.data)[:75])
                else:
                    log.info(vok+' has no .data attr')
                    log.info(str(type(FITSOBJ)))
                log.info(vok+'\n')
    log.info('-'*80)
761168
def save_all_ggr_logs(cls, test_name, test_passed):
        
        log_name = '{} [driver {}]' if len(cls.driver_wrappers) > 1 else '{}'
        driver_index = 1
        for driver_wrapper in cls.driver_wrappers:
            if not driver_wrapper.driver or driver_wrapper.server_type not in ['ggr', 'selenoid']:
                continue
            try:
                if driver_wrapper.config.getboolean_optional('Server', 'logs_enabled') or not test_passed:
                    name = get_valid_filename(log_name.format(test_name, driver_index))
                    Selenoid(driver_wrapper).download_session_log(name)
            except Exception as exc:
                # Capture exceptions to avoid errors in teardown method due to session timeouts
                driver_wrapper.logger.warn('Error downloading GGR logs: %s' % exc)
            driver_index += 1
1111400
def _get_scripts(self, scripts_path_rel, files_deployment, script_type, project_path):
        

        scripts_dict = {}
        if scripts_path_rel:

            self._logger.debug('Getting scripts with {0} definitions'.format(script_type))
            scripts_dict = pgpm.lib.utils.misc.collect_scripts_from_sources(scripts_path_rel, files_deployment,
                                                                            project_path, False, self._logger)
            if len(scripts_dict) == 0:
                self._logger.debug('No {0} definitions were found in {1} folder'.format(script_type, scripts_path_rel))
        else:
            self._logger.debug('No {0} folder was specified'.format(script_type))

        return scripts_dict
86044
function getScriptData(evt) {
            //Using currentTarget instead of target for Firefox 2.0's sake. Not
            //all old browsers will be supported, but this one was easy enough
            //to support and still makes sense.
            var node = evt.currentTarget || evt.srcElement;

            //Remove the listeners once here.
            removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
            removeListener(node, context.onScriptError, 'error');

            return {
                node: node,
                id: node && node.getAttribute('data-requiremodule')
            };
        }
380147
def _get_progress(self):
        
        input_data = []
        ret = {}

        # traverse emerge.log from bottom up to get latest information
        last_lines = self.py3.command_output(["tail", "-50", self.emerge_log_file])
        input_data = last_lines.split("\n")
        input_data.reverse()

        for line in input_data:
            if "*** terminating." in line:
                # copy content of ret_default, not only the references
                ret = copy.deepcopy(self.ret_default)
                break
            else:
                status_re = re.compile(
                    "\((?P<cu>[\d]+) of (?P<t>[\d]+)\) "
                    "(?P<a>[a-zA-Z\/]+( [a-zA-Z]+)?) "
                    "\((?P<ca>[\w\-]+)\/(?P<p>[\w\.]+)"
                )
                res = status_re.search(line)
                if res is not None:
                    ret["action"] = res.group("a").lower()
                    ret["category"] = res.group("ca")
                    ret["current"] = res.group("cu")
                    ret["pkg"] = res.group("p")
                    ret["total"] = res.group("t")
                    break
        return ret
1146909
def build_flask_like_logger(
    logger_name='logger',
    log_level=None,
    log_dir=None,
    console_enabled=True,
    max_log_size=5*1024*1024,
    max_backup_logs=5,
    host=None):
    '''
    
    '''
    old_logger_class = logging.getLoggerClass()
    logging.setLoggerClass(FlaskLikeLogger)
    logger = logging.getLogger(logger_name)
    logging.setLoggerClass(old_logger_class)

    if log_level:
        logger.setLevel(log_level)
    if host:
        logger.set_host(host)
    logger.apply_default_handlers(log_dir, console_enabled, max_log_size, max_backup_logs)
    return logger
282256
def _download_ota_script(script_url):
    """"""

    try:
        blob = requests.get(script_url, stream=True)
        return blob.content
    except Exception as e:
        iprint("Failed to download OTA script")
        iprint(e)
        return False
364266
def import_log_funcs():
    """"""
    global g_logger
 
    curr_mod = sys.modules[__name__]

    for func_name in _logging_funcs:
        func = getattr(g_logger, func_name)
        setattr(curr_mod, func_name, func)
555204
def _script_reload(script, input, output):
    """"""
    input = [Path(entry).expand().abspath() for entry in input]
    output = Path(output).expand().abspath()
    cmd = 'python3 {0} {1} {2}'.format(script, ' '.join(input), output)
    event_handler = RunScriptChangeHandler(cmd)
    event_handler.run()  # run always once
    observer = Observer()
    path = script.dirname().expand().abspath()
    click.secho('watch: {0}'.format(path), fg='blue')
    observer.schedule(event_handler, path, recursive=True)
    for entry in input:
        entry = entry.dirname().expand().abspath()
        click.secho('watch: {0}'.format(entry), fg='blue')
        observer.schedule(event_handler, entry, recursive=True)
    path = Path(__file__).parent / 'qface'
    click.secho('watch: {0}'.format(path), fg='blue')
    observer.schedule(event_handler, path, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()