Like Connection.bulk_query, but takes a filename to load a query
        from.
487814
def bulk_query_file(self, path, *multiparams):
        

         # If path doesn't exists
        if not os.path.exists(path):
            raise IOError("File '{}'' not found!".format(path))

        # If it's a directory
        if os.path.isdir(path):
            raise IOError("'{}' is a directory!".format(path))

        # Read the given .sql file into memory.
        with open(path) as f:
            query = f.read()

        self._conn.execute(text(query), *multiparams)
56711
def query_file(self, path, fetchall=False, **params):
        """"""

        # If path doesn't exists
        if not os.path.exists(path):
            raise IOError("File '{}' not found!".format(path))

        # If it's a directory
        if os.path.isdir(path):
            raise IOError("'{}' is a directory!".format(path))

        # Read the given .sql file into memory.
        with open(path) as f:
            query = f.read()

        # Defer processing to self.query method.
        return self.query(query=query, fetchall=fetchall, **params)
1052639
def query(querystr, connection=None, **connectkwargs):
    
    if connection is None:
        connection = connect(**connectkwargs)
    cursor = connection.cursor()
    cursor.execute(querystr)
    return cursor.fetchall()
946797
def query_bulk(names):
    """"""
    answers = [__threaded_query(name) for name in names]

    while True:
        if all([a.done() for a in answers]):
            break
        sleep(1)

    return [answer.result() for answer in answers]
954516
def _get_sql(filename):
    """"""
    with open(os.path.join(SQL_DIR, filename), 'r') as f:
        return f.read()
1189041
def _search(mapping, filename):
    """"""
    result = mapping.get(filename)
    if result is not None:
        return result
    name, ext = os.path.splitext(filename)
    result = mapping.get(ext)
    if result is not None:
        for pattern, result2 in result:
            if fnmatch(filename, pattern):
                return result2
    return None
630583
def load_infile_sql(path, columns, options={})
      replacement = opts[:insert_ignore] ? :ignore : :replace
      options = {:update => replacement}.merge(options)
      LoadDataInfileExpression.new(path, 
                                   opts[:from].first, 
                                   columns, 
                                   options).
        to_sql(db)
    end
33325
def load_from_dict(db, data, metadata):
    
    # The ORM overhead is too high for this kind of bulk load,
    # so drop down to SQLAlchemy Core.
    # This tries to do minimize the number of SQL commands by loading entire
    # tables at once

    if metadata['version'] != 2:
        raise ValueError('Can only load version 2')

    try:
        bind = db.get_bind(tables.Event)
    except (ValueError, AttributeError):
        pass
    else:
        if bind.dialect.name == 'sqlite':
            db.execute('PRAGMA foreign_keys = ON')

    with bulk_inserter(db) as insert:

        # Load speakers

        speaker_slugs = set()

        for series_slug, series in data['series'].items():
            for event_slug, event in series['events'].items():
                for talk in event.get('talks'):
                    for speaker in talk.get('speakers', ()):
                        if speaker not in speaker_slugs:
                            speaker_slugs.add(speaker)
                            insert(tables.Speaker, {
                                'slug': speaker,
                                'name': speaker,
                            })

        venue_ids = {}

        # Load cities, and their venues

        for city_slug, city in data['cities'].items():
            city_data = city['city']
            insert(tables.City, {
                'slug': city_slug,
                'name': city_data['name'],
                'latitude': city_data['location']['latitude'],
                'longitude': city_data['location']['longitude'],
                '_source': city_data['_source'],
            })

            for venue_slug, venue in city.get('venues', {}).items():
                venue_ids[city_slug, venue_slug] = insert(tables.Venue, {
                    'city_slug': city_slug,
                    'slug': venue_slug,
                    'name': venue['name'],
                    'address': venue.get('address'),
                    'latitude': venue['location']['latitude'],
                    'longitude': venue['location']['longitude'],
                    'notes': venue.get('notes'),
                })


        # Load series, their events, and everything underneath

        for series_slug, series_dir in data['series'].items():

            series = series_dir['series']
            recurrence = series.get('recurrence')
            if recurrence:
                rrule_str = recurrence['rrule']
                rrule.rrulestr(rrule_str)  # check rrule syntax
                recurrence_attrs = {
                    'recurrence_rule': rrule_str,
                    'recurrence_scheme': recurrence['scheme'],
                    'recurrence_description_cs': recurrence['description']['cs'],
                    'recurrence_description_en': recurrence['description']['en'],
                }
            else:
                recurrence_attrs = {
                    'recurrence_rule': None,
                    'recurrence_scheme': None,
                    'recurrence_description_cs': None,
                    'recurrence_description_en': None,
                }
            insert(tables.Series, {
                'slug': series_slug,
                'name': series['name'],
                'home_city_slug': series.get('city'),
                'description_cs': series['description']['cs'],
                'description_en': series['description']['en'],
                'organizer_info': json.dumps(series.get('organizer-info', ())),
                **recurrence_attrs,
            })

            for event_slug, event in series_dir['events'].items():
                venue_slug = event.get('venue')
                city_slug = event['city']
                if venue_slug:
                    venue_id = venue_ids[city_slug, venue_slug]
                else:
                    venue_id = None

                start = make_full_datetime(event['start'])
                end = event.get('end')
                if end is None:
                    end = start.replace(hour=23, minute=59, second=59)
                event_id = insert(tables.Event, {
                    'name': event['name'],
                    'number': event.get('number'),
                    'topic': event.get('topic'),
                    'description': event.get('description'),
                    'date': start.date(),
                    'start_time': start.time(),
                    'end': end,
                    'all_day': event.get('all_day', False),
                    'series_slug': series_slug,
                    'city_slug': city_slug,
                    'venue_id': venue_id,
                    '_source': event['_source']
                })

                for i, talk in enumerate(event.get('talks', ())):
                    talk_id = insert(tables.Talk, {
                        'event_id': event_id,
                        'index': i,
                        'title': talk['title'],
                        'description': talk.get('description'),
                        'is_lightning': talk.get('lightning', False),
                    })

                    for i, speaker in enumerate(talk.get('speakers', ())):
                        assert speaker in speaker_slugs
                        insert(tables.TalkSpeaker, {
                            'talk_id': talk_id,
                            'index': i,
                            'speaker_slug': speaker,
                        })

                    for i, link in enumerate([
                            *({'talk': u} for u in talk.get('urls', ())),
                            *talk.get('coverage', {})]):
                        for kind, url in link.items():
                            insert(tables.TalkLink, {
                                'talk_id': talk_id,
                                'index': i,
                                'url': url,
                                'kind': kind,
                            })

                for i, url in enumerate(event.get('urls', ())):
                    insert(tables.EventLink, {
                        'event_id': event_id,
                        'index': i,
                        'url': url,
                    })
769390
def LoadFile(f, table_name, conn):
  """"""
  reader = csv.reader(f)
  header = next(reader)

  columns = []
  for n in header:
    n = n.replace(' ', '')
    n = n.replace('-', '_')
    columns.append(n)

  create_columns = []
  column_types = {}
  for n in columns:
    if n in column_types:
      create_columns.append("%s %s" % (n, column_types[n]))
    else:
      create_columns.append("%s INTEGER" % (n))

  c = conn.cursor()
  try:
    c.execute("CREATE TABLE %s (%s)" % (table_name, ",".join(create_columns)))
  except sqlite.OperationalError:
    # Likely table exists
    print("table %s already exists?" % (table_name))
    for create_column in create_columns:
      try:
        c.execute("ALTER TABLE %s ADD COLUMN %s" % (table_name, create_column))
      except sqlite.OperationalError:
        # Likely it already exists
        print("column %s already exists in %s?" % (create_column, table_name))

  placeholders = ",".join(["?"] * len(columns))
  insert_values = "INSERT INTO %s (%s) VALUES (%s)" % (table_name, ",".join(columns), placeholders)

  #c.execute("BEGIN TRANSACTION;")
  for row in reader:
    if row:
      if len(row) < len(columns):
        row.extend([None] * (len(columns) - len(row)))
      c.execute(insert_values, row)
  #c.execute("END TRANSACTION;")
  conn.commit()
204436
def query_file(self, path, fetchall=False, **params):
        """"""

        with self.get_connection() as conn:
            return conn.query_file(path, fetchall, **params)
574096
def __read_single_query_result(rs, field_names):
    '''
    
    '''

    rf = StringIO.StringIO(rs)

    def readline():
        l = rf.readline()
        if not l.endswith('\n'):
            raise EOFError()
        return l.strip()

    result = Result()

    try:
        l = readline()
        assert l.startswith('# BLAST')

        l = readline()
        assert l.startswith('# Query: ')
        query_str = l[len('# Query: '):].strip()
        if query_str:
            if ' ' in query_str:
                result.id, result.description = [
                    s.strip() for s in query_str.split(' ', 1)]
            else:
                result.id = query_str

        l = readline()
        assert l.startswith('# Database: ')

        l = readline()
        if l.startswith('# Fields: '):
            fns = l[len('# Fields: '):].split(', ')
            assert len(field_names) == len(fns)
            l = readline()

        assert l.endswith(' hits found')
        nhits = int(l[len('# '):-1 * len(' hits found')])

        while nhits > 0:
            l = readline()
            field_vals = l.split('\t')
            assert len(field_vals) == len(field_names)

            fields = dict(zip(field_names, field_vals))
            result.hits.append(Hit(fields))
            nhits -= 1

        return result, rf.read()
    except EOFError:
        return None, rs
205163
def bulk_fetch(bulk_fetch_ids, odba_caller)
			instances = []
			loaded_ids = []
			bulk_fetch_ids.each { |id|
				if(entry = fetch_cache_entry(id))
					entry.odba_add_reference(odba_caller)
					instances.push(entry.odba_object)
					loaded_ids.push(id)
				end
			}
			bulk_fetch_ids -= loaded_ids
			unless(bulk_fetch_ids.empty?)
				rows = ODBA.storage.bulk_restore(bulk_fetch_ids)
				instances += bulk_restore(rows, odba_caller)
			end
			instances
		end
1059157
def load(self, filename):
        """"""
        LOGGER.info("Loading result from '%s'.", filename)
        if filename.endswith(".gz"):
            with gzip.open(filename, "rb") as file_handle:
                result = MemoteResult(
                    json.loads(file_handle.read().decode("utf-8"))
                )
        else:
            with open(filename, "r", encoding="utf-8") as file_handle:
                result = MemoteResult(json.load(file_handle))
        # TODO (Moritz Beber): Validate the read-in JSON maybe? Trade-off
        #  between extra time taken and correctness. Maybe we re-visit this
        #  issue when there was a new JSON format version needed.
        return result
1072688
def splitquery(url):
    """"""
    global _queryprog
    if _queryprog is None:
        import re
        _queryprog = re.compile('^(.*)\?([^?]*)$')

    match = _queryprog.match(url)
    if match: return match.group(1, 2)
    return url, None
592197
def load(self, *filenames):
        """"""
        if len(filenames) == 1:
            if os.path.basename( filenames[0] ) == 'index.coldshot':
                return self.load_coldshot( os.path.dirname( filenames[0]) )
            elif os.path.isdir( filenames[0] ):
                return self.load_coldshot( filenames[0] )
        try:
            self.loader = pstatsloader.PStatsLoader(*filenames)
            self.ConfigureViewTypeChoices()
            self.SetModel( self.loader )
            self.viewType = self.loader.ROOTS[0]
            self.SetTitle(_("Run Snake Run: %(filenames)s")
                          % {'filenames': ', '.join(filenames)[:120]})
        except (IOError, OSError, ValueError,MemoryError), err:
            self.SetStatusText(
                _('Failure during load of %(filenames)s: %(err)s'
            ) % dict(
                filenames=" ".join([repr(x) for x in filenames]),
                err=err
            ))
1188926
function getQueries(req, end) {
  var urlencoded = /^application\/x-www-form-urlencoded/;
  var multipart = /^multipart\/form-data/;
  var contentType = req.headers['content-type'] || '';

  if (multipart.test(contentType)) {
    // Multipart data.
    req.form = req.form || new formidable.IncomingForm();
    req.form.multiples = true;
    req.form.parse(req, function(err, fields, files) {
      req.fields = fields;
      req.files = files;
      // Ensure that files are arrays.
      for (var key in req.files) {
        if (!(req.files[key] instanceof Array)) {
          req.files[key] = [req.files[key]];
        }
      }
      if (err == null) {
        addToQuery(req, req.fields);
        addToQuery(req, req.files);
      }
      end(err);
    });

  } else if (urlencoded.test(contentType)) {
    // URL encoded data.
    var chunks;
    var gotrequest = function (chunk) {
      if (chunk !== undefined) {
        if (chunks === undefined) {
          chunks = chunk;
        } else {
          chunks = Buffer.concat([chunks, chunk]);
        }
      }
    };
    req.on('data', gotrequest);
    req.on('end', function(err) {
      if (req.server.saveRequestChunks) {
        req.savedChunks = chunks;
      }
      var strquery = chunks? chunks.toString(): '';
      jsonFromQuery(strquery, req.query);
      end(err);
    });
  } else {
    // URL query parameters.
    var search = req.uri.search || '';
    jsonFromQuery(search.slice(1), req.query);
    end();
  }
}
679854
def query(cls, *args, **kwargs):
        
        for doc in cls._coll.find(*args, **kwargs):
            yield cls.from_storage(doc)