This function runs .sql scripts in the folder 'sql_scripts'
438073
def run_sql_script(conn, scriptname='results_md2grid.sql'):
    

    script_dir = os.path.abspath(
        os.path.join(os.path.dirname(__file__), 'sql_scripts'))
    script_str = open(os.path.join(script_dir, scriptname)).read()
    conn.execution_options(autocommit=True).execute(script_str)

    return
910802
def run(self, tool, args, new_import_path=''):
        
        if new_import_path != '':
            #print('APPENDING PATH = ', new_import_path)
            sys.path.append(new_import_path)
        
        #if silent == 'N':
        print('main called ' + tool['file'] + '->' + tool['function'] + ' with ', args, ' = ', tool['return'])
        mod = __import__( os.path.basename(tool['file']).split('.')[0]) # for absolute folder names
        # mod = __import__( tool['file'][:-2]) # for aikif folders (doesnt work)
        func = getattr(mod, tool['function'])
        tool['return'] = func(args)
        return tool['return']
105151
def _initDatabase(self):
        
        queries = []

        if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0:
            for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]:
                sqlFile = open(scriptFilePath, "r")
                queriesInFile = self.extractFromSQLFile(sqlFile)
                sqlFile.close()

                queries.extend(queriesInFile)

        def failCallback(error):
            errorMessage = str(error)
            if isinstance(error, Failure):
                errorMessage = error.getErrorMessage()

            self.log.error(
                "[Viper.MySQL] _initDatabase() database error: {errorMessage}",
                errorMessage=errorMessage
            )

        def runCallback(transaction, queries):
            try:
                for query in queries:
                    transaction.execute(query)
            except Exception as e:
                failCallback(e)
                return

        interaction = self.runInteraction(runCallback, queries)
        interaction.addErrback(failCallback)
92710
function runScripts() {
  var scripts = [];
  var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"];
  var index = 0;

  /**
   * Transform and execute script. Ensures correct load order.
   */

  var exec = function exec() {
    var param = scripts[index];
    if (param instanceof Array) {
      transform.run.apply(transform, param);
      index++;
      exec();
    }
  };

  /**
   * Load, transform, and execute all scripts.
   */

  var run = function run(script, i) {
    var opts = {};

    if (script.src) {
      transform.load(script.src, function (param) {
        scripts[i] = param;
        exec();
      }, opts, true);
    } else {
      opts.filename = "embedded";
      scripts[i] = [script.innerHTML, opts];
    }
  };

  // Collect scripts with Babel `types`.

  var _scripts = global.document.getElementsByTagName("script");

  for (var i = 0; i < _scripts.length; ++i) {
    var _script = _scripts[i];
    if (types.indexOf(_script.type) >= 0) scripts.push(_script);
  }

  for (i in scripts) {
    run(scripts[i], i);
  }

  exec();
}
887223
def execute_project_models_sql_scripts(force_update=False):
    
    # TODO: Remove except and use ignore_conflicts
    # on bulk_create when django 2.2. is released
    with open(MODEL_FILE, "r") as file_content:
        query = file_content.read()
        db = db_connector()
        query_result = db.execute_pandas_sql_query(query)
        db.close()
        try:
            projects = Project.objects.bulk_create(
                (Project(**vals) for vals in query_result.to_dict("records")),
                # ignore_conflicts=True available on django 2.2.
            )
            indicators = [FinancialIndicator(project=p) for p in projects]
            FinancialIndicator.objects.bulk_create(indicators)
        except IntegrityError:
            # happens when there are duplicated projects
            LOG("Projects bulk_create failed, creating one by one...")
            with transaction.atomic():
                if force_update:
                    for item in query_result.to_dict("records"):
                        p, _ = Project.objects.update_or_create(**item)
                        FinancialIndicator.objects.update_or_create(project=p)
                else:

                    for item in query_result.to_dict("records"):
                        p, _ = Project.objects.get_or_create(**item)
                        FinancialIndicator.objects.update_or_create(project=p)
381090
def action_run_command(self):
        

        name = self.args['<name>']

        # get entry from DB
        self.db_query('''
            SELECT path,command FROM shortcuts WHERE name=?
            ''', (name,))

        row = self.db_fetch_one()

        if row is None:
            print_err('Shortcut "%s" does not exist.' % name)
            return

        path = row[0]
        cmd = row[1]

        # show message
        msg = colored('JumpRun shortcut', 'white', attrs=['bold']) + '\n' + \
            self.shortcut_str(path, cmd) + '\n'
        print(msg)

        # cd to the folder & run the command
        os.chdir(path)

        try:
            subprocess.call(cmd, shell=True)
        except KeyboardInterrupt:
            print('')  # newline
            return
580344
function execute(sql, params) {

	if (0 === sql.trim().length) {
		console.error("\nNo SQL to process\n");
		yargs.showHelp();
		process.exit(1);
	}

	for (var i = 1; i < params.length; i++) {
		var a = params[i];
		if (a[0] !== '"' && a[0] !== "'") {
			if (+a == a) { // jshint ignore:line
				params[i] = +a;
			}
		}
	}

	alasql.promise(sql, params)
		.then(function (res) {
			if (!alasql.options.stdout) {
				console.log(formatOutput(res));
			}
			process.exit(0);
		}).catch(function (err) {
			let errorJsonObj = JSON.parse(JSON.stringify(err, Object.getOwnPropertyNames(err)));
			console.error(formatOutput({
				error: errorJsonObj
			}));
			process.exit(1);
		});
}
1248868
public function run()
    {
        $this->Script->startup();

        $this->Options = $this->Script->getOptions(
            "[db-host:][db-user:][db-password:][db-database:][db-type:|db-driver:][sql][clean][clean-all][conc:][php-exec:][commit-within:]",
            "",
            array(
                'db-host' => "Database host",
                'db-user' => "Database user",
                'db-password' => "Database password",
                'db-database' => "Database name",
                'db-driver' => "Database driver",
                'db-type' => "Database driver, alias for --db-driver",
                'sql' => "Display sql queries",
                'clean' =>  "Remove all search data of the current installation id before beginning indexing",
                'clean-all' => "Remove all search data for all installations",
                'conc' => 'Parallelization, number of concurent processes to use',
                'php-exec' => 'Full path to PHP executable',
                'commit-within' => 'Commit to Solr within this time in seconds (default '
                    . self::DEFAULT_COMMIT_WITHIN . ' seconds)',
            )
        );
        $this->Script->initialize();

        // check if ezfind is enabled and exit if not
        if ( ! in_array( 'ezfind', eZExtension::activeExtensions() ) )
        {
            $this->CLI->error( 'eZ Find extension is not enabled and because of that index process will fail. Please enable it and run this script again.' );
            $this->Script->shutdown( 0 );
        }

        // Fix siteaccess
        $siteAccess = $this->Options['siteaccess'] ? $this->Options['siteaccess'] : false;
        if ( $siteAccess )
        {
            $this->changeSiteAccessSetting( $siteAccess );
        }
        else
        {
            $this->CLI->warning( 'You did not specify a siteaccess. The admin siteaccess is a required option in most cases.' );
            $input = readline( 'Are you sure the default siteaccess has all available languages defined? ([y] or [q] to quit )' );
            if ( $input === 'q' )
            {
                $this->Script->shutdown( 0 );
            }
        }

        // Check that Solr server is up and running
        if ( !$this->checkSolrRunning() )
        {
            $this->Script->shutdown( 1 );
            exit();
        }

        $this->initializeDB();

        // call clean up routines which will deal with the CLI arguments themselves
        $this->cleanUp();
        $this->cleanUpAll();

        if ( isset( $this->Options['commit-within'] )
                && is_numeric( $this->Options['commit-within'] ) )
        {
            $this->commitWithin = (int)$this->Options['commit-within'];
        }


        $this->CLI->output( 'Starting object re-indexing' );

        // Get PHP executable from user.
        $this->getPHPExecutable();

        $this->runMain();
    }
1180617
def __run_embedded(db_name,argv):
    """"""
    __monkey_patch_database_class()

    run((DataBase,), args=argv, util=util, green_mode=GreenMode.Gevent)
764850
public function run()
    {
        foreach($this->dumpFiles() as $dumpPart) {

            $query = "LOAD DATA LOCAL INFILE '"
                    . str_replace('\\', '/', $dumpPart) . "'
                    INTO TABLE `" . Config::citiesTableName() . "` 
                        FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
                        LINES TERMINATED BY '\n' IGNORE 1 LINES
                        (country,
                        city_ascii,
                        city,
                        region,
                        population,
                        latitude,
                        longitude
                    )";

            DB::connection()->getpdo()->exec($query);

        }
    }
272138
public void runSql( String sql ) throws Exception {
        String[] sqlSplit = sql.split("\n");
        StringBuilder sb = new StringBuilder();
        for( String string : sqlSplit ) {
            String trim = string.trim();
            if (trim.length() == 0) {
                continue;
            }
            if (trim.startsWith("--")) {
                continue;
            }
            sb.append(trim + " ");
        }

        String[] sqls = sb.toString().split(";");
        for( String single : sqls ) {
            executeInsertUpdateDeleteSql(single);
        }
    }
44652
private int execSQLScript(String sqlScript) {

		String path = GeoPackageProperties.getProperty(PropertyConstants.SQL,
				"directory");
		List<String> statements = ResourceIOUtils.parseSQLStatements(path,
				sqlScript);

		for (String statement : statements) {
			db.execSQL(statement);
		}

		return statements.size();
	}
986343
def run(files, temp_folder):
    ""
    try:
        import flake8  # NOQA
    except ImportError:
        return NO_FLAKE_MSG
    try:
        from flake8.engine import get_style_guide
    except ImportError:
        # We're on a new version of flake8
        from flake8.api.legacy import get_style_guide

    py_files = filter_python_files(files)
    if not py_files:
        return
    DEFAULT_CONFIG = join(temp_folder, get_config_file())

    with change_folder(temp_folder):
        flake8_style = get_style_guide(config_file=DEFAULT_CONFIG)
        out, err = StringIO(), StringIO()
        with redirected(out, err):
            flake8_style.check_files(py_files)
    return out.getvalue().strip() + err.getvalue().strip()
340752
def run_server(dbpath=os.path.expanduser(config.dbserver.file),
               dbhostport=None, loglevel='WARN'):
    
    if dbhostport:  # assume a string of the form "dbhost:port"
        dbhost, port = dbhostport.split(':')
        addr = (dbhost, int(port))
    else:
        addr = (config.dbserver.listen, DBSERVER_PORT)

    # create the db directory if needed
    dirname = os.path.dirname(dbpath)
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    # create and upgrade the db if needed
    db('PRAGMA foreign_keys = ON')  # honor ON DELETE CASCADE
    actions.upgrade_db(db)
    # the line below is needed to work around a very subtle bug of sqlite;
    # we need new connections, see https://github.com/gem/oq-engine/pull/3002
    db.close()

    # reset any computation left in the 'executing' state
    actions.reset_is_running(db)

    # configure logging and start the server
    logging.basicConfig(level=getattr(logging, loglevel))
    DbServer(db, addr).start()
846429
def run(self, sqlTail = '', raw = False) :
		""""""
		sql, sqlValues = self.getSQLQuery()
		cur = self.con.execute('%s %s'% (sql, sqlTail), sqlValues)

		res = []
		for v in cur :
			if not raw :
				res.append(RabaPupa(self.rabaClass, v[0]))
			else :
				return v
		
		return res
288780
public function exec_script($sql)
    {
        $sql  = $this->fix_table_names($sql);
        $buff = '';
        $body = false;

        foreach (explode("\n", $sql) as $line) {
            $tok = strtolower(trim($line));
            if (preg_match('/^--/', $line) || $tok == '' || $tok == '/') {
                continue;
            }

            $buff .= $line . "\n";

            // detect PL/SQL function bodies, don't break on semicolon
            if ($body && $tok == 'end;') {
                $body = false;
            }
            else if (!$body && $tok == 'begin') {
                $body = true;
            }

            if (!$body && substr($tok, -1) == ';') {
                $this->query($buff);
                $buff = '';
                if ($this->db_error) {
                    break;
                }
            }
        }

        return !$this->db_error;
    }
266025
def main():
    """"""
    args = get_args()

    # Make Chronophore's directories and files in $HOME
    DATA_DIR = pathlib.Path(appdirs.user_data_dir(__title__))
    LOG_FILE = pathlib.Path(appdirs.user_log_dir(__title__), 'debug.log')
    os.makedirs(str(DATA_DIR), exist_ok=True)
    os.makedirs(str(LOG_FILE.parent), exist_ok=True)

    if args.version:
        print('{} {}'.format(__title__, __version__))
        raise SystemExit

    if args.debug:
        CONSOLE_LOG_LEVEL = logging.DEBUG
    elif args.verbose:
        CONSOLE_LOG_LEVEL = logging.INFO
    else:
        CONSOLE_LOG_LEVEL = logging.WARNING

    logger = set_up_logging(LOG_FILE, CONSOLE_LOG_LEVEL)
    logger.debug('-'*80)
    logger.info('{} {}'.format(__title__, __version__))
    logger.debug('Log File: {}'.format(LOG_FILE))
    logger.debug('Data Directory: {}'.format(DATA_DIR))

    if args.testdb:
        DATABASE_FILE = DATA_DIR.joinpath('test.sqlite')
        logger.info('Using test database.')
    else:
        DATABASE_FILE = DATA_DIR.joinpath('chronophore.sqlite')

    logger.debug('Database File: {}'.format(DATABASE_FILE))
    engine = create_engine('sqlite:///{}'.format(str(DATABASE_FILE)))
    Base.metadata.create_all(engine)
    Session.configure(bind=engine)

    if args.log_sql:
        logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

    if args.testdb:
        add_test_users(session=Session())

    controller.flag_forgotten_entries(session=Session())

    if args.tk:
        from chronophore.tkview import TkChronophoreUI
        TkChronophoreUI()
    else:
        try:
            from PyQt5.QtWidgets import QApplication
        except ImportError:
            print(
                'Error: PyQt5, which chronophore uses for its'
                + ' graphical interface, is not installed.'
                + "\nInstall it with 'pip install PyQt5'"
                + " or use the old Tk ui with 'chronophore --tk'."
            )
            raise SystemExit
        else:
            from chronophore.qtview import QtChronophoreUI
            app = QApplication(sys.argv)
            chrono_ui = QtChronophoreUI()
            chrono_ui.show()
            sys.exit(app.exec_())

    logger.debug('{} stopping'.format(__title__))