sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def get_private_room_history(self, room_id, oldest=None, **kwargs):
"""
Get various history of specific private group in this case private
:param room_id:
:param kwargs:
:return:
"""
return GetPrivateRoomHistory(settings=self.settings, **kwargs).call(
... | Get various history of specific private group in this case private
:param room_id:
:param kwargs:
:return: | entailment |
def get_public_rooms(self, **kwargs):
"""
Get a listing of all public rooms with their names and IDs
"""
return GetPublicRooms(settings=self.settings, **kwargs).call(**kwargs) | Get a listing of all public rooms with their names and IDs | entailment |
def get_room_info(self, room_id, **kwargs):
"""
Get various information about a specific channel/room
:param room_id:
:param kwargs:
:return:
"""
return GetRoomInfo(settings=self.settings, **kwargs).call(
room_id=room_id,
**kwargs
... | Get various information about a specific channel/room
:param room_id:
:param kwargs:
:return: | entailment |
def upload_file(self, room_id, description, file, message, **kwargs):
"""
Upload file to room
:param room_id:
:param description:
:param file:
:param kwargs:
:return:
"""
return UploadFile(settings=self.settings, **kwargs).call(
room_id... | Upload file to room
:param room_id:
:param description:
:param file:
:param kwargs:
:return: | entailment |
def get_private_room_info(self, room_id, **kwargs):
"""
Get various information about a specific private group
:param room_id:
:param kwargs:
:return:
"""
return GetPrivateRoomInfo(settings=self.settings, **kwargs).call(
room_id=room_id,
*... | Get various information about a specific private group
:param room_id:
:param kwargs:
:return: | entailment |
def get_room_id(self, room_name, **kwargs):
"""
Get room ID
:param room_name:
:param kwargs:
:return:
"""
return GetRoomId(settings=self.settings, **kwargs).call(
room_name=room_name,
**kwargs
) | Get room ID
:param room_name:
:param kwargs:
:return: | entailment |
def get_room_history(
self,
room_id,
oldest=None,
latest=datetime.now(),
inclusive=False,
count=20,
unreads=False,
**kwa... | Get various history of specific channel/room
:param room_id:
:param kwargs:
:return: | entailment |
def create_public_room(self, name, **kwargs):
"""
Create room with given name
:param name: Room name
:param kwargs:
members: The users to add to the channel when it is created.
Optional; Ex.: ["rocket.cat"], Default: []
read_only: Set if the channel is read on... | Create room with given name
:param name: Room name
:param kwargs:
members: The users to add to the channel when it is created.
Optional; Ex.: ["rocket.cat"], Default: []
read_only: Set if the channel is read only or not.
Optional; Ex.: True, Default: False
... | entailment |
def delete_public_room(self, room_id, **kwargs):
"""
Delete room with given ID
:param room_id: Room ID
:param kwargs:
:return:
"""
return DeletePublicRoom(settings=self.settings, **kwargs).call(room_id=room_id, **kwargs) | Delete room with given ID
:param room_id: Room ID
:param kwargs:
:return: | entailment |
def get_users(self, **kwargs):
"""
Gets all of the users in the system and their information
:param kwargs:
:return:
"""
return GetUsers(settings=self.settings, **kwargs).call(**kwargs) | Gets all of the users in the system and their information
:param kwargs:
:return: | entailment |
def get_user_info(self, user_id, **kwargs):
"""
Retrieves information about a user,
the result is only limited to what the callee has access to view.
:param user_id:
:param kwargs:
:return:
"""
return GetUserInfo(settings=self.settings, **kwargs).call(
... | Retrieves information about a user,
the result is only limited to what the callee has access to view.
:param user_id:
:param kwargs:
:return: | entailment |
def create_user(self, email, name, password, username, **kwargs):
"""
Create user
:param email: E-mail
:param name: Full name
:param password: Password
:param username: Username
:param kwargs:
active:
roles:
join_default_channels:
r... | Create user
:param email: E-mail
:param name: Full name
:param password: Password
:param username: Username
:param kwargs:
active:
roles:
join_default_channels:
require_password_change:
send_welcome_email:
verified:
custom_f... | entailment |
def delete_user(self, user_id, **kwargs):
"""
Delete user
:param user_id: User ID
:param kwargs:
:return:
"""
return DeleteUser(settings=self.settings, **kwargs).call(user_id=user_id, **kwargs) | Delete user
:param user_id: User ID
:param kwargs:
:return: | entailment |
def get_index(cls, model, via_class=False):
'''
Returns the index name (as a string) for the given model as a class or a string.
:param model: model name or model class if via_class set to True.
:param via_class: set to True if parameter model is a class.
:raise KeyError: If the ... | Returns the index name (as a string) for the given model as a class or a string.
:param model: model name or model class if via_class set to True.
:param via_class: set to True if parameter model is a class.
:raise KeyError: If the provided model does not have any index associated. | entailment |
def get_model_index(cls, model, default=True):
'''
Returns the default model index for the given model, or the list of indices if default is False.
:param model: model name as a string.
:raise KeyError: If the provided model does not have any index associated.
'''
try:
... | Returns the default model index for the given model, or the list of indices if default is False.
:param model: model name as a string.
:raise KeyError: If the provided model does not have any index associated. | entailment |
def get_models(cls, index, as_class=False):
'''
Returns the list of models defined for this index.
:param index: index name.
:param as_class: set to True to return the model as a model object instead of as a string.
'''
try:
return cls._index_to_model[index] i... | Returns the list of models defined for this index.
:param index: index name.
:param as_class: set to True to return the model as a model object instead of as a string. | entailment |
def get_model_indices(cls, index):
'''
Returns the list of model indices (i.e. ModelIndex objects) defined for this index.
:param index: index name.
'''
try:
return cls._idx_name_to_mdl_to_mdlidx[index].values()
except KeyError:
raise KeyError('Cou... | Returns the list of model indices (i.e. ModelIndex objects) defined for this index.
:param index: index name. | entailment |
def map_raw_results(cls, raw_results, instance=None):
'''
Maps raw results to database model objects.
:param raw_results: list raw results as returned from elasticsearch-dsl-py.
:param instance: Bungiesearch instance if you want to make use of `.only()` or `optmize_queries` as defined in... | Maps raw results to database model objects.
:param raw_results: list raw results as returned from elasticsearch-dsl-py.
:param instance: Bungiesearch instance if you want to make use of `.only()` or `optmize_queries` as defined in the ModelIndex.
:return: list of mapped results in the *same* ord... | entailment |
def _clone(self):
'''
Must clone additional fields to those cloned by elasticsearch-dsl-py.
'''
instance = super(Bungiesearch, self)._clone()
instance._raw_results_only = self._raw_results_only
return instance | Must clone additional fields to those cloned by elasticsearch-dsl-py. | entailment |
def execute(self, return_results=True):
'''
Executes the query and attempts to create model objects from results.
'''
if self.results:
return self.results if return_results else None
self.execute_raw()
if self._raw_results_only:
self.results = se... | Executes the query and attempts to create model objects from results. | entailment |
def only(self, *fields):
'''
Restricts the fields to be fetched when mapping. Set to `__model` to fetch all fields define in the ModelIndex.
'''
s = self._clone()
if len(fields) == 1 and fields[0] == '__model':
s._only = '__model'
else:
s._only = f... | Restricts the fields to be fetched when mapping. Set to `__model` to fetch all fields define in the ModelIndex. | entailment |
def hook_alias(self, alias, model_obj=None):
'''
Returns the alias function, if it exists and if it can be applied to this model.
'''
try:
search_alias = self._alias_hooks[alias]
except KeyError:
raise AttributeError('Could not find search alias named {}. ... | Returns the alias function, if it exists and if it can be applied to this model. | entailment |
def custom_search(self, index, doc_type):
'''
Performs a search on a custom elasticsearch index and mapping. Will not attempt to map result objects.
'''
from bungiesearch import Bungiesearch
return Bungiesearch(raw_results=True).index(index).doc_type(doc_type) | Performs a search on a custom elasticsearch index and mapping. Will not attempt to map result objects. | entailment |
def contribute_to_class(self, cls, name):
'''
Sets up the signal processor. Since self.model is not available
in the constructor, we perform this operation here.
'''
super(BungiesearchManager, self).contribute_to_class(cls, name)
from . import Bungiesearch
from .... | Sets up the signal processor. Since self.model is not available
in the constructor, we perform this operation here. | entailment |
def django_field_to_index(field, **attr):
'''
Returns the index field type that would likely be associated with each Django type.
'''
dj_type = field.get_internal_type()
if dj_type in ('DateField', 'DateTimeField'):
return DateField(**attr)
elif dj_type in ('BooleanField', 'NullBoolean... | Returns the index field type that would likely be associated with each Django type. | entailment |
def value(self, obj):
'''
Computes the value of this field to update the index.
:param obj: object instance, as a dictionary or as a model instance.
'''
if self.template_name:
t = loader.select_template([self.template_name])
return t.render(Context({'objec... | Computes the value of this field to update the index.
:param obj: object instance, as a dictionary or as a model instance. | entailment |
def split_command(cmd, posix=None):
'''
- cmd is string list -> nothing to do
- cmd is string -> split it using shlex
:param cmd: string ('ls -l') or list of strings (['ls','-l'])
:rtype: string list
'''
if not isinstance(cmd, string_types):
# cmd is string list
pass
e... | - cmd is string list -> nothing to do
- cmd is string -> split it using shlex
:param cmd: string ('ls -l') or list of strings (['ls','-l'])
:rtype: string list | entailment |
def get_mapping(self, meta_fields=True):
'''
Returns the mapping for the index as a dictionary.
:param meta_fields: Also include elasticsearch meta fields in the dictionary.
:return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype.
'''... | Returns the mapping for the index as a dictionary.
:param meta_fields: Also include elasticsearch meta fields in the dictionary.
:return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype. | entailment |
def collect_analysis(self):
'''
:return: a dictionary which is used to get the serialized analyzer definition from the analyzer class.
'''
analysis = {}
for field in self.fields.values():
for analyzer_name in ('analyzer', 'index_analyzer', 'search_analyzer'):
... | :return: a dictionary which is used to get the serialized analyzer definition from the analyzer class. | entailment |
def serialize_object(self, obj, obj_pk=None):
'''
Serializes an object for it to be added to the index.
:param obj: Object to be serialized. Optional if obj_pk is passed.
:param obj_pk: Object primary key. Superseded by `obj` if available.
:return: A dictionary representing the ... | Serializes an object for it to be added to the index.
:param obj: Object to be serialized. Optional if obj_pk is passed.
:param obj_pk: Object primary key. Superseded by `obj` if available.
:return: A dictionary representing the object as defined in the mapping. | entailment |
def _get_fields(self, fields, excludes, hotfixes):
'''
Given any explicit fields to include and fields to exclude, add
additional fields based on the associated model. If the field needs a hotfix, apply it.
'''
final_fields = {}
fields = fields or []
excludes = ex... | Given any explicit fields to include and fields to exclude, add
additional fields based on the associated model. If the field needs a hotfix, apply it. | entailment |
def validate_items(self):
""" Validates the items in the backing array, including
performing type validation.
Sets the _typed property and clears the dirty flag as a side effect
Returns:
The typed array
"""
logger.debug(fmt("Validating {}", self))
fr... | Validates the items in the backing array, including
performing type validation.
Sets the _typed property and clears the dirty flag as a side effect
Returns:
The typed array | entailment |
def create(name, item_constraint=None, **addl_constraints):
""" Create an array validator based on the passed in constraints.
If item_constraint is a tuple, it is assumed that tuple validation
is being performed. If it is a class or dictionary, list validation
will be performed. Classes... | Create an array validator based on the passed in constraints.
If item_constraint is a tuple, it is assumed that tuple validation
is being performed. If it is a class or dictionary, list validation
will be performed. Classes are assumed to be subclasses of ProtocolBase,
while dictionarie... | entailment |
def extendMarkdown(self, md, md_globals):
""" Add FencedBlockPreprocessor to the Markdown instance. """
md.registerExtension(self)
md.preprocessors.add('fenced_code_block',
SpecialFencePreprocessor(md),
">normalize_whitespace") | Add FencedBlockPreprocessor to the Markdown instance. | entailment |
def parse_requirements(path):
"""Rudimentary parser for the `requirements.txt` file
We just want to separate regular packages from links to pass them to the
`install_requires` and `dependency_links` params of the `setup()`
function properly.
"""
try:
print(os.path.join(os.path.dirname(_... | Rudimentary parser for the `requirements.txt` file
We just want to separate regular packages from links to pass them to the
`install_requires` and `dependency_links` params of the `setup()`
function properly. | entailment |
def propmerge(into, data_from):
""" Merge JSON schema requirements into a dictionary """
newprops = copy.deepcopy(into)
for prop, propval in six.iteritems(data_from):
if prop not in newprops:
newprops[prop] = propval
continue
new_sp = newprops[prop]
for subp... | Merge JSON schema requirements into a dictionary | entailment |
def as_dict(self):
""" Return a dictionary containing the current values
of the object.
Returns:
(dict): The object represented as a dictionary
"""
out = {}
for prop in self:
propval = getattr(self, prop)
if hasattr(propval, 'for_json... | Return a dictionary containing the current values
of the object.
Returns:
(dict): The object represented as a dictionary | entailment |
def from_json(cls, jsonmsg):
""" Create an object directly from a JSON string.
Applies general validation after creating the
object to check whether all required fields are
present.
Args:
jsonmsg (str): An object encoded as a JSON string
Returns:
... | Create an object directly from a JSON string.
Applies general validation after creating the
object to check whether all required fields are
present.
Args:
jsonmsg (str): An object encoded as a JSON string
Returns:
An object of the generated type
... | entailment |
def validate(self):
""" Applies all defined validation to the current
state of the object, and raises an error if
they are not all met.
Raises:
ValidationError: if validations do not pass
"""
missing = self.missing_property_names()
if len(missing) >... | Applies all defined validation to the current
state of the object, and raises an error if
they are not all met.
Raises:
ValidationError: if validations do not pass | entailment |
def missing_property_names(self):
"""
Returns a list of properties which are required and missing.
Properties are excluded from this list if they are allowed to be null.
:return: list of missing properties.
"""
propname = lambda x: self.__prop_names__[x]
missin... | Returns a list of properties which are required and missing.
Properties are excluded from this list if they are allowed to be null.
:return: list of missing properties. | entailment |
def construct(self, uri, *args, **kw):
""" Wrapper to debug things """
logger.debug(util.lazy_format("Constructing {0}", uri))
if ('override' not in kw or kw['override'] is False) \
and uri in self.resolved:
logger.debug(util.lazy_format("Using existing {0}", uri))
... | Wrapper to debug things | entailment |
def _build_literal(self, nm, clsdata):
"""@todo: Docstring for _build_literal
:nm: @todo
:clsdata: @todo
:returns: @todo
"""
cls = type(str(nm), tuple((LiteralValue,)), {
'__propinfo__': {
'__literal__': clsdata,
'__title__': clsdata.get('title'),
... | @todo: Docstring for _build_literal
:nm: @todo
:clsdata: @todo
:returns: @todo | entailment |
def _build_object(self, nm, clsdata, parents,**kw):
logger.debug(util.lazy_format("Building object {0}", nm))
# To support circular references, we tag objects that we're
# currently building as "under construction"
self.under_construction.add(nm)
props = {}
defaults = s... | If this object itself has a 'oneOf' designation, then
make the validation 'type' the list of potential objects. | entailment |
def build_classes(self,strict=False, named_only=False, standardize_names=True):
"""
Build all of the classes named in the JSONSchema.
Class names will be transformed using inflection by default, so names
with spaces in the schema will be camelcased, while names without
spaces wi... | Build all of the classes named in the JSONSchema.
Class names will be transformed using inflection by default, so names
with spaces in the schema will be camelcased, while names without
spaces will have internal capitalization dropped. Thus "Home Address"
becomes "HomeAddress", while "H... | entailment |
def _interp(self, data):
"""The interpolation method implemented here is a kind of a billinear
interpolation. The input *data* field is first interpolated along the
rows and subsequently along its columns.
The final size of the interpolated *data* field is determined by the
la... | The interpolation method implemented here is a kind of a billinear
interpolation. The input *data* field is first interpolated along the
rows and subsequently along its columns.
The final size of the interpolated *data* field is determined by the
last indices in self.row_indices and s... | entailment |
def _interp_axis(self, data, axis):
"""The *data* field contains the data to be interpolated. It is
expected that values reach out to the *data* boundaries.
With *axis*=0 this method interpolates along rows and *axis*=1 it
interpolates along colums.
For column mode the *data* in... | The *data* field contains the data to be interpolated. It is
expected that values reach out to the *data* boundaries.
With *axis*=0 this method interpolates along rows and *axis*=1 it
interpolates along colums.
For column mode the *data* input is transposed before interpolation
... | entailment |
def _pandas_interp(self, data, indices):
"""The actual transformation based on the following stackoverflow
entry: http://stackoverflow.com/a/10465162
"""
new_index = np.arange(indices[-1] + 1)
data_frame = DataFrame(data, index=indices)
data_frame_reindexed = data_frame... | The actual transformation based on the following stackoverflow
entry: http://stackoverflow.com/a/10465162 | entailment |
def interpolate(self):
"""Do the interpolation and return resulting longitudes and latitudes.
"""
self.latitude = self._interp(self.lat_tiepoint)
self.longitude = self._interp(self.lon_tiepoint)
return self.latitude, self.longitude | Do the interpolation and return resulting longitudes and latitudes. | entailment |
def _execute(self, query, model, adapter, raw=False):
"""
We have to override this because in some situation
(such as with Filebackend, or any dummy backend)
we have to parse / adapt results *before* when can execute the query
"""
values = self.load(model, adapter)
... | We have to override this because in some situation
(such as with Filebackend, or any dummy backend)
we have to parse / adapt results *before* when can execute the query | entailment |
def get(self, key, default=None, reraise=False):
"""
Get the given key from the cache, if present.
A default value can be provided in case the requested key is not present,
otherwise, None will be returned.
:param key: the key to query
:type key: str
:param defau... | Get the given key from the cache, if present.
A default value can be provided in case the requested key is not present,
otherwise, None will be returned.
:param key: the key to query
:type key: str
:param default: the value to return if the key does not exist in cache
:p... | entailment |
def set(self, key, value, timeout=NotSet):
"""
Set the given key to the given value in the cache.
A timeout may be provided, otherwise, the :py:attr:`Cache.default_timeout`
will be used.
:param key: the key to which the value will be bound
:type key: str
:param v... | Set the given key to the given value in the cache.
A timeout may be provided, otherwise, the :py:attr:`Cache.default_timeout`
will be used.
:param key: the key to which the value will be bound
:type key: str
:param value: the value to store in the cache
:param timeout: t... | entailment |
def resolve_attr(obj, name):
"""A custom attrgetter that operates both on dictionaries and objects"""
# TODO: setup some hinting, so we can go directly to the correct
# Maybe it's a dict ? Let's try dict lookup, it's the fastest
try:
return obj[name]
except TypeError:
pass
except... | A custom attrgetter that operates both on dictionaries and objects | entailment |
def unique_everseen(seq):
"""Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order | entailment |
def hints(self, **kwargs):
"""
Use this method to update hints value of the underlying query
example: queryset.hints(permissive=False)
"""
new_query = self.query.clone()
new_query.hints.update(kwargs)
return self._clone(query=new_query) | Use this method to update hints value of the underlying query
example: queryset.hints(permissive=False) | entailment |
def build_filter_from_kwargs(self, **kwargs):
"""Convert django-s like lookup to SQLAlchemy ones"""
query = None
for path_to_convert, value in kwargs.items():
path_parts = path_to_convert.split('__')
lookup_class = None
try:
# We check if the ... | Convert django-s like lookup to SQLAlchemy ones | entailment |
def locally(self):
"""
Will execute the current queryset and pass it to the python backend
so user can run query on the local dataset (instead of contacting the store)
"""
from .backends import python
from . import models
store = python.IterableStore(values=self... | Will execute the current queryset and pass it to the python backend
so user can run query on the local dataset (instead of contacting the store) | entailment |
def get_scene_splits(nlines_swath, nlines_scan, n_cpus):
"""Calculate the line numbers where the swath will be split in smaller
granules for parallel processing"""
nscans = nlines_swath // nlines_scan
if nscans < n_cpus:
nscans_subscene = 1
else:
nscans_subscene = nscans // n_cpus
... | Calculate the line numbers where the swath will be split in smaller
granules for parallel processing | entailment |
def metop20kmto1km(lons20km, lats20km):
"""Getting 1km geolocation for metop avhrr from 20km tiepoints.
"""
cols20km = np.array([0] + list(range(4, 2048, 20)) + [2047])
cols1km = np.arange(2048)
lines = lons20km.shape[0]
rows20km = np.arange(lines)
rows1km = np.arange(lines)
along_track... | Getting 1km geolocation for metop avhrr from 20km tiepoints. | entailment |
def modis5kmto1km(lons5km, lats5km):
"""Getting 1km geolocation for modis from 5km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
"""
cols5km = np.arange(2, 1354, 5) / 5.0
cols1km = np.arange(1354) / 5.0
lines = lons5km.shape[0] * 5
rows5km = np.arange(2, lines, 5) /... | Getting 1km geolocation for modis from 5km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation | entailment |
def _multi(fun, lons, lats, chunk_size, cores=1):
"""Work on multiple cores.
"""
pool = Pool(processes=cores)
splits = get_scene_splits(lons.shape[0], chunk_size, cores)
lons_parts = np.vsplit(lons, splits)
lats_parts = np.vsplit(lats, splits)
results = [pool.apply_async(fun,
... | Work on multiple cores. | entailment |
def modis1kmto500m(lons1km, lats1km, cores=1):
"""Getting 500m geolocation for modis from 1km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
"""
if cores > 1:
return _multi(modis1kmto500m, lons1km, lats1km, 10, cores)
cols1km = np.arange(1354)
cols500m = np.aran... | Getting 500m geolocation for modis from 1km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation | entailment |
def modis1kmto250m(lons1km, lats1km, cores=1):
"""Getting 250m geolocation for modis from 1km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
"""
if cores > 1:
return _multi(modis1kmto250m, lons1km, lats1km, 10, cores)
cols1km = np.arange(1354)
cols250m = np.aran... | Getting 250m geolocation for modis from 1km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation | entailment |
def generic_modis5kmto1km(*data5km):
"""Getting 1km data for modis from 5km tiepoints.
"""
cols5km = np.arange(2, 1354, 5)
cols1km = np.arange(1354)
lines = data5km[0].shape[0] * 5
rows5km = np.arange(2, lines, 5)
rows1km = np.arange(lines)
along_track_order = 1
cross_track_order = ... | Getting 1km data for modis from 5km tiepoints. | entailment |
def fill_borders(self, *args):
"""Extrapolate tiepoint lons and lats to fill in the border of the
chunks.
"""
to_run = []
cases = {"y": self._fill_row_borders,
"x": self._fill_col_borders}
for dim in args:
try:
to_run.append(c... | Extrapolate tiepoint lons and lats to fill in the border of the
chunks. | entailment |
def _extrapolate_cols(self, data, first=True, last=True):
"""Extrapolate the column of data, to get the first and last together
with the data.
"""
if first:
pos = self.col_indices[:2]
first_column = _linear_extrapolate(pos,
... | Extrapolate the column of data, to get the first and last together
with the data. | entailment |
def _fill_col_borders(self):
"""Add the first and last column to the data by extrapolation.
"""
first = True
last = True
if self.col_indices[0] == self.hcol_indices[0]:
first = False
if self.col_indices[-1] == self.hcol_indices[-1]:
last = False
... | Add the first and last column to the data by extrapolation. | entailment |
def _extrapolate_rows(self, data, row_indices, first_index, last_index):
"""Extrapolate the rows of data, to get the first and last together
with the data.
"""
pos = row_indices[:2]
first_row = _linear_extrapolate(pos,
(data[0, :], data[1,... | Extrapolate the rows of data, to get the first and last together
with the data. | entailment |
def _fill_row_borders(self):
"""Add the first and last rows to the data by extrapolation.
"""
lines = len(self.hrow_indices)
chunk_size = self.chunk_size or lines
factor = len(self.hrow_indices) / len(self.row_indices)
tmp_data = []
for num in range(len(self.tie_... | Add the first and last rows to the data by extrapolation. | entailment |
def _interp(self):
"""Interpolate the cartesian coordinates.
"""
if np.all(self.hrow_indices == self.row_indices):
return self._interp1d()
xpoints, ypoints = np.meshgrid(self.hrow_indices,
self.hcol_indices)
for num, data in en... | Interpolate the cartesian coordinates. | entailment |
def _interp1d(self):
"""Interpolate in one dimension.
"""
lines = len(self.hrow_indices)
for num, data in enumerate(self.tie_data):
self.new_data[num] = np.empty((len(self.hrow_indices),
len(self.hcol_indices)),
... | Interpolate in one dimension. | entailment |
def get_lons_from_cartesian(x__, y__):
"""Get longitudes from cartesian coordinates.
"""
return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__) | Get longitudes from cartesian coordinates. | entailment |
def get_lats_from_cartesian(x__, y__, z__, thr=0.8):
"""Get latitudes from cartesian coordinates.
"""
# if we are at low latitudes - small z, then get the
# latitudes only from z. If we are at high latitudes (close to the poles)
# then derive the latitude using x and y:
lats = np.where(np.logic... | Get latitudes from cartesian coordinates. | entailment |
def set_tiepoints(self, lon, lat):
"""Defines the lon,lat tie points.
"""
self.lon_tiepoint = lon
self.lat_tiepoint = lat | Defines the lon,lat tie points. | entailment |
def compute_expansion_alignment(satz_a, satz_b, satz_c, satz_d):
"""All angles in radians."""
zeta_a = satz_a
zeta_b = satz_b
phi_a = compute_phi(zeta_a)
phi_b = compute_phi(zeta_b)
theta_a = compute_theta(zeta_a, phi_a)
theta_b = compute_theta(zeta_b, phi_b)
phi = (phi_a + phi_b) / 2
... | All angles in radians. | entailment |
def lonlat2xyz(lons, lats):
"""Convert lons and lats to cartesian coordinates."""
R = 6370997.0
x_coords = R * da.cos(da.deg2rad(lats)) * da.cos(da.deg2rad(lons))
y_coords = R * da.cos(da.deg2rad(lats)) * da.sin(da.deg2rad(lons))
z_coords = R * da.sin(da.deg2rad(lats))
return x_coords, y_coords,... | Convert lons and lats to cartesian coordinates. | entailment |
def xyz2lonlat(x__, y__, z__):
"""Get longitudes from cartesian coordinates.
"""
R = 6370997.0
lons = da.rad2deg(da.arccos(x__ / da.sqrt(x__ ** 2 + y__ ** 2))) * da.sign(y__)
lats = da.sign(z__) * (90 - da.rad2deg(da.arcsin(da.sqrt(x__ ** 2 + y__ ** 2) / R)))
return lons, lats | Get longitudes from cartesian coordinates. | entailment |
def setup_fields(attrs):
"""
Collect all fields declared on the class and remove them from attrs
"""
fields = {}
iterator = list(attrs.items())
for key, value in iterator:
if not isinstance(value, Field):
continue
fields[key] = value
del attrs[key]
return ... | Collect all fields declared on the class and remove them from attrs | entailment |
def _parse_jing_line(line):
"""Parse a line of jing output to a list of line, column, type
and message.
"""
parts = line.split(':', 4)
filename, line, column, type_, message = [x.strip() for x in parts]
if type_ == 'fatal':
if message in KNOWN_FATAL_MESSAGES_MAPPING:
message... | Parse a line of jing output to a list of line, column, type
and message. | entailment |
def _parse_jing_output(output):
"""Parse the jing output into a tuple of line, column, type and message.
"""
output = output.strip()
values = [_parse_jing_line(l) for l in output.split('\n') if l]
return tuple(values) | Parse the jing output into a tuple of line, column, type and message. | entailment |
def jing(rng_filepath, *xml_filepaths):
"""Run jing.jar using the RNG file against the given XML file."""
cmd = ['java', '-jar']
cmd.extend([str(JING_JAR), str(rng_filepath)])
for xml_filepath in xml_filepaths:
cmd.append(str(xml_filepath))
proc = subprocess.Popen(cmd,
... | Run jing.jar using the RNG file against the given XML file. | entailment |
def import_obj_from_str(s):
"""Returns an import object (either ImportImport or FromImport) from text.
"""
ast_obj = ast.parse(s).body[0]
return ast_type_to_import_type[type(ast_obj)](ast_obj) | Returns an import object (either ImportImport or FromImport) from text. | entailment |
def from_str(cls, s):
"""Construct an import object from a string."""
ast_obj = ast.parse(s).body[0]
if not isinstance(ast_obj, cls._expected_ast_type):
raise AssertionError(
'Expected ast of type {!r} but got {!r}'.format(
cls._expected_ast_type,
... | Construct an import object from a string. | entailment |
def sort(imports, separate=True, import_before_from=True, **classify_kwargs):
"""Sort import objects into groups.
:param list imports: FromImport / ImportImport objects
:param bool separate: Whether to classify and return separate segments
of imports based on classification.
:param bool import_... | Sort import objects into groups.
:param list imports: FromImport / ImportImport objects
:param bool separate: Whether to classify and return separate segments
of imports based on classification.
:param bool import_before_from: Whether to sort `import ...` imports before
`from ...` imports.
... | entailment |
def classify_import(module_name, application_directories=('.',)):
"""Classifies an import by its package.
Returns a value in ImportType.__all__
:param text module_name: The dotted notation of a module
:param tuple application_directories: tuple of paths which are considered
application roots.
... | Classifies an import by its package.
Returns a value in ImportType.__all__
:param text module_name: The dotted notation of a module
:param tuple application_directories: tuple of paths which are considered
application roots. | entailment |
def _arg_parser():
"""Factory for creating the argument parser"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('xml', nargs='*')
return parser | Factory for creating the argument parser | entailment |
def parse_metadata(elm_tree):
"""Given an element-like object (:mod:`lxml.etree`)
lookup the metadata and return the found elements
:param elm_tree: the root xml element
:type elm_tree: an element-like object from :mod:`lxml.etree`
:returns: common metadata properties
:rtype: dict
"""
... | Given an element-like object (:mod:`lxml.etree`)
lookup the metadata and return the found elements
:param elm_tree: the root xml element
:type elm_tree: an element-like object from :mod:`lxml.etree`
:returns: common metadata properties
:rtype: dict | entailment |
def validate_cnxml(*content_filepaths):
"""Validates the given CNXML file against the cnxml-jing.rng RNG."""
content_filepaths = [Path(path).resolve() for path in content_filepaths]
return jing(CNXML_JING_RNG, *content_filepaths) | Validates the given CNXML file against the cnxml-jing.rng RNG. | entailment |
def validate_collxml(*content_filepaths):
"""Validates the given COLLXML file against the collxml-jing.rng RNG."""
content_filepaths = [Path(path).resolve() for path in content_filepaths]
return jing(COLLXML_JING_RNG, *content_filepaths) | Validates the given COLLXML file against the collxml-jing.rng RNG. | entailment |
def action(args):
"""Roll back commands on a refpkg.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on) and n (giving the number of
operations to roll back).
"""
log.info('loading reference package')
r = refpkg.Refpkg(args.refpkg, create=Fa... | Roll back commands on a refpkg.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on) and n (giving the number of
operations to roll back). | entailment |
def set_targets(x, delta=10):
""" Sets target market trend for a date
Args:
x: Pandas DataFrame of market features
delta: Positive number defining a price buffer between what is
classified as a bullish/bearish market for the training set.
delta is equivalent to the total... | Sets target market trend for a date
Args:
x: Pandas DataFrame of market features
delta: Positive number defining a price buffer between what is
classified as a bullish/bearish market for the training set.
delta is equivalent to the total size of the neutral price zone.
... | entailment |
def eval_features(json):
""" Gets technical analysis features from market data JSONs
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
Returns:
Dict of market features and their values
"""
return {'close' : json[-1]['close']... | Gets technical analysis features from market data JSONs
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
Returns:
Dict of market features and their values | entailment |
def target_code_to_name(code):
""" Converts an int target code to a target name
Since self.TARGET_CODES is a 1:1 mapping, perform a reverse lookup
to get the more readable name.
Args:
code: Value from self.TARGET_CODES
Returns:
String target name corresponding to the given code.
... | Converts an int target code to a target name
Since self.TARGET_CODES is a 1:1 mapping, perform a reverse lookup
to get the more readable name.
Args:
code: Value from self.TARGET_CODES
Returns:
String target name corresponding to the given code. | entailment |
def setup_model(x, y, model_type='random_forest', seed=None, **kwargs):
""" Initializes a machine learning model
Args:
x: Pandas DataFrame, X axis of features
y: Pandas Series, Y axis of targets
model_type: Machine Learning model to use
Valid values: 'random_forest'
... | Initializes a machine learning model
Args:
x: Pandas DataFrame, X axis of features
y: Pandas Series, Y axis of targets
model_type: Machine Learning model to use
Valid values: 'random_forest'
seed: Random state to use when splitting sets and creating the model
**k... | entailment |
def get_json(self):
""" Gets market chart data from today to a previous date """
today = dt.now()
DIRECTION = 'last'
epochs = date.get_end_start_epochs(today.year, today.month, today.day,
DIRECTION, self.unit, self.count)
return poloniex... | Gets market chart data from today to a previous date | entailment |
def set_features(self, partition=1):
""" Parses market data JSON for technical analysis indicators
Args:
partition: Int of how many dates to take into consideration
when evaluating technical analysis indicators.
Returns:
Pandas DataFrame instance with co... | Parses market data JSON for technical analysis indicators
Args:
partition: Int of how many dates to take into consideration
when evaluating technical analysis indicators.
Returns:
Pandas DataFrame instance with columns as numpy.float32 features. | entailment |
def set_long_features(self, features, columns_to_set=[], partition=2):
""" Sets features of double the duration
Example: Setting 14 day RSIs to longer will create add a
feature column of a 28 day RSIs.
Args:
features: Pandas DataFrame instance with columns as numpy.floa... | Sets features of double the duration
Example: Setting 14 day RSIs to longer will create add a
feature column of a 28 day RSIs.
Args:
features: Pandas DataFrame instance with columns as numpy.float32 features.
columns_to_set: List of strings of feature names to make ... | entailment |
def feature_importances(self):
""" Return list of features and their importance in classification """
feature_names = [feature for feature in self.features.train]
return list(zip(feature_names, self.feature_importances_)) | Return list of features and their importance in classification | entailment |
def exitcode(self):
"""
Process exit code. :const:`0` when process exited successfully,
positive number when exception was occurred, negative number when
process was signaled and :data:`None` when process has not exited
yet.
"""
if self._process is None:
... | Process exit code. :const:`0` when process exited successfully,
positive number when exception was occurred, negative number when
process was signaled and :data:`None` when process has not exited
yet. | entailment |
def start(self):
"""
Run the process.
"""
if self:
raise ProcessError(
"Process '%s' has been already started" % self.name)
first_run = not self.has_started
# Run process
self._process = self._process_cls(*self._process_args)
se... | Run the process. | entailment |
def stop(self):
"""
Stop the worker.
"""
if self._http_server is not None:
self._http_server.stop()
tornado.ioloop.IOLoop.instance().add_callback(
tornado.ioloop.IOLoop.instance().stop) | Stop the worker. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.