_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q245800 | ViirsRSR._get_bandfilenames | train | def _get_bandfilenames(self, **options):
"""Get filename for each band"""
conf = options[self.platform_name + '-viirs']
rootdir = conf['rootdir']
for section in conf:
if not section.startswith('section'):
| python | {
"resource": ""
} |
q245801 | ViirsRSR._get_bandfile | train | def _get_bandfile(self, **options):
"""Get the VIIRS rsr filename"""
# Need to understand why there are A&B files for band M16. FIXME!
# Anyway, the absolute response differences are small, below 0.05
# LOG.debug("paths = %s", str(self.bandfilenames))
path = self.bandfilenames... | python | {
"resource": ""
} |
q245802 | ViirsRSR._load | train | def _load(self, scale=0.001):
"""Load the VIIRS RSR data for the band requested"""
if self.bandname == 'DNB':
header_lines_to_skip = N_HEADER_LINES_DNB[self.platform_name]
else:
header_lines_to_skip = N_HEADER_LINES[self.platform_name]
try:
data = np.... | python | {
"resource": ""
} |
q245803 | MsiRSR._load | train | def _load(self, scale=0.001):
"""Load the Sentinel-2 MSI relative spectral responses
"""
with open_workbook(self.path) as wb_:
for sheet in wb_.sheets():
if sheet.name not in SHEET_HEADERS.keys():
continue
plt_short_name = PLATFOR... | python | {
"resource": ""
} |
q245804 | SlstrRSR._load | train | def _load(self, scale=1.0):
"""Load the SLSTR relative spectral responses
"""
LOG.debug("File: %s", str(self.requested_band_filename))
ncf = Dataset(self.requested_band_filename, 'r')
| python | {
"resource": ""
} |
q245805 | get_config | train | def get_config():
"""Get the configuration from file"""
if CONFIG_FILE is not None:
configfile = CONFIG_FILE
else:
configfile = BUILTIN_CONFIG_FILE
config = {}
with open(configfile, 'r') as fp_:
config = recursive_dict_update(config, yaml.load(fp_, Loader=UnsafeLoader))
| python | {
"resource": ""
} |
q245806 | Rayleigh._get_lutfiles_version | train | def _get_lutfiles_version(self):
"""Check the version of the atm correction luts from the version file in the
specific aerosol correction directory
"""
basedir = RAYLEIGH_LUT_DIRS[self._aerosol_type]
lutfiles_version_path = os.path.join(basedir,
... | python | {
"resource": ""
} |
q245807 | Rayleigh.get_effective_wavelength | train | def get_effective_wavelength(self, bandname):
"""Get the effective wavelength with Rayleigh scattering in mind"""
try:
rsr = RelativeSpectralResponse(self.platform_name, self.sensor)
except(IOError, OSError):
LOG.exception(
"No spectral responses for this ... | python | {
"resource": ""
} |
q245808 | griditer | train | def griditer(x, y, ncol, nrow=None, step=1):
"""
Iterate through a grid of tiles.
Args:
x (int): x start-coordinate
y (int): y start-coordinate
ncol (int): number of tile columns
nrow (int): number of tile rows. If not specified, this
defaults to ncol, s.t. a qua... | python | {
"resource": ""
} |
q245809 | bboxiter | train | def bboxiter(tile_bounds, tiles_per_row_per_region=1):
"""
Iterate through a grid of regions defined by a TileBB.
Args:
tile_bounds (GridBB):
tiles_per_row_per_region: Combine multiple tiles in one region.
E.g. if set to two, four tiles will be combined in one region.
... | python | {
"resource": ""
} |
q245810 | TileCoordinate.resolution | train | def resolution(self):
"""
Get the tile resolution at the current position.
The scale in WG84 depends on
* the zoom level (obviously)
* the latitude
* the tile size
References:
* http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Reso... | python | {
"resource": ""
} |
q245811 | RegionCoordinate.get_tiles | train | def get_tiles(self):
"""Get all TileCoordinates contained in the region"""
for x, y in griditer(self.root_tile.x, | python | {
"resource": ""
} |
q245812 | maps_json | train | def maps_json():
"""
Generates a json object which serves as bridge between
the web interface and the map source collection.
All attributes relevant for openlayers are converted into
JSON and served through this route.
Returns:
Response: All map sources as JSON object.
"""
map_... | python | {
"resource": ""
} |
q245813 | map_to_pdf | train | def map_to_pdf(map_source, zoom, x, y, width, height):
"""
Generate a PDF at the given position.
Args:
map_source (str): id of the map source to print.
zoom (int): zoom-level to print
x (float): Center of the Map in mercator projection (EPSG:4326), x-coordinate
y (float): Ce... | python | {
"resource": ""
} |
q245814 | kml_master | train | def kml_master():
"""KML master document for loading all maps in Google Earth""" | python | {
"resource": ""
} |
q245815 | kml_map_root | train | def kml_map_root(map_source):
"""KML for a given map"""
map = app.config["mapsources"][map_source] | python | {
"resource": ""
} |
q245816 | kml_region | train | def kml_region(map_source, z, x, y):
"""KML region fetched by a Google Earth network link. """
map = app.config["mapsources"][map_source] | python | {
"resource": ""
} |
q245817 | count_elements | train | def count_elements(doc):
"Counts the number of times each element is used in a document"
summary = {}
for el in doc.iter():
try:
namespace, element_name = re.search('^{(.+)}(.+)$', el.tag).groups()
except:
namespace = None
element_name = el.tag
if ... | python | {
"resource": ""
} |
q245818 | get_factory_object_name | train | def get_factory_object_name(namespace):
"Returns the correct factory object for a given namespace"
factory_map = {
'http://www.opengis.net/kml/2.2': 'KML',
'http://www.w3.org/2005/Atom': 'ATOM',
'http://www.google.com/kml/ext/2.2': 'GX'
}
if namespace:
if factory_map... | python | {
"resource": ""
} |
q245819 | kml_element_name | train | def kml_element_name(grid_coords, elem_id="KML"):
"""
Create a unique element name for KML
Args:
grid_coords (GridCoordinate):
elem_id (str):
>>> kml_element_name(GridCoordinate(zoom=5, x=42, | python | {
"resource": ""
} |
q245820 | URLFormatter.get_abs_url | train | def get_abs_url(self, rel_url):
"""
Create an absolute url from a relative one.
>>> url_formatter = URLFormatter("example.com", 80)
| python | {
"resource": ""
} |
q245821 | URLFormatter.get_map_url | train | def get_map_url(self, mapsource, grid_coords):
""" Get URL to a map region. """
return self.get_abs_url(
| python | {
"resource": ""
} |
q245822 | KMLMaster.add_maps | train | def add_maps(self, parent, root_path=""):
"""
Recursively add maps in a folder hierarchy.
Args:
parent (KMLElement): KMLElement to which we want to append child folders or maps respectively
root_path (str): path of 'parent'
"""
for mapsource in self.map_f... | python | {
"resource": ""
} |
q245823 | separate_namespace | train | def separate_namespace(qname):
"Separates the namespace from the element"
import re
try:
namespace, element_name = re.search('^{(.+)}(.+)$', qname).groups()
except: | python | {
"resource": ""
} |
q245824 | print_map | train | def print_map(map_source, x, y, zoom=14, width=297, height=210, dpi=300, format="pdf"):
"""
Download map tiles and stitch them together in a single image, ready for printing.
Args:
map_source (MapSource): Map to download
x (float): map center x-coordinate in Mercator projection (EPSG:4326)
... | python | {
"resource": ""
} |
q245825 | get_print_bbox | train | def get_print_bbox(x, y, zoom, width, height, dpi):
"""
Calculate the tile bounding box based on position, map size and resolution.
The function returns the next larger tile-box, that covers the specified
page size in mm.
Args:
x (float): map center x-coordinate in Mercator projection (EPS... | python | {
"resource": ""
} |
q245826 | download_tile | train | def download_tile(map_layer, zoom, x, y):
"""
Download a given tile from the tile server.
Args:
map_layer (MapLayer): MapLayer object which provides the tile-url.
zoom (int): zoom level
x (int): Tile-x-coordinate
y (int): Tile-y-coordinate
Returns:
file: tempora... | python | {
"resource": ""
} |
q245827 | get_tiles | train | def get_tiles(map_layer, bbox, n_workers=N_DOWNLOAD_WORKERS):
"""
Download tiles.
Args:
map_source (MapSource):
bbox (TileBB): Bounding box delimiting the map
n_workers (int): number of threads to used for downloading.
Returns:
dict of file: Dictionary mapping coordinat... | python | {
"resource": ""
} |
q245828 | stitch_map | train | def stitch_map(tiles, width, height, bbox, dpi):
"""
Merge tiles together into one image.
Args:
tiles (list of dict of file): tiles for each layer
width (float): page width in mm
height (height): page height in mm
dpi (dpi): resolution in dots per inch
Returns:
... | python | {
"resource": ""
} |
q245829 | add_scales_bar | train | def add_scales_bar(img, bbox):
"""
Add a scales bar to the map.
Calculates the resolution at the current latitude and
inserts the corresponding scales bar on the map.
Args:
img (Image): Image object to which the scales bar will be added.
bbox (TileBB): boundaries of the map
"... | python | {
"resource": ""
} |
q245830 | fromstring | train | def fromstring(text, schema=None):
"""Parses a KML text string
This function parses a KML text string and optionally validates it against
a provided schema object"""
if schema:
| python | {
"resource": ""
} |
q245831 | parse | train | def parse(fileobject, schema=None):
"""Parses a file object
This functon parses a KML file object, and optionally validates it against
a provided schema.
"""
if schema:
# with validation
parser = objectify.makeparser(schema = schema.schema, strip_cdata=False)
| python | {
"resource": ""
} |
q245832 | load_maps | train | def load_maps(maps_dir):
"""
Load all xml map sources from a given directory.
Args:
maps_dir: path to directory to search for maps
Returns:
dict of MapSource:
"""
maps_dir = os.path.abspath(maps_dir)
maps = {}
for root, dirnames, filenames in os.walk(maps_dir):
| python | {
"resource": ""
} |
q245833 | walk_mapsources | train | def walk_mapsources(mapsources, root=""):
"""
recursively walk through foldernames of mapsources.
Like os.walk, only for a list of mapsources.
Args:
mapsources (list of MapSource):
Yields:
(root, foldernames, maps)
>>> mapsources = load_maps("test/mapsources")
>>> pprint(... | python | {
"resource": ""
} |
q245834 | MapLayer.get_tile_url | train | def get_tile_url(self, zoom, x, y):
"""
Fill the placeholders of the tile url with zoom, x and y.
>>> ms = MapSource.from_xml("mapsources/osm.xml")
>>> ms.get_tile_url(42, 43, 44)
| python | {
"resource": ""
} |
q245835 | MapSource.min_zoom | train | def min_zoom(self):
"""
Get the minimal zoom level of all layers.
Returns:
int: the minimum of all zoom levels of all layers
Raises:
ValueError: if no layers exist
| python | {
"resource": ""
} |
q245836 | MapSource.max_zoom | train | def max_zoom(self):
"""
Get the maximal zoom level of all layers.
Returns:
int: the maximum of all zoom levels of all layers
Raises:
ValueError: if no layers exist
| python | {
"resource": ""
} |
q245837 | MapSource.parse_xml_boundary | train | def parse_xml_boundary(xml_region):
"""
Get the geographic bounds from an XML element
Args:
xml_region (Element): The <region> tag as XML Element
Returns:
GeographicBB:
"""
try:
bounds = {}
for boundary in xml_region.getch... | python | {
"resource": ""
} |
q245838 | MapSource.parse_xml_layers | train | def parse_xml_layers(xml_layers):
"""
Get the MapLayers from an XML element
Args:
xml_layers (Element): The <layers> tag as XML Element
Returns:
list of MapLayer:
""" | python | {
"resource": ""
} |
q245839 | MapSource.parse_xml_layer | train | def parse_xml_layer(xml_custom_map_source):
"""
Get one MapLayer from an XML element
Args:
xml_custom_map_source (Element): The <customMapSource> element tag wrapped
in a <layers> tag as XML Element
Returns:
MapLayer:
"""
map_laye... | python | {
"resource": ""
} |
q245840 | MapSource.from_xml | train | def from_xml(xml_path, mapsource_prefix=""):
"""
Create a MapSource object from a MOBAC
mapsource xml.
Args:
xml_path: path to the MOBAC mapsource xml file.
mapsource_prefix: root path of the mapsource folder.
Used to determine relative path within ... | python | {
"resource": ""
} |
q245841 | SingleLogoutMixin.get_saml_slos | train | def get_saml_slos(cls, logout_request):
"""returns saml logout ticket info"""
try:
root = etree.fromstring(logout_request)
return root.xpath(
"//samlp:SessionIndex",
| python | {
"resource": ""
} |
q245842 | SingleLogoutMixin.verify_logout_request | train | def verify_logout_request(cls, logout_request, ticket):
"""verifies the single logout request came from the CAS server
returns True if the logout_request is valid, False otherwise
"""
try:
session_index = cls.get_saml_slos(logout_request)
| python | {
"resource": ""
} |
q245843 | CASClientWithSAMLV1.verify_ticket | train | def verify_ticket(self, ticket, **kwargs):
"""Verifies CAS 3.0+ XML-based authentication ticket and returns extended attributes.
@date: 2011-11-30
@author: Carlos Gonzalez Vila <carlewis@gmail.com>
Returns username and attributes on success and None,None on failure.
"""
... | python | {
"resource": ""
} |
q245844 | ConditionSet.get_field_value | train | def get_field_value(self, instance, field_name):
"""
Given an instance, and the name of an attribute, returns the value
of that attribute on the instance.
Default behavior will map the ``percent`` attribute to ``id``.
"""
# XXX: can we come up w/ a better API?
| python | {
"resource": ""
} |
q245845 | ConditionSet.has_active_condition | train | def has_active_condition(self, conditions, instances):
"""
Given a list of instances, and the conditions active for
this switch, returns a boolean reprsenting if any
conditional is met, including a non-instance default.
"""
return_value = None
for instance in iter... | python | {
"resource": ""
} |
q245846 | ConditionSet.is_active | train | def is_active(self, instance, conditions):
"""
Given an instance, and the conditions active for this switch, returns
a boolean representing if the feature is active.
"""
return_value = None
for name, field in self.fields.iteritems():
field_conditions = conditi... | python | {
"resource": ""
} |
q245847 | json | train | def json(func):
"Decorator to make JSON views simpler"
def wrapper(self, request, *args, **kwargs):
try:
response = {
"success": True,
"data": func(self, request, *args, **kwargs)
}
except GargoyleException, exc:
response = {
... | python | {
"resource": ""
} |
q245848 | UserConditionSet.is_active | train | def is_active(self, instance, conditions):
"""
value is the current value of the switch
instance is the instance of our type
"""
if isinstance(instance, User):
| python | {
"resource": ""
} |
q245849 | autodiscover | train | def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want.
"""
import copy
from django.conf import settings
from django.utils.importlib import import_module
for app... | python | {
"resource": ""
} |
q245850 | Switch.add_condition | train | def add_condition(self, manager, condition_set, field_name, condition, exclude=False, commit=True):
"""
Adds a new condition and registers it in the global ``gargoyle`` switch manager.
If ``commit`` is ``False``, the data will not be written to the database.
>>> switch = gargoyle['my_s... | python | {
"resource": ""
} |
q245851 | Switch.clear_conditions | train | def clear_conditions(self, manager, condition_set, field_name=None, commit=True):
"""
Clears conditions given a set of parameters.
If ``commit`` is ``False``, the data will not be written to the database.
Clear all conditions given a ConditionSet, and a field name:
>>> switch ... | python | {
"resource": ""
} |
q245852 | FacetFactory.add_term_facet | train | def add_term_facet(self, *args, **kwargs):
"""Add a term factory facet"""
| python | {
"resource": ""
} |
q245853 | FacetFactory.add_date_facet | train | def add_date_facet(self, *args, **kwargs):
"""Add a date factory facet"""
| python | {
"resource": ""
} |
q245854 | FacetFactory.add_geo_facet | train | def add_geo_facet(self, *args, **kwargs):
"""Add a geo factory facet"""
| python | {
"resource": ""
} |
q245855 | symbol_by_name | train | def symbol_by_name(name, aliases={}, imp=None, package=None,
sep='.', default=None, **kwargs):
"""Get symbol by qualified name.
The name should be the full dot-separated path to the class::
modulename.ClassName
Example::
celery.concurrency.processes.TaskPool
... | python | {
"resource": ""
} |
q245856 | import_from_cwd | train | def import_from_cwd(module, imp=None, package=None):
"""Import module, but make sure it finds modules
located in the current directory.
Modules located in the current directory has
precedence over modules located in `sys.path`.
| python | {
"resource": ""
} |
q245857 | file_to_attachment | train | def file_to_attachment(filename, filehandler=None):
"""
Convert a file to attachment
"""
if filehandler:
return {'_name': filename,
| python | {
"resource": ""
} |
q245858 | ESJsonDecoder.string_to_datetime | train | def string_to_datetime(self, obj):
"""
Decode a datetime string to a datetime object
"""
if isinstance(obj, six.string_types) and len(obj) == 19:
try:
return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S")
except ValueError:
pass
... | python | {
"resource": ""
} |
q245859 | ESJsonDecoder.dict_to_object | train | def dict_to_object(self, d):
"""
Decode datetime value from string to datetime
"""
for k, v in list(d.items()):
if isinstance(v, six.string_types) and len(v) == 19:
# Decode a datetime string to a datetime object
try:
d[k] =... | python | {
"resource": ""
} |
q245860 | ES._check_servers | train | def _check_servers(self):
"""Check the servers variable and convert in a valid tuple form"""
new_servers = []
def check_format(server):
if server.scheme not in ["thrift", "http", "https"]:
raise RuntimeError("Unable to recognize protocol: \"%s\"" % _type)
... | python | {
"resource": ""
} |
q245861 | ES._init_connection | train | def _init_connection(self):
"""
Create initial connection pool
"""
#detect connectiontype
if not self.servers:
raise RuntimeError("No server defined")
server = random.choice(self.servers)
if server.scheme in ["http", "https"]:
self.connect... | python | {
"resource": ""
} |
q245862 | ES._discovery | train | def _discovery(self):
"""
Find other servers asking nodes to given server
"""
data = self.cluster_nodes()
self.cluster_name = data["cluster_name"]
for _, nodedata in list(data["nodes"].items()):
| python | {
"resource": ""
} |
q245863 | ES._set_bulk_size | train | def _set_bulk_size(self, bulk_size):
"""
Set the bulk size
:param bulk_size the bulker size
"""
| python | {
"resource": ""
} |
q245864 | ES._set_raise_on_bulk_item_failure | train | def _set_raise_on_bulk_item_failure(self, raise_on_bulk_item_failure):
"""
Set the raise_on_bulk_item_failure parameter
:param raise_on_bulk_item_failure a bool the status of the raise_on_bulk_item_failure
"""
| python | {
"resource": ""
} |
q245865 | ES._validate_indices | train | def _validate_indices(self, indices=None):
"""Return a valid list of indices.
`indices` may be a string or a list of strings.
If `indices` is not supplied, returns the default_indices.
"""
if indices is None:
| python | {
"resource": ""
} |
q245866 | ES.validate_types | train | def validate_types(self, types=None):
"""Return a valid list of types.
`types` may be a string or a list of strings.
If `types` is not supplied, returns the default_types.
"""
types = types or self.default_types
if | python | {
"resource": ""
} |
q245867 | ES.create_bulker | train | def create_bulker(self):
"""
Create a bulker object and return it to allow to manage custom bulk policies
"""
return | python | {
"resource": ""
} |
q245868 | ES.ensure_index | train | def ensure_index(self, index, mappings=None, settings=None, clear=False):
"""
Ensure if an index with mapping exists
"""
mappings = mappings or []
if isinstance(mappings, dict):
mappings = [mappings]
exists = self.indices.exists_index(index)
if exists ... | python | {
"resource": ""
} |
q245869 | ES.collect_info | train | def collect_info(self):
"""
Collect info about the connection and fill the info dictionary.
"""
try:
info = {}
res = self._send_request('GET', "/")
info['server'] = {}
info['server']['name'] = res['name']
info['server']['version... | python | {
"resource": ""
} |
q245870 | ES.index_raw_bulk | train | def index_raw_bulk(self, header, document):
"""
Function helper for fast inserting
:param header: a string with the bulk header must be ended with a newline
:param document: a | python | {
"resource": ""
} |
q245871 | ES.index | train | def index(self, doc, index, doc_type, id=None, parent=None, force_insert=False,
op_type=None, bulk=False, version=None, querystring_args=None, ttl=None):
"""
Index a typed JSON document into a specific index and make it searchable.
"""
if querystring_args is None:
... | python | {
"resource": ""
} |
q245872 | ES.put_file | train | def put_file(self, filename, index, doc_type, id=None, name=None):
"""
Store a file in a index
"""
if id is None:
request_method = 'POST'
else:
request_method = 'PUT'
path = | python | {
"resource": ""
} |
q245873 | ES.get_file | train | def get_file(self, index, doc_type, id=None):
"""
Return the filename and memory data stream
"""
| python | {
"resource": ""
} |
q245874 | ES.update_by_function | train | def update_by_function(self, extra_doc, index, doc_type, id, querystring_args=None,
update_func=None, attempts=2):
"""
Update an already indexed typed JSON document.
The update happens client-side, i.e. the current document is retrieved,
updated locally and fi... | python | {
"resource": ""
} |
q245875 | ES.partial_update | train | def partial_update(self, index, doc_type, id, doc=None, script=None, params=None,
upsert=None, querystring_args=None):
"""
Partially update a document with a script
"""
if querystring_args is None:
querystring_args = {}
if doc is None and scrip... | python | {
"resource": ""
} |
q245876 | ES.delete | train | def delete(self, index, doc_type, id, bulk=False, **query_params):
"""
Delete a typed JSON document from a specific index based on its id.
If bulk is True, the delete operation is put in bulk mode.
"""
if bulk:
cmd = {"delete": {"_index": index, "_type": doc_type,
... | python | {
"resource": ""
} |
q245877 | ES.delete_by_query | train | def delete_by_query(self, indices, doc_types, query, **query_params):
"""
Delete documents from one or more indices and one or more types based | python | {
"resource": ""
} |
q245878 | ES.exists | train | def exists(self, index, doc_type, id, **query_params):
"""
Return if a document exists
"""
| python | {
"resource": ""
} |
q245879 | ES.get | train | def get(self, index, doc_type, id, fields=None, model=None, **query_params):
"""
Get a typed JSON document from an index based on its id.
"""
path = make_path(index, doc_type, id)
if fields is not None:
| python | {
"resource": ""
} |
q245880 | ES.factory_object | train | def factory_object(self, index, doc_type, data=None, id=None):
"""
Create a stub object to be manipulated
"""
data = data or {}
obj = self.model()
obj._meta.index = index
obj._meta.type = doc_type
| python | {
"resource": ""
} |
q245881 | ES.mget | train | def mget(self, ids, index=None, doc_type=None, **query_params):
"""
Get multi JSON documents.
ids can be:
list of tuple: (index, type, id)
list of ids: index and doc_type are required
"""
if not ids:
return []
body = []
for va... | python | {
"resource": ""
} |
q245882 | ES.search_raw | train | def search_raw(self, query, indices=None, doc_types=None, headers=None, **query_params):
"""Execute a search against one or more indices to get the search hits.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to be passed
... | python | {
"resource": ""
} |
q245883 | ES.search | train | def search(self, query, indices=None, doc_types=None, model=None, scan=False, headers=None, **query_params):
"""Execute a search against one or more indices to get the resultset.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to ... | python | {
"resource": ""
} |
q245884 | ES.suggest | train | def suggest(self, name, text, field, type='term', size=None, params=None,
**kwargs):
"""
Execute suggester of given type.
:param name: name for the suggester
:param text: text to search for
:param field: field to search
| python | {
"resource": ""
} |
q245885 | ES.count | train | def count(self, query=None, indices=None, doc_types=None, **query_params):
"""
Execute a query against one or more indices and get hits count.
"""
from .query import MatchAllQuery
if query is None:
query = MatchAllQuery()
| python | {
"resource": ""
} |
q245886 | ES.create_river | train | def create_river(self, river, river_name=None):
"""
Create a river
"""
if isinstance(river, River):
body = river.serialize()
river_name = river.name
| python | {
"resource": ""
} |
q245887 | ES.delete_river | train | def delete_river(self, river, river_name=None):
"""
Delete a river
"""
if isinstance(river, River):
| python | {
"resource": ""
} |
q245888 | ES.morelikethis | train | def morelikethis(self, index, doc_type, id, fields, **query_params):
"""
Execute a "more like this" search query against one or more fields and get back search hits.
"""
path = make_path(index, doc_type, id, '_mlt')
query_params['mlt_fields'] = ','.join(fields)
| python | {
"resource": ""
} |
q245889 | ES.create_percolator | train | def create_percolator(self, index, name, query, **kwargs):
"""
Create a percolator document
Any kwargs will be added to the document as extra properties.
"""
if isinstance(query, Query):
query = {"query": query.serialize()}
if not isinstance(query, dict):
... | python | {
"resource": ""
} |
q245890 | ES.percolate | train | def percolate(self, index, doc_types, query):
"""
Match a query with a document
"""
if doc_types is None:
raise RuntimeError('percolate() must be supplied with at least one doc_type')
| python | {
"resource": ""
} |
q245891 | ResultSet.fix_facets | train | def fix_facets(self):
"""
This function convert date_histogram facets to datetime
"""
facets = self.facets
for key in list(facets.keys()):
_type = facets[key].get("_type", "unknown")
if _type == "date_histogram":
for entry in facets[key].ge... | python | {
"resource": ""
} |
q245892 | ResultSet.fix_aggs | train | def fix_aggs(self):
"""
This function convert date_histogram aggs to datetime
"""
aggs = self.aggs
for key in list(aggs.keys()):
_type = aggs[key].get("_type", "unknown")
if _type == "date_histogram":
for entry in aggs[key].get("entries", [... | python | {
"resource": ""
} |
q245893 | ResultSet.fix_keys | train | def fix_keys(self):
"""
Remove the _ from the keys of the results
"""
if not self.valid:
return
for hit in self._results['hits']['hits']:
for key, item in list(hit.items()):
| python | {
"resource": ""
} |
q245894 | ResultSet.clean_highlight | train | def clean_highlight(self):
"""
Remove the empty highlight
"""
if not self.valid:
return
for hit in self._results['hits']['hits']:
if 'highlight' in hit:
hl = hit['highlight'] | python | {
"resource": ""
} |
q245895 | HighLighter.add_field | train | def add_field(self, name, fragment_size=150, number_of_fragments=3, fragment_offset=None, order="score", type=None):
"""
Add a field to Highlinghter
"""
data = {}
if fragment_size:
data['fragment_size'] = fragment_size
if number_of_fragments is not None:
... | python | {
"resource": ""
} |
q245896 | QuerySet.iterator | train | def iterator(self):
"""
An iterator over the results from applying this QuerySet to the
| python | {
"resource": ""
} |
q245897 | QuerySet.in_bulk | train | def in_bulk(self, id_list):
"""
Returns a dictionary mapping each of the given IDs to the object with
that ID.
"""
if not id_list:
return {}
qs = self._clone()
| python | {
"resource": ""
} |
q245898 | QuerySet.complex_filter | train | def complex_filter(self, filter_obj):
"""
Returns a new QuerySet instance with filter_obj added to the filters.
filter_obj can be a Q object (or anything with an add_to_query()
method) or a dictionary of keyword lookup arguments.
This exists to support framework features such a... | python | {
"resource": ""
} |
q245899 | QuerySet.reverse | train | def reverse(self):
"""
Reverses the ordering of the QuerySet.
"""
clone = self._clone()
assert self._ordering, "You need to set an ordering for reverse"
ordering = []
for order in self._ordering:
for k,v in order.items():
if v=="asc":
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.