code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def levenberg_marquardt(self, start_x=None, damping=1.0e-3, tolerance=1.0e-6):
"""
Optimise value of x using levenberg marquardt
"""
if start_x is None:
start_x = self._analytical_fitter.fit(self._c)
return optimise_levenberg_marquardt(start_x, self._a, self._c, toler... | Optimise value of x using levenberg marquardt | Below is the the instruction that describes the task:
### Input:
Optimise value of x using levenberg marquardt
### Response:
def levenberg_marquardt(self, start_x=None, damping=1.0e-3, tolerance=1.0e-6):
"""
Optimise value of x using levenberg marquardt
"""
if start_x is None:
... |
def write_name(self, name):
"""Writes a domain name to the packet"""
try:
# Find existing instance of this name in packet
#
index = self.names[name]
except KeyError:
# No record of this name already, so write it
# out as normal, record... | Writes a domain name to the packet | Below is the the instruction that describes the task:
### Input:
Writes a domain name to the packet
### Response:
def write_name(self, name):
"""Writes a domain name to the packet"""
try:
# Find existing instance of this name in packet
#
index = self.names[name]... |
def _check_with_label(self, selector, checked, locator=None, allow_label_click=None, visible=None, wait=None,
**kwargs):
"""
Args:
selector (str): The selector for the type of element that should be checked/unchecked.
checked (bool): Whether the element ... | Args:
selector (str): The selector for the type of element that should be checked/unchecked.
checked (bool): Whether the element should be checked.
locator (str, optional): Which element to check.
allow_label_click (bool, optional): Attempt to click the label to toggle st... | Below is the the instruction that describes the task:
### Input:
Args:
selector (str): The selector for the type of element that should be checked/unchecked.
checked (bool): Whether the element should be checked.
locator (str, optional): Which element to check.
allow_... |
def datetime(self):
"""
[datetime.datetime] 当前快照数据的时间戳
"""
try:
dt = self._tick_dict['datetime']
except (KeyError, ValueError):
return datetime.datetime.min
else:
if not isinstance(dt, datetime.datetime):
if dt > 1000000... | [datetime.datetime] 当前快照数据的时间戳 | Below is the the instruction that describes the task:
### Input:
[datetime.datetime] 当前快照数据的时间戳
### Response:
def datetime(self):
"""
[datetime.datetime] 当前快照数据的时间戳
"""
try:
dt = self._tick_dict['datetime']
except (KeyError, ValueError):
return dateti... |
def dispatch(self, request):
"""Takes a request and dispatches its data to a jsonrpc method.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: json output of the corresponding method
:rtype: str
.. versionadded:: 0.1.0
... | Takes a request and dispatches its data to a jsonrpc method.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: json output of the corresponding method
:rtype: str
.. versionadded:: 0.1.0 | Below is the the instruction that describes the task:
### Input:
Takes a request and dispatches its data to a jsonrpc method.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: json output of the corresponding method
:rtype: str
... |
def inv_std_norm_cdf(x):
"""
Inverse cumulative standard Gaussian distribution
Based on Winitzki, S. (2008)
"""
z = 2*x -1
ln1z2 = np.log(1-z**2)
a = 8*(np.pi -3)/(3*np.pi*(4-np.pi))
b = 2/(np.pi * a) + ln1z2/2
inv_erf = np.sign(z) * np.sqrt( np.sqrt(b**2 - ln1z2/a) - b )
return ... | Inverse cumulative standard Gaussian distribution
Based on Winitzki, S. (2008) | Below is the the instruction that describes the task:
### Input:
Inverse cumulative standard Gaussian distribution
Based on Winitzki, S. (2008)
### Response:
def inv_std_norm_cdf(x):
"""
Inverse cumulative standard Gaussian distribution
Based on Winitzki, S. (2008)
"""
z = 2*x -1
ln1z2 ... |
def _wait_new_conf(self):
"""Ask the daemon to drop its configuration and wait for a new one
This overrides the default method from GenericInterface
:return: None
"""
with self.app.conf_lock:
logger.warning("My master Arbiter wants me to wait for a new configuration... | Ask the daemon to drop its configuration and wait for a new one
This overrides the default method from GenericInterface
:return: None | Below is the the instruction that describes the task:
### Input:
Ask the daemon to drop its configuration and wait for a new one
This overrides the default method from GenericInterface
:return: None
### Response:
def _wait_new_conf(self):
"""Ask the daemon to drop its configuration and wa... |
def plotsignal(self,fig=None,saveplot=True,folder=None,figformat='png',**kwargs):
"""
Plots TransitSignal
Calls :func:`TransitSignal.plot`, saves to provided folder.
:param fig: (optional)
Argument for :func:`plotutils.setfig`.
:param saveplot: (optional)
... | Plots TransitSignal
Calls :func:`TransitSignal.plot`, saves to provided folder.
:param fig: (optional)
Argument for :func:`plotutils.setfig`.
:param saveplot: (optional)
Whether to save figure.
:param folder: (optional)
Folder to which to save plot... | Below is the the instruction that describes the task:
### Input:
Plots TransitSignal
Calls :func:`TransitSignal.plot`, saves to provided folder.
:param fig: (optional)
Argument for :func:`plotutils.setfig`.
:param saveplot: (optional)
Whether to save figure.
... |
def generate_static(self, path):
"""
This method generates a valid path to the public folder of the running project
"""
if not path:
return ""
if path[0] == '/':
return "%s?v=%s" % (path, self.version)
return "%s/%s?v=%s" % (self.static, path, se... | This method generates a valid path to the public folder of the running project | Below is the the instruction that describes the task:
### Input:
This method generates a valid path to the public folder of the running project
### Response:
def generate_static(self, path):
"""
This method generates a valid path to the public folder of the running project
"""
if no... |
def detect_sv(align_bam, genome_build, dirs, config):
"""Detect structural variation from discordant aligned pairs.
"""
work_dir = utils.safe_makedir(os.path.join(dirs["work"], "structural"))
pair_stats = shared.calc_paired_insert_stats(align_bam)
fix_bam = remove_nopairs(align_bam, work_dir, config... | Detect structural variation from discordant aligned pairs. | Below is the the instruction that describes the task:
### Input:
Detect structural variation from discordant aligned pairs.
### Response:
def detect_sv(align_bam, genome_build, dirs, config):
"""Detect structural variation from discordant aligned pairs.
"""
work_dir = utils.safe_makedir(os.path.join(di... |
def merge_data(lista_dfs_o_dict, keys_merge=None):
"""
Realiza y devuelve el merge de una lista de pandas DataFrame's (o bien de un diccionario de {key:pd.Dataframe}).
Coge la primera y en ella va añadiendo el resto, de una en una.
Seguramente no sea la mejor opción para realizar la fusión de los datos ... | Realiza y devuelve el merge de una lista de pandas DataFrame's (o bien de un diccionario de {key:pd.Dataframe}).
Coge la primera y en ella va añadiendo el resto, de una en una.
Seguramente no sea la mejor opción para realizar la fusión de los datos de distintos días, pero aguanta bien la
superposición de mu... | Below is the the instruction that describes the task:
### Input:
Realiza y devuelve el merge de una lista de pandas DataFrame's (o bien de un diccionario de {key:pd.Dataframe}).
Coge la primera y en ella va añadiendo el resto, de una en una.
Seguramente no sea la mejor opción para realizar la fusión de los ... |
def _display_controls(self):
"""
Method to pretty print controls.
"""
def print_command(char, info):
char += " " * (10 - len(char))
print("{}\t{}".format(char, info))
print("")
print_command("Keys", "Command")
print_command("q", "reset si... | Method to pretty print controls. | Below is the the instruction that describes the task:
### Input:
Method to pretty print controls.
### Response:
def _display_controls(self):
"""
Method to pretty print controls.
"""
def print_command(char, info):
char += " " * (10 - len(char))
print("{}\t{}"... |
def set_restart_power_failure(enabled):
'''
Set whether or not the computer will automatically restart after a power
failure.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False r... | Set whether or not the computer will automatically restart after a power
failure.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False ... | Below is the the instruction that describes the task:
### Input:
Set whether or not the computer will automatically restart after a power
failure.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
... |
def remove(self, task_name):
""" Removes an existing task directory.
`task_name`
Task name.
Returns ``True`` if removal successful.
"""
try:
task_dir = self._get_task_dir(task_name)
shutil.rmtree(task_dir)
return ... | Removes an existing task directory.
`task_name`
Task name.
Returns ``True`` if removal successful. | Below is the the instruction that describes the task:
### Input:
Removes an existing task directory.
`task_name`
Task name.
Returns ``True`` if removal successful.
### Response:
def remove(self, task_name):
""" Removes an existing task directory.
`task... |
def populate(self, deserialized_txs=None, filename=None, retry=None):
"""Populates the batch with unsaved model instances
from a generator of deserialized objects.
"""
if not deserialized_txs:
raise BatchError("Failed to populate batch. There are no objects to add.")
... | Populates the batch with unsaved model instances
from a generator of deserialized objects. | Below is the the instruction that describes the task:
### Input:
Populates the batch with unsaved model instances
from a generator of deserialized objects.
### Response:
def populate(self, deserialized_txs=None, filename=None, retry=None):
"""Populates the batch with unsaved model instances
... |
def compiler_version():
""" Return the version of the installed solc. """
version_info = subprocess.check_output(['solc', '--version'])
match = re.search(b'^Version: ([0-9a-z.-]+)/', version_info, re.MULTILINE)
if match:
return match.group(1) | Return the version of the installed solc. | Below is the the instruction that describes the task:
### Input:
Return the version of the installed solc.
### Response:
def compiler_version():
""" Return the version of the installed solc. """
version_info = subprocess.check_output(['solc', '--version'])
match = re.search(b'^Version: ([0-9a-z.-]+)/',... |
def add_output(self, key, value, variable_type):
"""Dynamically add output to output_data dictionary to be written to DB later.
This method provides an alternative and more dynamic way to create output variables in an
App. Instead of storing the output data manually and writing all at once the ... | Dynamically add output to output_data dictionary to be written to DB later.
This method provides an alternative and more dynamic way to create output variables in an
App. Instead of storing the output data manually and writing all at once the data can be
stored inline, when it is generated and ... | Below is the the instruction that describes the task:
### Input:
Dynamically add output to output_data dictionary to be written to DB later.
This method provides an alternative and more dynamic way to create output variables in an
App. Instead of storing the output data manually and writing all at ... |
def deprecated_function(func, warning=DEPRECATED_FUNCTION_WARNING):
"""Adds a `DeprecationWarning` to a function
Parameters
----------
func : `callable`
the function to decorate with a `DeprecationWarning`
warning : `str`, optional
the warning to present
Notes
-----
Th... | Adds a `DeprecationWarning` to a function
Parameters
----------
func : `callable`
the function to decorate with a `DeprecationWarning`
warning : `str`, optional
the warning to present
Notes
-----
The final warning message is formatted as ``warning.format(func)``
so you... | Below is the the instruction that describes the task:
### Input:
Adds a `DeprecationWarning` to a function
Parameters
----------
func : `callable`
the function to decorate with a `DeprecationWarning`
warning : `str`, optional
the warning to present
Notes
-----
The fina... |
def enable_global_annotations_decorator(flag = True, retrospective = True):
"""Enables or disables global annotation mode via decorators.
See flag global_annotations_decorator.
In contrast to setting the flag directly, this function provides
a retrospective option. If retrospective is true, this will al... | Enables or disables global annotation mode via decorators.
See flag global_annotations_decorator.
In contrast to setting the flag directly, this function provides
a retrospective option. If retrospective is true, this will also
affect already imported modules, not only future imports. | Below is the the instruction that describes the task:
### Input:
Enables or disables global annotation mode via decorators.
See flag global_annotations_decorator.
In contrast to setting the flag directly, this function provides
a retrospective option. If retrospective is true, this will also
affect ... |
def get_mol_filename(self):
'''Returns mol filename'''
mol_filename = parsers.get_mol_filename(self.__chebi_id)
if mol_filename is None:
mol_filename = parsers.get_mol_filename(self.get_parent_id())
if mol_filename is None:
for parent_or_child_id in self.__get_a... | Returns mol filename | Below is the the instruction that describes the task:
### Input:
Returns mol filename
### Response:
def get_mol_filename(self):
'''Returns mol filename'''
mol_filename = parsers.get_mol_filename(self.__chebi_id)
if mol_filename is None:
mol_filename = parsers.get_mol_filename(s... |
def create_metadata_response(self, uri, http_method='GET', body=None,
headers=None):
"""Create metadata response
"""
headers = {
'Content-Type': 'application/json'
}
return headers, json.dumps(self.claims), 200 | Create metadata response | Below is the the instruction that describes the task:
### Input:
Create metadata response
### Response:
def create_metadata_response(self, uri, http_method='GET', body=None,
headers=None):
"""Create metadata response
"""
headers = {
'Content-Type... |
def logexception(self, logger=None):
'''
calls exception method on a loger and prints the log to stdout
logger is set in the cfg
#Todo more details here on the cfg etc
:param logger:
:return:
'''
traceback.print_exc()
if logger:
logger... | calls exception method on a loger and prints the log to stdout
logger is set in the cfg
#Todo more details here on the cfg etc
:param logger:
:return: | Below is the the instruction that describes the task:
### Input:
calls exception method on a loger and prints the log to stdout
logger is set in the cfg
#Todo more details here on the cfg etc
:param logger:
:return:
### Response:
def logexception(self, logger=None):
'''
... |
def _handle_post(self):
"""
An OCSP POST request contains the DER encoded OCSP request in the HTTP
request body.
"""
der = request.body.read()
ocsp_request = self._parse_ocsp_request(der)
return self._build_http_response(ocsp_request) | An OCSP POST request contains the DER encoded OCSP request in the HTTP
request body. | Below is the the instruction that describes the task:
### Input:
An OCSP POST request contains the DER encoded OCSP request in the HTTP
request body.
### Response:
def _handle_post(self):
"""
An OCSP POST request contains the DER encoded OCSP request in the HTTP
request body.
... |
def aggregate_data(data, T=[0, inf], P=[0, inf], data_ranges=None,
merge="overlap", feature_type=None, impute=False,
scale_center=True):
"""
Aggregates molecular data for model training
Parameters
----------
data: list
density, cpt, and/or viscosity
... | Aggregates molecular data for model training
Parameters
----------
data: list
density, cpt, and/or viscosity
T: array
desired min and max of temperature distribution
P: array
desired min and max of pressure distribution
data_ranges: array
desired min and max of p... | Below is the the instruction that describes the task:
### Input:
Aggregates molecular data for model training
Parameters
----------
data: list
density, cpt, and/or viscosity
T: array
desired min and max of temperature distribution
P: array
desired min and max of pressure... |
def get_vnetwork_dvpgs_input_vcenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_dvpgs = ET.Element("get_vnetwork_dvpgs")
config = get_vnetwork_dvpgs
input = ET.SubElement(get_vnetwork_dvpgs, "input")
vcenter = ET.SubElem... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_vnetwork_dvpgs_input_vcenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_dvpgs = ET.Element("get_vnetwork_dvpgs")
config = ge... |
def _augment_network(self, edge_dict):
"""Given a dictionary of edges (edge id -> feature list), add all of
these to the CoNetwork object
"""
for (vertex0, vertex1), feature_list in edge_dict.items():
edge_obj = Edge(vertex0, vertex1, feature_list)
self.edges[(ver... | Given a dictionary of edges (edge id -> feature list), add all of
these to the CoNetwork object | Below is the the instruction that describes the task:
### Input:
Given a dictionary of edges (edge id -> feature list), add all of
these to the CoNetwork object
### Response:
def _augment_network(self, edge_dict):
"""Given a dictionary of edges (edge id -> feature list), add all of
these to... |
def convolve(data, h, res_g=None, sub_blocks=None):
"""
convolves 1d-3d data with kernel h
data and h can either be numpy arrays or gpu buffer objects (OCLArray,
which must be float32 then)
boundary conditions are clamping to zero at edge.
"""
if not len(data.shape) in [1, 2, 3]:
... | convolves 1d-3d data with kernel h
data and h can either be numpy arrays or gpu buffer objects (OCLArray,
which must be float32 then)
boundary conditions are clamping to zero at edge. | Below is the the instruction that describes the task:
### Input:
convolves 1d-3d data with kernel h
data and h can either be numpy arrays or gpu buffer objects (OCLArray,
which must be float32 then)
boundary conditions are clamping to zero at edge.
### Response:
def convolve(data, h, res_g=None, su... |
def append(self, data, size):
"""
Append user-supplied data to chunk, return resulting chunk size. If the
data would exceeded the available space, it is truncated. If you want to
grow the chunk to accommodate new data, use the zchunk_extend method.
"""
return lib.zchunk_append(self._as_p... | Append user-supplied data to chunk, return resulting chunk size. If the
data would exceeded the available space, it is truncated. If you want to
grow the chunk to accommodate new data, use the zchunk_extend method. | Below is the the instruction that describes the task:
### Input:
Append user-supplied data to chunk, return resulting chunk size. If the
data would exceeded the available space, it is truncated. If you want to
grow the chunk to accommodate new data, use the zchunk_extend method.
### Response:
def append(self, data... |
def run(self):
"""Required by flake8
Will be called after add_options and parse_options.
Yields:
tuple: (int, int, str, type) the tuple used by flake8 to construct a violation
"""
if len(self.filename_checks) == 0:
message = "N401 no configuration found ... | Required by flake8
Will be called after add_options and parse_options.
Yields:
tuple: (int, int, str, type) the tuple used by flake8 to construct a violation | Below is the the instruction that describes the task:
### Input:
Required by flake8
Will be called after add_options and parse_options.
Yields:
tuple: (int, int, str, type) the tuple used by flake8 to construct a violation
### Response:
def run(self):
"""Required by flake8
... |
def mf_aBl(self):
"""
These are the expected log likelihoods (node potentials)
as seen from the discrete states.
"""
mf_aBl = self._mf_aBl = np.zeros((self.T, self.num_states))
ids, dds, eds = self.init_dynamics_distns, self.dynamics_distns, \
self.emission_di... | These are the expected log likelihoods (node potentials)
as seen from the discrete states. | Below is the the instruction that describes the task:
### Input:
These are the expected log likelihoods (node potentials)
as seen from the discrete states.
### Response:
def mf_aBl(self):
"""
These are the expected log likelihoods (node potentials)
as seen from the discrete states.
... |
def delete_panel(self, panel_obj):
"""Delete a panel by '_id'.
Args:
panel_obj(dict)
Returns:
res(pymongo.DeleteResult)
"""
res = self.panel_collection.delete_one({'_id': panel_obj['_id']})
LOG.warning("Deleting panel %s, version %s" % (panel_obj... | Delete a panel by '_id'.
Args:
panel_obj(dict)
Returns:
res(pymongo.DeleteResult) | Below is the the instruction that describes the task:
### Input:
Delete a panel by '_id'.
Args:
panel_obj(dict)
Returns:
res(pymongo.DeleteResult)
### Response:
def delete_panel(self, panel_obj):
"""Delete a panel by '_id'.
Args:
panel_obj(dict... |
def get_response_content_type(self):
"""Figure out what content type will be used in the response."""
if self._best_response_match is None:
settings = get_settings(self.application, force_instance=True)
acceptable = headers.parse_accept(
self.request.headers.get(
... | Figure out what content type will be used in the response. | Below is the the instruction that describes the task:
### Input:
Figure out what content type will be used in the response.
### Response:
def get_response_content_type(self):
"""Figure out what content type will be used in the response."""
if self._best_response_match is None:
settings ... |
def is_winding_consistent(self):
"""
Does the mesh have consistent winding or not.
A mesh with consistent winding has each shared edge
going in an opposite direction from the other in the pair.
Returns
--------
consistent : bool
Is winding is consistent... | Does the mesh have consistent winding or not.
A mesh with consistent winding has each shared edge
going in an opposite direction from the other in the pair.
Returns
--------
consistent : bool
Is winding is consistent or not | Below is the the instruction that describes the task:
### Input:
Does the mesh have consistent winding or not.
A mesh with consistent winding has each shared edge
going in an opposite direction from the other in the pair.
Returns
--------
consistent : bool
Is windi... |
def update(cls, request_response_id, monetary_account_id=None,
amount_responded=None, status=None, address_shipping=None,
address_billing=None, custom_headers=None):
"""
Update the status to accept or reject the RequestResponse.
:type user_id: int
:type mon... | Update the status to accept or reject the RequestResponse.
:type user_id: int
:type monetary_account_id: int
:type request_response_id: int
:param amount_responded: The Amount the user decides to pay.
:type amount_responded: object_.Amount
:param status: The responding s... | Below is the the instruction that describes the task:
### Input:
Update the status to accept or reject the RequestResponse.
:type user_id: int
:type monetary_account_id: int
:type request_response_id: int
:param amount_responded: The Amount the user decides to pay.
:type amo... |
def network_sketch(ax, highlight=None, labels=True, yscaling=1.):
'''
highlight : None or string
if string, then only the label of this population is set and the box is highlighted
'''
name_to_id_mapping={'L6E':(0,0),
'L6I':(0,1),
'L5E':(1,0)... | highlight : None or string
if string, then only the label of this population is set and the box is highlighted | Below is the the instruction that describes the task:
### Input:
highlight : None or string
if string, then only the label of this population is set and the box is highlighted
### Response:
def network_sketch(ax, highlight=None, labels=True, yscaling=1.):
'''
highlight : None or string
... |
def md5(self):
"""
"Hash" of transforms
Returns
-----------
md5 : str
Approximate hash of transforms
"""
result = str(self._updated) + str(self.base_frame)
return result | "Hash" of transforms
Returns
-----------
md5 : str
Approximate hash of transforms | Below is the the instruction that describes the task:
### Input:
"Hash" of transforms
Returns
-----------
md5 : str
Approximate hash of transforms
### Response:
def md5(self):
"""
"Hash" of transforms
Returns
-----------
md5 : str
... |
def send(self, user_id, stock_id, op_user_id=None, device_info=None,
out_trade_no=None):
"""
发放代金券
:param user_id: 用户在公众号下的 openid
:param stock_id: 代金券批次 ID
:param op_user_id: 可选,操作员账号,默认为商户号
:param device_info: 可选,微信支付分配的终端设备号
:param out_trade_no: 可... | 发放代金券
:param user_id: 用户在公众号下的 openid
:param stock_id: 代金券批次 ID
:param op_user_id: 可选,操作员账号,默认为商户号
:param device_info: 可选,微信支付分配的终端设备号
:param out_trade_no: 可选,商户订单号,需保持唯一性,默认自动生成
:return: 返回的结果信息 | Below is the the instruction that describes the task:
### Input:
发放代金券
:param user_id: 用户在公众号下的 openid
:param stock_id: 代金券批次 ID
:param op_user_id: 可选,操作员账号,默认为商户号
:param device_info: 可选,微信支付分配的终端设备号
:param out_trade_no: 可选,商户订单号,需保持唯一性,默认自动生成
:return: 返回的结果信息
### Re... |
def readS8(self, register):
"""Read a signed byte from the specified register."""
result = self.readU8(register)
if result > 127:
result -= 256
return result | Read a signed byte from the specified register. | Below is the the instruction that describes the task:
### Input:
Read a signed byte from the specified register.
### Response:
def readS8(self, register):
"""Read a signed byte from the specified register."""
result = self.readU8(register)
if result > 127:
result -= 256
... |
def save_state(internal_request, state):
"""
Saves all necessary information needed by the UserIdHasher
:type internal_request: satosa.internal_data.InternalRequest
:param internal_request: The request
:param state: The current state
"""
state_data = {"hash_type... | Saves all necessary information needed by the UserIdHasher
:type internal_request: satosa.internal_data.InternalRequest
:param internal_request: The request
:param state: The current state | Below is the the instruction that describes the task:
### Input:
Saves all necessary information needed by the UserIdHasher
:type internal_request: satosa.internal_data.InternalRequest
:param internal_request: The request
:param state: The current state
### Response:
def save_state(intern... |
def get_reply_order_cache_data(comid):
"""
Prepare a representation of the comment ID given as parameter so
that it is suitable for byte ordering in MySQL.
"""
return "%s%s%s%s" % (chr((comid >> 24) % 256), chr((comid >> 16) % 256),
chr((comid >> 8) % 256), chr(comid % 256)) | Prepare a representation of the comment ID given as parameter so
that it is suitable for byte ordering in MySQL. | Below is the the instruction that describes the task:
### Input:
Prepare a representation of the comment ID given as parameter so
that it is suitable for byte ordering in MySQL.
### Response:
def get_reply_order_cache_data(comid):
"""
Prepare a representation of the comment ID given as parameter so
... |
def inet_aton(text):
"""Convert a text format IPv6 address into network format.
@param text: the textual address
@type text: string
@rtype: string
@raises dns.exception.SyntaxError: the text was not properly formatted
"""
#
# Our aim here is not something fast; we just want something t... | Convert a text format IPv6 address into network format.
@param text: the textual address
@type text: string
@rtype: string
@raises dns.exception.SyntaxError: the text was not properly formatted | Below is the the instruction that describes the task:
### Input:
Convert a text format IPv6 address into network format.
@param text: the textual address
@type text: string
@rtype: string
@raises dns.exception.SyntaxError: the text was not properly formatted
### Response:
def inet_aton(text):
... |
def find_files(sequencepath):
"""
Use glob to find all FASTA files in the provided sequence path. NOTE: FASTA files must have an extension such as
.fasta, .fa, or .fas. Extensions of .fsa, .tfa, ect. are not currently supported
:param sequencepath: path of folder containing FASTA genomes
:return: li... | Use glob to find all FASTA files in the provided sequence path. NOTE: FASTA files must have an extension such as
.fasta, .fa, or .fas. Extensions of .fsa, .tfa, ect. are not currently supported
:param sequencepath: path of folder containing FASTA genomes
:return: list of FASTA files | Below is the the instruction that describes the task:
### Input:
Use glob to find all FASTA files in the provided sequence path. NOTE: FASTA files must have an extension such as
.fasta, .fa, or .fas. Extensions of .fsa, .tfa, ect. are not currently supported
:param sequencepath: path of folder containing FA... |
def get_default_values(self):
"""
Make a crude estimation of the alignment using the center of mass
and general C->N orientation.
"""
out = dict(dx=0, dy=0, dz=0, theta=0, phi=0, psi=0)
dx, dy, dz, _ = np.mean(self.coord1 - self.coord2, axis=1)
out['dx'] = dx
... | Make a crude estimation of the alignment using the center of mass
and general C->N orientation. | Below is the the instruction that describes the task:
### Input:
Make a crude estimation of the alignment using the center of mass
and general C->N orientation.
### Response:
def get_default_values(self):
"""
Make a crude estimation of the alignment using the center of mass
and gene... |
def save(self):
"""Convert the scanner to JSON.
Returns
-------
`dict`
JSON data.
"""
data = super().save()
data['expr'] = self.expr.pattern
data['default_end'] = self.default_end
return data | Convert the scanner to JSON.
Returns
-------
`dict`
JSON data. | Below is the the instruction that describes the task:
### Input:
Convert the scanner to JSON.
Returns
-------
`dict`
JSON data.
### Response:
def save(self):
"""Convert the scanner to JSON.
Returns
-------
`dict`
JSON data.
"... |
def _number_type_helper(national_number, metadata):
"""Return the type of the given number against the metadata"""
if not _is_number_matching_desc(national_number, metadata.general_desc):
return PhoneNumberType.UNKNOWN
if _is_number_matching_desc(national_number, metadata.premium_rate):
retu... | Return the type of the given number against the metadata | Below is the the instruction that describes the task:
### Input:
Return the type of the given number against the metadata
### Response:
def _number_type_helper(national_number, metadata):
"""Return the type of the given number against the metadata"""
if not _is_number_matching_desc(national_number, metadat... |
def _calculate_page_index(index, data):
"""Determine the location of a given index in paged data.
Arguments:
index (:py:class:`int`): The overall index.
data: (:py:class:`dict`) The first page of data.
Returns:
:py:class:`tuple`: The location of that index, in the... | Determine the location of a given index in paged data.
Arguments:
index (:py:class:`int`): The overall index.
data: (:py:class:`dict`) The first page of data.
Returns:
:py:class:`tuple`: The location of that index, in the format
``(page, index_in_page)``. | Below is the the instruction that describes the task:
### Input:
Determine the location of a given index in paged data.
Arguments:
index (:py:class:`int`): The overall index.
data: (:py:class:`dict`) The first page of data.
Returns:
:py:class:`tuple`: The location of ... |
def make_hop_info_from_url(url, verify_reachability=None):
"""Build HopInfo object from url.
It allows only telnet and ssh as a valid protocols.
Args:
url (str): The url string describing the node. i.e.
telnet://username@1.1.1.1. The protocol, username and address
portion o... | Build HopInfo object from url.
It allows only telnet and ssh as a valid protocols.
Args:
url (str): The url string describing the node. i.e.
telnet://username@1.1.1.1. The protocol, username and address
portion of url is mandatory. Port and password is optional.
If ... | Below is the the instruction that describes the task:
### Input:
Build HopInfo object from url.
It allows only telnet and ssh as a valid protocols.
Args:
url (str): The url string describing the node. i.e.
telnet://username@1.1.1.1. The protocol, username and address
portio... |
def ParseMessagesRow(self, parser_mediator, query, row, **unused_kwargs):
"""Parses an Messages row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.R... | Parses an Messages row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | Below is the the instruction that describes the task:
### Input:
Parses an Messages row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row.
##... |
def bounding_primitive(self):
"""
The minimum volume primitive (box, sphere, or cylinder) that
bounds the mesh.
Returns
---------
bounding_primitive : trimesh.primitives.Sphere
trimesh.primitives.Box
trimesh.primi... | The minimum volume primitive (box, sphere, or cylinder) that
bounds the mesh.
Returns
---------
bounding_primitive : trimesh.primitives.Sphere
trimesh.primitives.Box
trimesh.primitives.Cylinder
Primitive which bounds th... | Below is the the instruction that describes the task:
### Input:
The minimum volume primitive (box, sphere, or cylinder) that
bounds the mesh.
Returns
---------
bounding_primitive : trimesh.primitives.Sphere
trimesh.primitives.Box
... |
def _setse(self, i):
"""Initialise bitstring with signed exponential-Golomb code for integer i."""
if i > 0:
u = (i * 2) - 1
else:
u = -2 * i
self._setue(u) | Initialise bitstring with signed exponential-Golomb code for integer i. | Below is the the instruction that describes the task:
### Input:
Initialise bitstring with signed exponential-Golomb code for integer i.
### Response:
def _setse(self, i):
"""Initialise bitstring with signed exponential-Golomb code for integer i."""
if i > 0:
u = (i * 2) - 1
els... |
def list_closed_workflow_executions(domain=None, startTimeFilter=None, closeTimeFilter=None, executionFilter=None, closeStatusFilter=None, typeFilter=None, tagFilter=None, nextPageToken=None, maximumPageSize=None, reverseOrder=None):
"""
Returns a list of closed workflow executions in the specified domain that ... | Returns a list of closed workflow executions in the specified domain that meet the filtering criteria. The results may be split into multiple pages. To retrieve subsequent pages, make the call again using the nextPageToken returned by the initial call.
Access Control
You can use IAM policies to control this act... | Below is the the instruction that describes the task:
### Input:
Returns a list of closed workflow executions in the specified domain that meet the filtering criteria. The results may be split into multiple pages. To retrieve subsequent pages, make the call again using the nextPageToken returned by the initial call... |
def send(channel, message, **kwargs):
"""
Site: https://slack.com
API: https://api.slack.com
Desc: real-time messaging
"""
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DBMail/%s" % get_version(),
}
username = from_unicode(kwargs.pop("us... | Site: https://slack.com
API: https://api.slack.com
Desc: real-time messaging | Below is the the instruction that describes the task:
### Input:
Site: https://slack.com
API: https://api.slack.com
Desc: real-time messaging
### Response:
def send(channel, message, **kwargs):
"""
Site: https://slack.com
API: https://api.slack.com
Desc: real-time messaging
"""
head... |
def tail(fpath, n=2, trailing=True):
""" Alias for path_ndir_split """
return path_ndir_split(fpath, n=n, trailing=trailing) | Alias for path_ndir_split | Below is the the instruction that describes the task:
### Input:
Alias for path_ndir_split
### Response:
def tail(fpath, n=2, trailing=True):
""" Alias for path_ndir_split """
return path_ndir_split(fpath, n=n, trailing=trailing) |
def search(self, query, threshold=None):
"""Search the index for items whose key exceeds threshold
similarity to the query string.
:param query: returned items will have at least `threshold` \
similarity to the query string.
:return: list of pairs of (item, similarity) by decre... | Search the index for items whose key exceeds threshold
similarity to the query string.
:param query: returned items will have at least `threshold` \
similarity to the query string.
:return: list of pairs of (item, similarity) by decreasing similarity.
>>> from ngram import NGr... | Below is the the instruction that describes the task:
### Input:
Search the index for items whose key exceeds threshold
similarity to the query string.
:param query: returned items will have at least `threshold` \
similarity to the query string.
:return: list of pairs of (item, sim... |
def connect(self, peer_address):
"""Client-side UDP connection establishment
This method connects this object's underlying socket. It subsequently
performs a handshake if do_handshake_on_connect was set during
initialization.
Arguments:
peer_address - address tuple of s... | Client-side UDP connection establishment
This method connects this object's underlying socket. It subsequently
performs a handshake if do_handshake_on_connect was set during
initialization.
Arguments:
peer_address - address tuple of server peer | Below is the the instruction that describes the task:
### Input:
Client-side UDP connection establishment
This method connects this object's underlying socket. It subsequently
performs a handshake if do_handshake_on_connect was set during
initialization.
Arguments:
peer_add... |
def makedirs(self, dir_name, mode=PERM_DEF, exist_ok=False):
"""Create a leaf Fake directory and create any non-existent
parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directo... | Create a leaf Fake directory and create any non-existent
parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directories) with. This argument defaults to 0o777.
The umask i... | Below is the the instruction that describes the task:
### Input:
Create a leaf Fake directory and create any non-existent
parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directorie... |
def active_status(self, request):
"""
This will only work if you have django-celery installed (for now).
In case you only need to work with status codes to find out if the
workers are up or not.
This will only work if we assume our db only contains "active workers".
To us... | This will only work if you have django-celery installed (for now).
In case you only need to work with status codes to find out if the
workers are up or not.
This will only work if we assume our db only contains "active workers".
To use this feature, you must ensure you use only named wor... | Below is the the instruction that describes the task:
### Input:
This will only work if you have django-celery installed (for now).
In case you only need to work with status codes to find out if the
workers are up or not.
This will only work if we assume our db only contains "active workers"... |
def weight(self):
"""
Current weight of the Node (with respect to the parent).
"""
if self.root.stale:
self.root.update(self.root.now, None)
return self._weight | Current weight of the Node (with respect to the parent). | Below is the the instruction that describes the task:
### Input:
Current weight of the Node (with respect to the parent).
### Response:
def weight(self):
"""
Current weight of the Node (with respect to the parent).
"""
if self.root.stale:
self.root.update(self.root.now, ... |
def for_point(cls, point, zoom):
"""Creates a tile for given point"""
latitude, longitude = point.latitude_longitude
return cls.for_latitude_longitude(latitude=latitude, longitude=longitude, zoom=zoom) | Creates a tile for given point | Below is the the instruction that describes the task:
### Input:
Creates a tile for given point
### Response:
def for_point(cls, point, zoom):
"""Creates a tile for given point"""
latitude, longitude = point.latitude_longitude
return cls.for_latitude_longitude(latitude=latitude, longitude=l... |
def get_page_as_pdf(self, page_id):
"""
Export page as standard pdf exporter
:param page_id: Page ID
:return: PDF File
"""
headers = self.form_token_headers
url = 'spaces/flyingpdf/pdfpageexport.action?pageId={pageId}'.format(pageId=page_id)
return self.ge... | Export page as standard pdf exporter
:param page_id: Page ID
:return: PDF File | Below is the the instruction that describes the task:
### Input:
Export page as standard pdf exporter
:param page_id: Page ID
:return: PDF File
### Response:
def get_page_as_pdf(self, page_id):
"""
Export page as standard pdf exporter
:param page_id: Page ID
:return:... |
def get_device_type(device_type=0):
"""Return the device type from a device_type list."""
device_types = {
0: "Unknown",
1: "Classic - BR/EDR devices",
2: "Low Energy - LE-only",
3: "Dual Mode - BR/EDR/LE"
}
if device_type in [0, 1, 2, 3]:
return_value = device_ty... | Return the device type from a device_type list. | Below is the the instruction that describes the task:
### Input:
Return the device type from a device_type list.
### Response:
def get_device_type(device_type=0):
"""Return the device type from a device_type list."""
device_types = {
0: "Unknown",
1: "Classic - BR/EDR devices",
2: "... |
def groupby(self, *args, **kwargs):
"""Takes the same parameters as groupby on DataFrame.
Like with groupby on DataFrame disabling sorting will result in an
even larger performance improvement. This returns a Sparkling Pandas
L{GroupBy} object which supports many of the same operations a... | Takes the same parameters as groupby on DataFrame.
Like with groupby on DataFrame disabling sorting will result in an
even larger performance improvement. This returns a Sparkling Pandas
L{GroupBy} object which supports many of the same operations as regular
GroupBy but not all. | Below is the the instruction that describes the task:
### Input:
Takes the same parameters as groupby on DataFrame.
Like with groupby on DataFrame disabling sorting will result in an
even larger performance improvement. This returns a Sparkling Pandas
L{GroupBy} object which supports many of... |
def plot(x, y, z, ax=None, **kwargs):
r"""
Plot iso-probability mass function, converted to sigmas.
Parameters
----------
x, y, z : numpy arrays
Same as arguments to :func:`matplotlib.pyplot.contour`
ax: axes object, optional
:class:`matplotlib.axes._subplots.AxesSubplot` to pl... | r"""
Plot iso-probability mass function, converted to sigmas.
Parameters
----------
x, y, z : numpy arrays
Same as arguments to :func:`matplotlib.pyplot.contour`
ax: axes object, optional
:class:`matplotlib.axes._subplots.AxesSubplot` to plot the contours
onto. If unsupplie... | Below is the the instruction that describes the task:
### Input:
r"""
Plot iso-probability mass function, converted to sigmas.
Parameters
----------
x, y, z : numpy arrays
Same as arguments to :func:`matplotlib.pyplot.contour`
ax: axes object, optional
:class:`matplotlib.axes._... |
def set_cpu_affinity(n, process_ids, actual=not Conf.TESTING):
"""
Sets the cpu affinity for the supplied processes.
Requires the optional psutil module.
:param int n: affinity
:param list process_ids: a list of pids
:param bool actual: Test workaround for Travis not supporting cpu affinity
... | Sets the cpu affinity for the supplied processes.
Requires the optional psutil module.
:param int n: affinity
:param list process_ids: a list of pids
:param bool actual: Test workaround for Travis not supporting cpu affinity | Below is the the instruction that describes the task:
### Input:
Sets the cpu affinity for the supplied processes.
Requires the optional psutil module.
:param int n: affinity
:param list process_ids: a list of pids
:param bool actual: Test workaround for Travis not supporting cpu affinity
### Respon... |
def retrieve(self, request, project, pk=None):
"""
Returns a job_log_url object given its ID
"""
log = JobLog.objects.get(id=pk)
return Response(self._log_as_dict(log)) | Returns a job_log_url object given its ID | Below is the the instruction that describes the task:
### Input:
Returns a job_log_url object given its ID
### Response:
def retrieve(self, request, project, pk=None):
"""
Returns a job_log_url object given its ID
"""
log = JobLog.objects.get(id=pk)
return Response(self._log... |
def get_object_query_dict(self):
"""returns objects keys according to self.object_query_code
which can be json encoded queryset filter dict or key=value set
in the following format: ```"key=val, key2 = val2 , key3= value with spaces"```
Returns:
(dict): Queryset filtering ... | returns objects keys according to self.object_query_code
which can be json encoded queryset filter dict or key=value set
in the following format: ```"key=val, key2 = val2 , key3= value with spaces"```
Returns:
(dict): Queryset filtering dicqt | Below is the the instruction that describes the task:
### Input:
returns objects keys according to self.object_query_code
which can be json encoded queryset filter dict or key=value set
in the following format: ```"key=val, key2 = val2 , key3= value with spaces"```
Returns:
(d... |
def requeue(self, queue=None, retry_count=0):
""" Requeues the current job. Doesn't interrupt it """
if not queue:
if not self.data or not self.data.get("queue"):
self.fetch(full_data={"_id": 0, "queue": 1, "path": 1})
queue = self.data["queue"]
self._sa... | Requeues the current job. Doesn't interrupt it | Below is the the instruction that describes the task:
### Input:
Requeues the current job. Doesn't interrupt it
### Response:
def requeue(self, queue=None, retry_count=0):
""" Requeues the current job. Doesn't interrupt it """
if not queue:
if not self.data or not self.data.get("queue"... |
def collect_github_config():
"""
Try load Github configuration such as usernames from the local or global git config
"""
github_config = {}
for field in ["user", "token"]:
try:
github_config[field] = subprocess.check_output(["git", "config", "github.{}".format(field)]).decode('utf-8').strip()
except (OSErro... | Try load Github configuration such as usernames from the local or global git config | Below is the the instruction that describes the task:
### Input:
Try load Github configuration such as usernames from the local or global git config
### Response:
def collect_github_config():
"""
Try load Github configuration such as usernames from the local or global git config
"""
github_config = {}
for fie... |
def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
... | :param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return: | Below is the the instruction that describes the task:
### Input:
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
### Response:
def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param dat... |
def _return_wrapper(fits, return_all, start, trace):
"""If the user wants to get all of the models back, this will
return a list of the ARIMA models, otherwise it will just return
the model. If this is called from the end of the function, ``fits``
will already be a list.
We *know* that if a functio... | If the user wants to get all of the models back, this will
return a list of the ARIMA models, otherwise it will just return
the model. If this is called from the end of the function, ``fits``
will already be a list.
We *know* that if a function call makes it here, ``fits`` is NOT None
or it would h... | Below is the the instruction that describes the task:
### Input:
If the user wants to get all of the models back, this will
return a list of the ARIMA models, otherwise it will just return
the model. If this is called from the end of the function, ``fits``
will already be a list.
We *know* that if ... |
def get_pipeline_inputs(job, input_flag, input_file):
"""
Get the input file from s3 or disk, untargz if necessary and then write to file job store.
:param job: job
:param str input_flag: The name of the flag
:param str input_file: The value passed in the config file
:return: The jobstore ID for... | Get the input file from s3 or disk, untargz if necessary and then write to file job store.
:param job: job
:param str input_flag: The name of the flag
:param str input_file: The value passed in the config file
:return: The jobstore ID for the file | Below is the the instruction that describes the task:
### Input:
Get the input file from s3 or disk, untargz if necessary and then write to file job store.
:param job: job
:param str input_flag: The name of the flag
:param str input_file: The value passed in the config file
:return: The jobstore ID ... |
def _get_or_create_stack(name):
"""Returns a thread local stack uniquified by the given name."""
stack = getattr(_LOCAL_STACKS, name, None)
if stack is None:
stack = []
setattr(_LOCAL_STACKS, name, stack)
return stack | Returns a thread local stack uniquified by the given name. | Below is the the instruction that describes the task:
### Input:
Returns a thread local stack uniquified by the given name.
### Response:
def _get_or_create_stack(name):
"""Returns a thread local stack uniquified by the given name."""
stack = getattr(_LOCAL_STACKS, name, None)
if stack is None:
stack = [... |
def md5(value):
"""
Create MD5
:param value:
:return:
"""
m = hashlib.md5()
m.update(value)
return str(m.hexdigest()) | Create MD5
:param value:
:return: | Below is the the instruction that describes the task:
### Input:
Create MD5
:param value:
:return:
### Response:
def md5(value):
"""
Create MD5
:param value:
:return:
"""
m = hashlib.md5()
m.update(value)
return str(m.hexdigest()) |
def register_instance(self, instance, allow_dotted_names=False):
"""Registers an instance to respond to XML-RPC requests.
Only one instance can be installed at a time.
If the registered instance has a _dispatch method then that
method will be called with the name of the XML-RPC method ... | Registers an instance to respond to XML-RPC requests.
Only one instance can be installed at a time.
If the registered instance has a _dispatch method then that
method will be called with the name of the XML-RPC method and
its parameters as a tuple
e.g. instance._dispatch('add',... | Below is the the instruction that describes the task:
### Input:
Registers an instance to respond to XML-RPC requests.
Only one instance can be installed at a time.
If the registered instance has a _dispatch method then that
method will be called with the name of the XML-RPC method and
... |
def get_snapshots(self):
"""
Returns a list of all completed snapshots for this volume ID.
"""
ec2 = self.get_ec2_connection()
rs = ec2.get_all_snapshots()
all_vols = [self.volume_id] + self.past_volume_ids
snaps = []
for snapshot in rs:
if sna... | Returns a list of all completed snapshots for this volume ID. | Below is the the instruction that describes the task:
### Input:
Returns a list of all completed snapshots for this volume ID.
### Response:
def get_snapshots(self):
"""
Returns a list of all completed snapshots for this volume ID.
"""
ec2 = self.get_ec2_connection()
rs = ec... |
def stats(self):
"""The current status of the positions.
Returns
-------
stats : PositionStats
The current stats position stats.
Notes
-----
This is cached, repeated access will not recompute the stats until
the stats may have changed.
... | The current status of the positions.
Returns
-------
stats : PositionStats
The current stats position stats.
Notes
-----
This is cached, repeated access will not recompute the stats until
the stats may have changed. | Below is the the instruction that describes the task:
### Input:
The current status of the positions.
Returns
-------
stats : PositionStats
The current stats position stats.
Notes
-----
This is cached, repeated access will not recompute the stats until
... |
def parse_station_table(root):
"""Parse station list XML file."""
stations = [parse_xml_station(elem) for elem in root.findall('station')]
return {st.id: st for st in stations} | Parse station list XML file. | Below is the the instruction that describes the task:
### Input:
Parse station list XML file.
### Response:
def parse_station_table(root):
"""Parse station list XML file."""
stations = [parse_xml_station(elem) for elem in root.findall('station')]
return {st.id: st for st in stations} |
def populate_data_sharing_consent(apps, schema_editor):
"""
Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data.
Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model.
"""
DataSharingConsent = apps.get_model('co... | Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data.
Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model. | Below is the the instruction that describes the task:
### Input:
Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data.
Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model.
### Response:
def populate_data_sharing_consent(a... |
def deregister(cls, attr_name):
"""
De-register an extended property that has been registered with register()
"""
try:
field = cls.get_field_by_fieldname(attr_name)
except InvalidField:
raise ValueError("'%s' is not registered" % attr_name)
if not ... | De-register an extended property that has been registered with register() | Below is the the instruction that describes the task:
### Input:
De-register an extended property that has been registered with register()
### Response:
def deregister(cls, attr_name):
"""
De-register an extended property that has been registered with register()
"""
try:
... |
def _assemble_and_send_request(self):
"""
Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES
ON FedexBaseService AND IS INHERITED.
"""
client = self.client
# Fire off the query.
return c... | Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES
ON FedexBaseService AND IS INHERITED. | Below is the the instruction that describes the task:
### Input:
Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES
ON FedexBaseService AND IS INHERITED.
### Response:
def _assemble_and_send_request(self):
"""
Fire... |
def temp_update(self, params, values):
"""
Context manager to temporarily perform a parameter update (by using the
stack structure). To use:
with state.temp_update(params, values):
# measure the cost or something
state.error
"""
self.p... | Context manager to temporarily perform a parameter update (by using the
stack structure). To use:
with state.temp_update(params, values):
# measure the cost or something
state.error | Below is the the instruction that describes the task:
### Input:
Context manager to temporarily perform a parameter update (by using the
stack structure). To use:
with state.temp_update(params, values):
# measure the cost or something
state.error
### Response:
d... |
def taxTree(taxdict):
"""Return taxonomic Newick tree"""
# the taxonomic dictionary holds the lineage of each ident in
# the same order as the taxonomy
# use hierarchy to construct a taxonomic tree
for rank in taxdict.taxonomy:
current_level = float(taxdict.taxonomy.index(rank))
# g... | Return taxonomic Newick tree | Below is the the instruction that describes the task:
### Input:
Return taxonomic Newick tree
### Response:
def taxTree(taxdict):
"""Return taxonomic Newick tree"""
# the taxonomic dictionary holds the lineage of each ident in
# the same order as the taxonomy
# use hierarchy to construct a taxonom... |
def query_status(self):
'''Query the hub for the status of this command'''
try:
data = self.api_iface._api_get(self.link)
self._update_details(data)
except APIError as e:
print("API error: ")
for key,value in e.data.iteritems:
print... | Query the hub for the status of this command | Below is the the instruction that describes the task:
### Input:
Query the hub for the status of this command
### Response:
def query_status(self):
'''Query the hub for the status of this command'''
try:
data = self.api_iface._api_get(self.link)
self._update_details(data)
... |
def can_create_hierarchy_with_record_types(self, hierarchy_record_types):
"""Tests if this user can create a single ``Hierarchy`` using the desired record types.
While ``HierarchyManager.getHierarchyRecordTypes()`` can be used
to examine which records are supported, this method tests which
... | Tests if this user can create a single ``Hierarchy`` using the desired record types.
While ``HierarchyManager.getHierarchyRecordTypes()`` can be used
to examine which records are supported, this method tests which
record(s) are required for creating a specific ``Hierarchy``.
Providing a... | Below is the the instruction that describes the task:
### Input:
Tests if this user can create a single ``Hierarchy`` using the desired record types.
While ``HierarchyManager.getHierarchyRecordTypes()`` can be used
to examine which records are supported, this method tests which
record(s) ar... |
def paint( self, painter, option, widget ):
"""
Overloads the paint method from QGraphicsPathItem to \
handle custom drawing of the path using this items \
pens and polygons.
:param painter <QPainter>
:param option <QGraphicsItemStyleOption>
... | Overloads the paint method from QGraphicsPathItem to \
handle custom drawing of the path using this items \
pens and polygons.
:param painter <QPainter>
:param option <QGraphicsItemStyleOption>
:param widget <QWidget> | Below is the the instruction that describes the task:
### Input:
Overloads the paint method from QGraphicsPathItem to \
handle custom drawing of the path using this items \
pens and polygons.
:param painter <QPainter>
:param option <QGraphicsItemStyleOptio... |
def explain_template_loading_attempts(app, template, attempts):
"""
This should help developers understand what failed. Mostly the same as
:func:`flask.debughelpers.explain_template_loading_attempts`, except here we've
extended it to support showing what :class:`UnchainedJinjaLoader` is doing.
"""
... | This should help developers understand what failed. Mostly the same as
:func:`flask.debughelpers.explain_template_loading_attempts`, except here we've
extended it to support showing what :class:`UnchainedJinjaLoader` is doing. | Below is the the instruction that describes the task:
### Input:
This should help developers understand what failed. Mostly the same as
:func:`flask.debughelpers.explain_template_loading_attempts`, except here we've
extended it to support showing what :class:`UnchainedJinjaLoader` is doing.
### Response:
d... |
def eigenvectors_left_samples(self):
r""" Samples of the left eigenvectors of the hidden transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :, :] = self._sampled_hmms[i].eigenvectors_left
... | r""" Samples of the left eigenvectors of the hidden transition matrix | Below is the the instruction that describes the task:
### Input:
r""" Samples of the left eigenvectors of the hidden transition matrix
### Response:
def eigenvectors_left_samples(self):
r""" Samples of the left eigenvectors of the hidden transition matrix """
res = np.empty((self.nsamples, self.nst... |
def name(self): # pylint: disable=no-self-use
"""
Name returns user's name or user's email or user_id
:return: best guess of name to use to greet user
"""
if 'lis_person_sourcedid' in self.session:
return self.session['lis_person_sourcedid']
elif 'lis_person_... | Name returns user's name or user's email or user_id
:return: best guess of name to use to greet user | Below is the the instruction that describes the task:
### Input:
Name returns user's name or user's email or user_id
:return: best guess of name to use to greet user
### Response:
def name(self): # pylint: disable=no-self-use
"""
Name returns user's name or user's email or user_id
... |
def os_info():
"""Returns os data.
"""
return {
'uname': dict(platform.uname()._asdict()),
'path': os.environ.get('PATH', '').split(':'),
'shell': os.environ.get('SHELL', '/bin/sh'),
} | Returns os data. | Below is the the instruction that describes the task:
### Input:
Returns os data.
### Response:
def os_info():
"""Returns os data.
"""
return {
'uname': dict(platform.uname()._asdict()),
'path': os.environ.get('PATH', '').split(':'),
'shell': os.environ.get('SHELL', '/bin/sh'),
... |
def safe_request(fct):
''' Return json messages instead of raising errors '''
def inner(*args, **kwargs):
''' decorator '''
try:
_data = fct(*args, **kwargs)
except requests.exceptions.ConnectionError as error:
return {'error': str(error), 'status': 404}
... | Return json messages instead of raising errors | Below is the the instruction that describes the task:
### Input:
Return json messages instead of raising errors
### Response:
def safe_request(fct):
''' Return json messages instead of raising errors '''
def inner(*args, **kwargs):
''' decorator '''
try:
_data = fct(*args, **kwa... |
def resize_dimension(self, dimension, size):
"""
Resize a dimension to a certain size.
It will pad with the underlying HDF5 data sets' fill values (usually
zero) where necessary.
"""
if self.dimensions[dimension] is not None:
raise ValueError("Dimension '%s' ... | Resize a dimension to a certain size.
It will pad with the underlying HDF5 data sets' fill values (usually
zero) where necessary. | Below is the the instruction that describes the task:
### Input:
Resize a dimension to a certain size.
It will pad with the underlying HDF5 data sets' fill values (usually
zero) where necessary.
### Response:
def resize_dimension(self, dimension, size):
"""
Resize a dimension to a ... |
def render_to_response(self, context, indent=None):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context, indent=indent)) | Returns a JSON response containing 'context' as payload | Below is the the instruction that describes the task:
### Input:
Returns a JSON response containing 'context' as payload
### Response:
def render_to_response(self, context, indent=None):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_... |
def _undouble(self, word):
"""Undouble endings -kk, -dd, and -tt.
Parameters
----------
word : str
The word to stem
Returns
-------
str
The word with doubled endings undoubled
"""
if (
len(word) > 1
... | Undouble endings -kk, -dd, and -tt.
Parameters
----------
word : str
The word to stem
Returns
-------
str
The word with doubled endings undoubled | Below is the the instruction that describes the task:
### Input:
Undouble endings -kk, -dd, and -tt.
Parameters
----------
word : str
The word to stem
Returns
-------
str
The word with doubled endings undoubled
### Response:
def _undouble(self... |
def samples(self, gp, Y_metadata=None):
"""
Returns a set of samples of observations based on a given value of the latent variable.
:param gp: latent variable
"""
orig_shape = gp.shape
gp = gp.flatten()
#orig_shape = gp.shape
gp = gp.flatten()
Ysi... | Returns a set of samples of observations based on a given value of the latent variable.
:param gp: latent variable | Below is the the instruction that describes the task:
### Input:
Returns a set of samples of observations based on a given value of the latent variable.
:param gp: latent variable
### Response:
def samples(self, gp, Y_metadata=None):
"""
Returns a set of samples of observations based on a ... |
def range_by_score(self, min, max, num=None, withscores=False):
"""Return all the elements with score >= min and score <= max
(a range query) from the sorted set."""
return self.client.zrangebyscore(self.name, min, max, num=num,
withscores=withscores) | Return all the elements with score >= min and score <= max
(a range query) from the sorted set. | Below is the the instruction that describes the task:
### Input:
Return all the elements with score >= min and score <= max
(a range query) from the sorted set.
### Response:
def range_by_score(self, min, max, num=None, withscores=False):
"""Return all the elements with score >= min and score <= ma... |
def __get_attr(what, type_attr, value_attr, **kwargs):
"""
get the value of a parm
:param what: string parm
:param type_attr: type of parm
:param value_attr:
:param kwargs:
:return: value of the parm
"""
if what in kwargs:
value = int(k... | get the value of a parm
:param what: string parm
:param type_attr: type of parm
:param value_attr:
:param kwargs:
:return: value of the parm | Below is the the instruction that describes the task:
### Input:
get the value of a parm
:param what: string parm
:param type_attr: type of parm
:param value_attr:
:param kwargs:
:return: value of the parm
### Response:
def __get_attr(what, type_attr, value_attr, **kwargs):
... |
def message(self):
''' Override this to provide failure message'''
name = self.__class__.__name__
return "{0} {1}".format(humanize(name),
pp(*self.expectedArgs, **self.expectedKwArgs)) | Override this to provide failure message | Below is the the instruction that describes the task:
### Input:
Override this to provide failure message
### Response:
def message(self):
''' Override this to provide failure message'''
name = self.__class__.__name__
return "{0} {1}".format(humanize(name),
p... |
def _convert_to_spmatrix(operators):
"""Convert an array-like object of operators to a sparse matrix."""
# Lazy import to improve `import odl` time
import scipy.sparse
# Convert ops to sparse representation. This is not trivial because
# operators can be indexable themselves and... | Convert an array-like object of operators to a sparse matrix. | Below is the the instruction that describes the task:
### Input:
Convert an array-like object of operators to a sparse matrix.
### Response:
def _convert_to_spmatrix(operators):
"""Convert an array-like object of operators to a sparse matrix."""
# Lazy import to improve `import odl` time
im... |
def HWProcess(cls, proc, ctx):
"""
Serialize HWProcess instance
:param scope: name scope to prevent name collisions
"""
body = proc.statements
childCtx = ctx.withIndent()
statemets = [cls.asHdl(s, childCtx) for s in body]
proc.name = ctx.scope.checkedName... | Serialize HWProcess instance
:param scope: name scope to prevent name collisions | Below is the the instruction that describes the task:
### Input:
Serialize HWProcess instance
:param scope: name scope to prevent name collisions
### Response:
def HWProcess(cls, proc, ctx):
"""
Serialize HWProcess instance
:param scope: name scope to prevent name collisions
... |
def get_account_from_name(self, name):
"""
Returns the account with the given name.
:type name: string
:param name: The name of the account.
"""
for account in self.accounts:
if account.get_name() == name:
return account
return None | Returns the account with the given name.
:type name: string
:param name: The name of the account. | Below is the the instruction that describes the task:
### Input:
Returns the account with the given name.
:type name: string
:param name: The name of the account.
### Response:
def get_account_from_name(self, name):
"""
Returns the account with the given name.
:type name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.