code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def load(self, *relations):
"""
Load a set of relationships onto the collection.
"""
if len(self.items) > 0:
query = self.first().new_query().with_(*relations)
self._set_items(query.eager_load_relations(self.items))
return self | Load a set of relationships onto the collection. | Below is the the instruction that describes the task:
### Input:
Load a set of relationships onto the collection.
### Response:
def load(self, *relations):
"""
Load a set of relationships onto the collection.
"""
if len(self.items) > 0:
query = self.first().new_query().w... |
def merge_graphs(self, other_docgraph, verbose=False):
"""
Merges another document graph into the current one, thereby adding all
the necessary nodes and edges (with attributes, layers etc.).
NOTE: This will only work if both graphs have exactly the same
tokenization.
""... | Merges another document graph into the current one, thereby adding all
the necessary nodes and edges (with attributes, layers etc.).
NOTE: This will only work if both graphs have exactly the same
tokenization. | Below is the the instruction that describes the task:
### Input:
Merges another document graph into the current one, thereby adding all
the necessary nodes and edges (with attributes, layers etc.).
NOTE: This will only work if both graphs have exactly the same
tokenization.
### Response:
d... |
def consecutive_ones_property(sets, universe=None):
""" Check the consecutive ones property.
:param list sets: is a list of subsets of the ground set.
:param groundset: is the set of all elements,
by default it is the union of the given sets
:returns: returns a list of the ordered groun... | Check the consecutive ones property.
:param list sets: is a list of subsets of the ground set.
:param groundset: is the set of all elements,
by default it is the union of the given sets
:returns: returns a list of the ordered ground set where
every given set is consecutive,
... | Below is the the instruction that describes the task:
### Input:
Check the consecutive ones property.
:param list sets: is a list of subsets of the ground set.
:param groundset: is the set of all elements,
by default it is the union of the given sets
:returns: returns a list of the orde... |
def mkvirtualenv():
"""
Create the virtualenv project environment
"""
root = '/'.join([deployment_root(),'env'])
path = '/'.join([root,env.project_fullname])
dirs_created = []
if env.verbosity:
print env.host,'CREATING VIRTUALENV', path
if not exists(root): dirs_created += mkdirs... | Create the virtualenv project environment | Below is the the instruction that describes the task:
### Input:
Create the virtualenv project environment
### Response:
def mkvirtualenv():
"""
Create the virtualenv project environment
"""
root = '/'.join([deployment_root(),'env'])
path = '/'.join([root,env.project_fullname])
dirs_created... |
def print_dictionary(self, d, h, n, nl=False):
"""Print complex using the specified indent (n) and newline (nl)."""
if d in h:
return "{}..."
h.append(d)
s = []
if nl:
s.append("\n")
s.append(self.indent(n))
s.append("{")
for it... | Print complex using the specified indent (n) and newline (nl). | Below is the the instruction that describes the task:
### Input:
Print complex using the specified indent (n) and newline (nl).
### Response:
def print_dictionary(self, d, h, n, nl=False):
"""Print complex using the specified indent (n) and newline (nl)."""
if d in h:
return "{}..."
... |
def save_predefined(self, predefined, client=None):
"""Save this ACL for the current bucket using a predefined ACL.
If :attr:`user_project` is set, bills the API request to that project.
:type predefined: str
:param predefined: An identifier for a predefined ACL. Must be one
... | Save this ACL for the current bucket using a predefined ACL.
If :attr:`user_project` is set, bills the API request to that project.
:type predefined: str
:param predefined: An identifier for a predefined ACL. Must be one
of the keys in :attr:`PREDEFINED_JSON_ACLS`
... | Below is the the instruction that describes the task:
### Input:
Save this ACL for the current bucket using a predefined ACL.
If :attr:`user_project` is set, bills the API request to that project.
:type predefined: str
:param predefined: An identifier for a predefined ACL. Must be one
... |
def from_sample_rate(sample_rate, n_bands, always_even=False):
"""
Return a :class:`~zounds.spectral.LinearScale` instance whose upper
frequency bound is informed by the nyquist frequency of the sample rate.
Args:
sample_rate (SamplingRate): the sample rate whose nyquist fre... | Return a :class:`~zounds.spectral.LinearScale` instance whose upper
frequency bound is informed by the nyquist frequency of the sample rate.
Args:
sample_rate (SamplingRate): the sample rate whose nyquist frequency
will serve as the upper frequency bound of this scale
... | Below is the the instruction that describes the task:
### Input:
Return a :class:`~zounds.spectral.LinearScale` instance whose upper
frequency bound is informed by the nyquist frequency of the sample rate.
Args:
sample_rate (SamplingRate): the sample rate whose nyquist frequency
... |
def serialize(self, queryset, **options):
"""
Serialize a queryset.
"""
self.options = options
self.stream = options.pop("stream", six.StringIO())
self.selected_fields = options.pop("fields", None)
self.use_natural_keys = options.pop("use_natural_keys", False)
... | Serialize a queryset. | Below is the the instruction that describes the task:
### Input:
Serialize a queryset.
### Response:
def serialize(self, queryset, **options):
"""
Serialize a queryset.
"""
self.options = options
self.stream = options.pop("stream", six.StringIO())
self.selected_fiel... |
def from_image(cls, image):
"""
Create a PrintableImage from a PIL Image
:param image: a PIL Image
:return:
"""
(w, h) = image.size
# Thermal paper is 512 pixels wide
if w > 512:
ratio = 512. / w
h = int(h * ratio)
imag... | Create a PrintableImage from a PIL Image
:param image: a PIL Image
:return: | Below is the the instruction that describes the task:
### Input:
Create a PrintableImage from a PIL Image
:param image: a PIL Image
:return:
### Response:
def from_image(cls, image):
"""
Create a PrintableImage from a PIL Image
:param image: a PIL Image
:return:
... |
def _maybe_localize_point(ts, is_none, is_not_none, freq, tz):
"""
Localize a start or end Timestamp to the timezone of the corresponding
start or end Timestamp
Parameters
----------
ts : start or end Timestamp to potentially localize
is_none : argument that should be None
is_not_none :... | Localize a start or end Timestamp to the timezone of the corresponding
start or end Timestamp
Parameters
----------
ts : start or end Timestamp to potentially localize
is_none : argument that should be None
is_not_none : argument that should not be None
freq : Tick, DateOffset, or None
... | Below is the the instruction that describes the task:
### Input:
Localize a start or end Timestamp to the timezone of the corresponding
start or end Timestamp
Parameters
----------
ts : start or end Timestamp to potentially localize
is_none : argument that should be None
is_not_none : argum... |
def download(date_array, tag, sat_id, data_path, user=None, password=None):
"""Routine to download Kp index data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '1min' and '5min'.
(default=None)
sat_id : (string or NoneType)
... | Routine to download Kp index data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '1min' and '5min'.
(default=None)
sat_id : (string or NoneType)
Specifies the satellite ID for a constellation. Not used.
(default=None)... | Below is the the instruction that describes the task:
### Input:
Routine to download Kp index data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '1min' and '5min'.
(default=None)
sat_id : (string or NoneType)
Specifies th... |
def on_set(self, key, value):
"""Callback called on successful set. Uses function from __init__."""
if self._on_set is not None:
self._on_set(key, value) | Callback called on successful set. Uses function from __init__. | Below is the the instruction that describes the task:
### Input:
Callback called on successful set. Uses function from __init__.
### Response:
def on_set(self, key, value):
"""Callback called on successful set. Uses function from __init__."""
if self._on_set is not None:
self._on_set(key, value) |
def __send_handle_get_request(self, handle, indices=None):
'''
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Opt... | Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the enti... | Below is the the instruction that describes the task:
### Input:
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A l... |
def b_spline_basis(x, edge_knots, n_splines=20, spline_order=3, sparse=True,
periodic=True, verbose=True):
"""
tool to generate b-spline basis using vectorized De Boor recursion
the basis functions extrapolate linearly past the end-knots.
Parameters
----------
x : array-like,... | tool to generate b-spline basis using vectorized De Boor recursion
the basis functions extrapolate linearly past the end-knots.
Parameters
----------
x : array-like, with ndims == 1.
edge_knots : array-like contaning locations of the 2 edge knots.
n_splines : int. number of splines to generate.... | Below is the the instruction that describes the task:
### Input:
tool to generate b-spline basis using vectorized De Boor recursion
the basis functions extrapolate linearly past the end-knots.
Parameters
----------
x : array-like, with ndims == 1.
edge_knots : array-like contaning locations of ... |
def _next(self, possible_solution):
"""Where the magic happens. Produces a generator that returns all solutions given
a base solution to start searching.
"""
# bail out if we have seen it already. See __iter__ to where seen is initially set.
# A complete solution has all its vari... | Where the magic happens. Produces a generator that returns all solutions given
a base solution to start searching. | Below is the the instruction that describes the task:
### Input:
Where the magic happens. Produces a generator that returns all solutions given
a base solution to start searching.
### Response:
def _next(self, possible_solution):
"""Where the magic happens. Produces a generator that returns all sol... |
def mimetype_params(self):
"""The mimetype parameters as dict. For example if the
content type is ``text/html; charset=utf-8`` the params would be
``{'charset': 'utf-8'}``.
.. versionadded:: 0.5
"""
def on_update(d):
self.headers["Content-Type"] = dump_optio... | The mimetype parameters as dict. For example if the
content type is ``text/html; charset=utf-8`` the params would be
``{'charset': 'utf-8'}``.
.. versionadded:: 0.5 | Below is the the instruction that describes the task:
### Input:
The mimetype parameters as dict. For example if the
content type is ``text/html; charset=utf-8`` the params would be
``{'charset': 'utf-8'}``.
.. versionadded:: 0.5
### Response:
def mimetype_params(self):
"""The mime... |
def set_is_polling(polling, host=None, core_name=None):
'''
SLAVE CALL
Prevent the slaves from polling the master for updates.
polling : boolean
True will enable polling. False will disable it.
host : str (None)
The solr host to query. __opts__['host'] is default.
core_name : st... | SLAVE CALL
Prevent the slaves from polling the master for updates.
polling : boolean
True will enable polling. False will disable it.
host : str (None)
The solr host to query. __opts__['host'] is default.
core_name : str (None)
The name of the solr core if using cores. Leave thi... | Below is the the instruction that describes the task:
### Input:
SLAVE CALL
Prevent the slaves from polling the master for updates.
polling : boolean
True will enable polling. False will disable it.
host : str (None)
The solr host to query. __opts__['host'] is default.
core_name : s... |
def getparent(self, profile):
"""Resolve a parent ID"""
assert self.parent
for inputtemplate in profile.input:
if inputtemplate == self.parent:
return inputtemplate
raise Exception("Parent InputTemplate '"+self.parent+"' not found!") | Resolve a parent ID | Below is the the instruction that describes the task:
### Input:
Resolve a parent ID
### Response:
def getparent(self, profile):
"""Resolve a parent ID"""
assert self.parent
for inputtemplate in profile.input:
if inputtemplate == self.parent:
return inputtemplate... |
def to_call_agraph(self):
""" Build a PyGraphviz AGraph object corresponding to a call graph of
functions. """
A = nx.nx_agraph.to_agraph(self.call_graph)
A.graph_attr.update({"dpi": 227, "fontsize": 20, "fontname": "Menlo"})
A.node_attr.update(
{"shape": "rectangle"... | Build a PyGraphviz AGraph object corresponding to a call graph of
functions. | Below is the the instruction that describes the task:
### Input:
Build a PyGraphviz AGraph object corresponding to a call graph of
functions.
### Response:
def to_call_agraph(self):
""" Build a PyGraphviz AGraph object corresponding to a call graph of
functions. """
A = nx.nx_agrap... |
def aesCCM(key, key_handle, nonce, data, decrypt=False):
"""
Function implementing YubiHSM AEAD encrypt/decrypt in software.
"""
if decrypt:
(data, saved_mac) = _split_data(data, len(data) - pyhsm.defines.YSM_AEAD_MAC_SIZE)
nonce = pyhsm.util.input_validate_nonce(nonce, pad = True)
mac ... | Function implementing YubiHSM AEAD encrypt/decrypt in software. | Below is the the instruction that describes the task:
### Input:
Function implementing YubiHSM AEAD encrypt/decrypt in software.
### Response:
def aesCCM(key, key_handle, nonce, data, decrypt=False):
"""
Function implementing YubiHSM AEAD encrypt/decrypt in software.
"""
if decrypt:
(data, ... |
def restore_course(self, courseid, backup):
""" Restores a course of given courseid to a date specified in backup (format : YYYYMMDD.HHMMSS) """
self.wipe_course(courseid)
filepath = os.path.join(self.backup_dir, courseid, backup + ".zip")
with zipfile.ZipFile(filepath, "r") as zipf:
... | Restores a course of given courseid to a date specified in backup (format : YYYYMMDD.HHMMSS) | Below is the the instruction that describes the task:
### Input:
Restores a course of given courseid to a date specified in backup (format : YYYYMMDD.HHMMSS)
### Response:
def restore_course(self, courseid, backup):
""" Restores a course of given courseid to a date specified in backup (format : YYYYMMDD.HH... |
def _new_percolator(spec, search_pattern):
"""Create new percolator associated with the new set."""
if spec and search_pattern:
query = query_string_parser(search_pattern=search_pattern).to_dict()
for index in current_search.mappings.keys():
# Create the percolator doc_type in the ex... | Create new percolator associated with the new set. | Below is the the instruction that describes the task:
### Input:
Create new percolator associated with the new set.
### Response:
def _new_percolator(spec, search_pattern):
"""Create new percolator associated with the new set."""
if spec and search_pattern:
query = query_string_parser(search_patter... |
def ListHunts(context=None):
"""List all GRR hunts."""
items = context.SendIteratorRequest("ListHunts", hunt_pb2.ApiListHuntsArgs())
return utils.MapItemsIterator(lambda data: Hunt(data=data, context=context),
items) | List all GRR hunts. | Below is the the instruction that describes the task:
### Input:
List all GRR hunts.
### Response:
def ListHunts(context=None):
"""List all GRR hunts."""
items = context.SendIteratorRequest("ListHunts", hunt_pb2.ApiListHuntsArgs())
return utils.MapItemsIterator(lambda data: Hunt(data=data, context=context),... |
def depth_renderbuffer(self, size, *, samples=0) -> 'Renderbuffer':
'''
:py:class:`Renderbuffer` objects are OpenGL objects that contain images.
They are created and used specifically with :py:class:`Framebuffer` objects.
Args:
size (tuple): The width and hei... | :py:class:`Renderbuffer` objects are OpenGL objects that contain images.
They are created and used specifically with :py:class:`Framebuffer` objects.
Args:
size (tuple): The width and height of the renderbuffer.
Keyword Args:
samples (int): The numbe... | Below is the the instruction that describes the task:
### Input:
:py:class:`Renderbuffer` objects are OpenGL objects that contain images.
They are created and used specifically with :py:class:`Framebuffer` objects.
Args:
size (tuple): The width and height of the renderbuffer... |
def download(self, itemID, savePath):
"""
downloads an item to local disk
Inputs:
itemID - unique id of item to download
savePath - folder to save the file in
"""
if os.path.isdir(savePath) == False:
os.makedirs(savePath)
url = self._url... | downloads an item to local disk
Inputs:
itemID - unique id of item to download
savePath - folder to save the file in | Below is the the instruction that describes the task:
### Input:
downloads an item to local disk
Inputs:
itemID - unique id of item to download
savePath - folder to save the file in
### Response:
def download(self, itemID, savePath):
"""
downloads an item to local dis... |
def _get_vnet(self, adapter_number):
"""
Return the vnet will use in ubridge
"""
vnet = "ethernet{}.vnet".format(adapter_number)
if vnet not in self._vmx_pairs:
raise VMwareError("vnet {} not in VMX file".format(vnet))
return vnet | Return the vnet will use in ubridge | Below is the the instruction that describes the task:
### Input:
Return the vnet will use in ubridge
### Response:
def _get_vnet(self, adapter_number):
"""
Return the vnet will use in ubridge
"""
vnet = "ethernet{}.vnet".format(adapter_number)
if vnet not in self._vmx_pairs:... |
def assert_boolean_false(expr, msg_fmt="{msg}"):
"""Fail the test unless the expression is the constant False.
>>> assert_boolean_false(False)
>>> assert_boolean_false(0)
Traceback (most recent call last):
...
AssertionError: 0 is not False
The following msg_fmt arguments are supported... | Fail the test unless the expression is the constant False.
>>> assert_boolean_false(False)
>>> assert_boolean_false(0)
Traceback (most recent call last):
...
AssertionError: 0 is not False
The following msg_fmt arguments are supported:
* msg - the default error message
* expr - tes... | Below is the the instruction that describes the task:
### Input:
Fail the test unless the expression is the constant False.
>>> assert_boolean_false(False)
>>> assert_boolean_false(0)
Traceback (most recent call last):
...
AssertionError: 0 is not False
The following msg_fmt arguments ... |
def template(page=None, layout=None, **kwargs):
"""
Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
:fi... | Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
:first arg or $layout: The layout to use for that view
... | Below is the the instruction that describes the task:
### Input:
Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
... |
def make_urls_hyperlinks(text: str) -> str:
"""
Adds hyperlinks to text that appears to contain URLs.
See
- http://stackoverflow.com/questions/1071191
- ... except that double-replaces everything; e.g. try with
``text = "me@somewhere.com me@somewhere.com"``
- http://stackp.online.f... | Adds hyperlinks to text that appears to contain URLs.
See
- http://stackoverflow.com/questions/1071191
- ... except that double-replaces everything; e.g. try with
``text = "me@somewhere.com me@somewhere.com"``
- http://stackp.online.fr/?p=19 | Below is the the instruction that describes the task:
### Input:
Adds hyperlinks to text that appears to contain URLs.
See
- http://stackoverflow.com/questions/1071191
- ... except that double-replaces everything; e.g. try with
``text = "me@somewhere.com me@somewhere.com"``
- http://st... |
def update_edge_todo(self, elev_fn, dem_proc):
"""
Can figure out how to update the todo based on the elev filename
"""
for key in self.edges[elev_fn].keys():
self.edges[elev_fn][key].set_data('todo', data=dem_proc.edge_todo) | Can figure out how to update the todo based on the elev filename | Below is the the instruction that describes the task:
### Input:
Can figure out how to update the todo based on the elev filename
### Response:
def update_edge_todo(self, elev_fn, dem_proc):
"""
Can figure out how to update the todo based on the elev filename
"""
for key in self.edg... |
def _get_sector(self, channel, nlines, ncols):
"""Determine which sector was scanned"""
if self._is_vis(channel):
margin = 100
sectors_ref = self.vis_sectors
else:
margin = 50
sectors_ref = self.ir_sectors
for (nlines_ref, ncols_ref), sect... | Determine which sector was scanned | Below is the the instruction that describes the task:
### Input:
Determine which sector was scanned
### Response:
def _get_sector(self, channel, nlines, ncols):
"""Determine which sector was scanned"""
if self._is_vis(channel):
margin = 100
sectors_ref = self.vis_sectors
... |
def bootstrap_files(self):
""" we need some files to bootstrap the FreeBSD installation.
Some...
- need to be provided by the user (i.e. authorized_keys)
- others have some (sensible) defaults (i.e. rc.conf)
- some can be downloaded via URL (i.e.) http://pkg.freebsd.o... | we need some files to bootstrap the FreeBSD installation.
Some...
- need to be provided by the user (i.e. authorized_keys)
- others have some (sensible) defaults (i.e. rc.conf)
- some can be downloaded via URL (i.e.) http://pkg.freebsd.org/freebsd:10:x86:64/latest/Latest/pkg.... | Below is the the instruction that describes the task:
### Input:
we need some files to bootstrap the FreeBSD installation.
Some...
- need to be provided by the user (i.e. authorized_keys)
- others have some (sensible) defaults (i.e. rc.conf)
- some can be downloaded via U... |
def get_rnn_cells(self) -> List[mx.rnn.BaseRNNCell]:
"""
Returns a list of RNNCells used by this encoder.
"""
return self.forward_rnn.get_rnn_cells() + self.reverse_rnn.get_rnn_cells() | Returns a list of RNNCells used by this encoder. | Below is the the instruction that describes the task:
### Input:
Returns a list of RNNCells used by this encoder.
### Response:
def get_rnn_cells(self) -> List[mx.rnn.BaseRNNCell]:
"""
Returns a list of RNNCells used by this encoder.
"""
return self.forward_rnn.get_rnn_cells() + sel... |
def _zero_based_index(self, onebased: Union[int, str]) -> int:
"""Convert a one-based index to a zero-based index."""
result = int(onebased)
if result > 0:
result -= 1
return result | Convert a one-based index to a zero-based index. | Below is the the instruction that describes the task:
### Input:
Convert a one-based index to a zero-based index.
### Response:
def _zero_based_index(self, onebased: Union[int, str]) -> int:
"""Convert a one-based index to a zero-based index."""
result = int(onebased)
if result > 0:
... |
def build_result(data):
"""Create a dictionary with the contents of result.json"""
more = {}
for key, value in data.items():
if key != 'elements':
newnode = value
else:
newnode = {}
for el in value:
nkey, nvalue = process_node(el)
... | Create a dictionary with the contents of result.json | Below is the the instruction that describes the task:
### Input:
Create a dictionary with the contents of result.json
### Response:
def build_result(data):
"""Create a dictionary with the contents of result.json"""
more = {}
for key, value in data.items():
if key != 'elements':
new... |
def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: T... | This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name... | Below is the the instruction that describes the task:
### Input:
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise... |
def deploy(self, ids):
"""
Method to deploy vip's
:param vips: List containing vip's desired to be deployed on equipment
:return: None
"""
url = build_uri_with_ids('api/v3/vip-request/deploy/%s/', ids)
return super(ApiVipRequest, self).post(url) | Method to deploy vip's
:param vips: List containing vip's desired to be deployed on equipment
:return: None | Below is the the instruction that describes the task:
### Input:
Method to deploy vip's
:param vips: List containing vip's desired to be deployed on equipment
:return: None
### Response:
def deploy(self, ids):
"""
Method to deploy vip's
:param vips: List containing vip's d... |
def add_layer(self, element, layer):
"""
add a layer to an existing node or edge
Parameters
----------
element : str, int, (str/int, str/int)
the ID of a node or edge (source node ID, target node ID)
layer : str
the layer that the element shall be... | add a layer to an existing node or edge
Parameters
----------
element : str, int, (str/int, str/int)
the ID of a node or edge (source node ID, target node ID)
layer : str
the layer that the element shall be added to | Below is the the instruction that describes the task:
### Input:
add a layer to an existing node or edge
Parameters
----------
element : str, int, (str/int, str/int)
the ID of a node or edge (source node ID, target node ID)
layer : str
the layer that the elem... |
def set_headers(self, headers):
"""*Sets new request headers or updates the existing.*
``headers``: The headers to add or update as a JSON object or a
dictionary.
*Examples*
| `Set Headers` | { "authorization": "Basic QWxhZGRpbjpPcGVuU2VzYW1"} |
| `Set Headers` | { "Ac... | *Sets new request headers or updates the existing.*
``headers``: The headers to add or update as a JSON object or a
dictionary.
*Examples*
| `Set Headers` | { "authorization": "Basic QWxhZGRpbjpPcGVuU2VzYW1"} |
| `Set Headers` | { "Accept-Encoding": "identity"} |
| `Se... | Below is the the instruction that describes the task:
### Input:
*Sets new request headers or updates the existing.*
``headers``: The headers to add or update as a JSON object or a
dictionary.
*Examples*
| `Set Headers` | { "authorization": "Basic QWxhZGRpbjpPcGVuU2VzYW1"} |
... |
def _worst_case_generation(self, worst_case_scale_factors, modes):
"""
Define worst case generation time series for fluctuating and
dispatchable generators.
Parameters
----------
worst_case_scale_factors : dict
Scale factors defined in config file 'config_tim... | Define worst case generation time series for fluctuating and
dispatchable generators.
Parameters
----------
worst_case_scale_factors : dict
Scale factors defined in config file 'config_timeseries.cfg'.
Scale factors describe actual power to nominal power ratio of... | Below is the the instruction that describes the task:
### Input:
Define worst case generation time series for fluctuating and
dispatchable generators.
Parameters
----------
worst_case_scale_factors : dict
Scale factors defined in config file 'config_timeseries.cfg'.
... |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._uuid is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._attachment is not None:
ret... | :rtype: bool | Below is the the instruction that describes the task:
### Input:
:rtype: bool
### Response:
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._uuid is not None:
return False
if self._created is not None:
return False
if self._update... |
def get(self, key, default=None, remote=False):
"""
Overrides dictionary get behavior to retrieve database objects with
support for returning a default. If remote=True then a remote
request is made to retrieve the database from the remote server,
otherwise the client's locally c... | Overrides dictionary get behavior to retrieve database objects with
support for returning a default. If remote=True then a remote
request is made to retrieve the database from the remote server,
otherwise the client's locally cached database object is returned.
:param str key: Database... | Below is the the instruction that describes the task:
### Input:
Overrides dictionary get behavior to retrieve database objects with
support for returning a default. If remote=True then a remote
request is made to retrieve the database from the remote server,
otherwise the client's locally ... |
def read_csv(filename, delimiter=",", skip=0, guess_type=True, has_header=True, use_types={}):
"""Read a CSV file
Usage
-----
>>> data = read_csv(filename, delimiter=delimiter, skip=skip,
guess_type=guess_type, has_header=True, use_types={})
# Use specific types
>>> types = {"... | Read a CSV file
Usage
-----
>>> data = read_csv(filename, delimiter=delimiter, skip=skip,
guess_type=guess_type, has_header=True, use_types={})
# Use specific types
>>> types = {"sepal.length": int, "petal.width": float}
>>> data = read_csv(filename, guess_type=guess_type, use... | Below is the the instruction that describes the task:
### Input:
Read a CSV file
Usage
-----
>>> data = read_csv(filename, delimiter=delimiter, skip=skip,
guess_type=guess_type, has_header=True, use_types={})
# Use specific types
>>> types = {"sepal.length": int, "petal.width"... |
def _gatherLookupIndexes(gpos):
"""
Gather a mapping of script to lookup indexes
referenced by the kern feature for each script.
Returns a dictionary of this structure:
{
"latn" : [0],
"DFLT" : [0]
}
"""
# gather the indexes of the kern features
kernFe... | Gather a mapping of script to lookup indexes
referenced by the kern feature for each script.
Returns a dictionary of this structure:
{
"latn" : [0],
"DFLT" : [0]
} | Below is the the instruction that describes the task:
### Input:
Gather a mapping of script to lookup indexes
referenced by the kern feature for each script.
Returns a dictionary of this structure:
{
"latn" : [0],
"DFLT" : [0]
}
### Response:
def _gatherLookupIndexes... |
def build(self, builder):
"""Build XML by appending to builder"""
params = dict(
Namespace=self.namespace,
Name=self.name,
Value=self.value,
TransactionType=self.transaction_type,
)
builder.start("mdsol:Attribute", params)
builder.... | Build XML by appending to builder | Below is the the instruction that describes the task:
### Input:
Build XML by appending to builder
### Response:
def build(self, builder):
"""Build XML by appending to builder"""
params = dict(
Namespace=self.namespace,
Name=self.name,
Value=self.value,
... |
def get_vnetwork_vswitches_input_last_rcvd_instance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_vswitches = ET.Element("get_vnetwork_vswitches")
config = get_vnetwork_vswitches
input = ET.SubElement(get_vnetwork_vswitches, "input... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_vnetwork_vswitches_input_last_rcvd_instance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_vswitches = ET.Element("get_vnetwork_vswitche... |
def add_output_opt(self, opt, out):
""" Add an option that determines an output
"""
self.add_opt(opt, out._dax_repr())
self._add_output(out) | Add an option that determines an output | Below is the the instruction that describes the task:
### Input:
Add an option that determines an output
### Response:
def add_output_opt(self, opt, out):
""" Add an option that determines an output
"""
self.add_opt(opt, out._dax_repr())
self._add_output(out) |
def histogram_equalize(self, use_bands, **kwargs):
''' Equalize and the histogram and normalize value range
Equalization is on all three bands, not per-band'''
data = self._read(self[use_bands,...], **kwargs)
data = np.rollaxis(data.astype(np.float32), 0, 3)
flattened = data.... | Equalize and the histogram and normalize value range
Equalization is on all three bands, not per-band | Below is the the instruction that describes the task:
### Input:
Equalize and the histogram and normalize value range
Equalization is on all three bands, not per-band
### Response:
def histogram_equalize(self, use_bands, **kwargs):
''' Equalize and the histogram and normalize value range
... |
def require_axis(f):
""" Check if the object of the function has axis and sel_axis members """
@wraps(f)
def _wrapper(self, *args, **kwargs):
if None in (self.axis, self.sel_axis):
raise ValueError('%(func_name) requires the node %(node)s '
'to have an axis and a sel... | Check if the object of the function has axis and sel_axis members | Below is the the instruction that describes the task:
### Input:
Check if the object of the function has axis and sel_axis members
### Response:
def require_axis(f):
""" Check if the object of the function has axis and sel_axis members """
@wraps(f)
def _wrapper(self, *args, **kwargs):
if None... |
def set_feature_transform(self, mode='polynomial', degree=1):
'''
Transform data feature to high level
'''
if self.status != 'load_train_data':
print("Please load train data first.")
return self.train_X
self.feature_transform_mode = mode
self.fe... | Transform data feature to high level | Below is the the instruction that describes the task:
### Input:
Transform data feature to high level
### Response:
def set_feature_transform(self, mode='polynomial', degree=1):
'''
Transform data feature to high level
'''
if self.status != 'load_train_data':
print("Pl... |
def _parse_config_file(self, cfg_files):
"""Parse config file (ini) and set properties
:return:
"""
cfg_handler = configparser.ConfigParser(interpolation=None)
if not cfg_handler.read(map(str, cfg_files)):
return
self._parse_global_section(cfg_handler)
... | Parse config file (ini) and set properties
:return: | Below is the the instruction that describes the task:
### Input:
Parse config file (ini) and set properties
:return:
### Response:
def _parse_config_file(self, cfg_files):
"""Parse config file (ini) and set properties
:return:
"""
cfg_handler = configparser.ConfigParser(in... |
def query(self, expr, **kwargs):
"""Query columns of the DataManager with a boolean expression.
Args:
expr: Boolean expression to query the columns with.
Returns:
DataManager containing the rows where the boolean expression is satisfied.
"""
columns = se... | Query columns of the DataManager with a boolean expression.
Args:
expr: Boolean expression to query the columns with.
Returns:
DataManager containing the rows where the boolean expression is satisfied. | Below is the the instruction that describes the task:
### Input:
Query columns of the DataManager with a boolean expression.
Args:
expr: Boolean expression to query the columns with.
Returns:
DataManager containing the rows where the boolean expression is satisfied.
### Res... |
def newton_refine_curve(curve, point, s, new_s):
"""Image for :func:`._curve_helpers.newton_refine` docstring."""
if NO_IMAGES:
return
ax = curve.plot(256)
ax.plot(point[0, :], point[1, :], marker="H")
wrong_points = curve.evaluate_multi(np.asfortranarray([s, new_s]))
ax.plot(
w... | Image for :func:`._curve_helpers.newton_refine` docstring. | Below is the the instruction that describes the task:
### Input:
Image for :func:`._curve_helpers.newton_refine` docstring.
### Response:
def newton_refine_curve(curve, point, s, new_s):
"""Image for :func:`._curve_helpers.newton_refine` docstring."""
if NO_IMAGES:
return
ax = curve.plot(256)
... |
def arg_bool(name, default=False):
""" Fetch a query argument, as a boolean. """
v = request.args.get(name, '')
if not len(v):
return default
return v in BOOL_TRUISH | Fetch a query argument, as a boolean. | Below is the the instruction that describes the task:
### Input:
Fetch a query argument, as a boolean.
### Response:
def arg_bool(name, default=False):
""" Fetch a query argument, as a boolean. """
v = request.args.get(name, '')
if not len(v):
return default
return v in BOOL_TRUISH |
def readmol(path, as_string=False):
"""Reads the given molecule file and returns the corresponding Pybel molecule as well as the input file type.
In contrast to the standard Pybel implementation, the file is closed properly."""
supported_formats = ['pdb']
# Fix for Windows-generated files: Remove carria... | Reads the given molecule file and returns the corresponding Pybel molecule as well as the input file type.
In contrast to the standard Pybel implementation, the file is closed properly. | Below is the the instruction that describes the task:
### Input:
Reads the given molecule file and returns the corresponding Pybel molecule as well as the input file type.
In contrast to the standard Pybel implementation, the file is closed properly.
### Response:
def readmol(path, as_string=False):
"""Rea... |
def _sync_content_metadata(self, serialized_data, http_method):
"""
Synchronize content metadata using the Degreed course content API.
Args:
serialized_data: JSON-encoded object containing content metadata.
http_method: The HTTP method to use for the API request.
... | Synchronize content metadata using the Degreed course content API.
Args:
serialized_data: JSON-encoded object containing content metadata.
http_method: The HTTP method to use for the API request.
Raises:
ClientError: If Degreed API request fails. | Below is the the instruction that describes the task:
### Input:
Synchronize content metadata using the Degreed course content API.
Args:
serialized_data: JSON-encoded object containing content metadata.
http_method: The HTTP method to use for the API request.
Raises:
... |
def delete_suffixes(self, word):
"""
Delete some very common suffixes.
"""
length = len(word)
suffixes = ['al', 'ance', 'ence', 'er', 'ic', 'able', 'ible',
'ant', 'ement', 'ment', 'ent', 'ism', 'ate',
'iti', 'ous', 'ive', 'ize']
fo... | Delete some very common suffixes. | Below is the the instruction that describes the task:
### Input:
Delete some very common suffixes.
### Response:
def delete_suffixes(self, word):
"""
Delete some very common suffixes.
"""
length = len(word)
suffixes = ['al', 'ance', 'ence', 'er', 'ic', 'able', 'ible',
... |
def gen_checkbox_list(sig_dic):
'''
For generating List view HTML file for CHECKBOX.
for each item.
'''
view_zuoxiang = '''<span class="iga_pd_val">'''
dic_tmp = sig_dic['dic']
for key in dic_tmp.keys():
tmp_str = '''{{% if "{0}" in postinfo.extinfo["{1}"] %}} {2} {{% end %}}
... | For generating List view HTML file for CHECKBOX.
for each item. | Below is the the instruction that describes the task:
### Input:
For generating List view HTML file for CHECKBOX.
for each item.
### Response:
def gen_checkbox_list(sig_dic):
'''
For generating List view HTML file for CHECKBOX.
for each item.
'''
view_zuoxiang = '''<span class="iga_pd_val">... |
def zeros(dur=None):
"""
Zeros/zeroes stream generator.
You may sum your endless stream by this to enforce an end to it.
Parameters
----------
dur :
Duration, in number of samples; endless if not given.
Returns
-------
Stream that repeats "0.0" during a given time duration (if any) or
endlessl... | Zeros/zeroes stream generator.
You may sum your endless stream by this to enforce an end to it.
Parameters
----------
dur :
Duration, in number of samples; endless if not given.
Returns
-------
Stream that repeats "0.0" during a given time duration (if any) or
endlessly. | Below is the the instruction that describes the task:
### Input:
Zeros/zeroes stream generator.
You may sum your endless stream by this to enforce an end to it.
Parameters
----------
dur :
Duration, in number of samples; endless if not given.
Returns
-------
Stream that repeats "0.0" during a gi... |
def independentlinear60(display=False):
""" A simulated dataset with tight correlations among distinct groups of features.
"""
# set a constant seed
old_seed = np.random.seed()
np.random.seed(0)
# generate dataset with known correlation
N = 1000
M = 60
# set one coefficent from ea... | A simulated dataset with tight correlations among distinct groups of features. | Below is the the instruction that describes the task:
### Input:
A simulated dataset with tight correlations among distinct groups of features.
### Response:
def independentlinear60(display=False):
""" A simulated dataset with tight correlations among distinct groups of features.
"""
# set a constant ... |
def find_indices(lst, element):
""" Returns the indices for all occurrences of 'element' in 'lst'.
Args:
lst (list): List to search.
element: Element to find.
Returns:
list: List of indices or values
"""
result = []
offset = -1
while True:
try:
... | Returns the indices for all occurrences of 'element' in 'lst'.
Args:
lst (list): List to search.
element: Element to find.
Returns:
list: List of indices or values | Below is the the instruction that describes the task:
### Input:
Returns the indices for all occurrences of 'element' in 'lst'.
Args:
lst (list): List to search.
element: Element to find.
Returns:
list: List of indices or values
### Response:
def find_indices(lst, element):
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.