code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def removeRedundantVerbChains( foundChains, removeOverlapping = True, removeSingleAraAndEi = False ):
''' Eemaldab yleliigsed verbiahelad: ahelad, mis katavad osaliselt v6i t2ielikult
teisi ahelaid (removeOverlapping == True), yhes6nalised 'ei' ja 'รคra' ahelad (kui
removeSingleAraAndEi == True)... | Eemaldab yleliigsed verbiahelad: ahelad, mis katavad osaliselt v6i t2ielikult
teisi ahelaid (removeOverlapping == True), yhes6nalised 'ei' ja 'รคra' ahelad (kui
removeSingleAraAndEi == True);
Yldiselt on nii, et ylekattuvaid ei tohiks palju olla, kuna fraaside laiendamisel
... | Below is the the instruction that describes the task:
### Input:
Eemaldab yleliigsed verbiahelad: ahelad, mis katavad osaliselt v6i t2ielikult
teisi ahelaid (removeOverlapping == True), yhes6nalised 'ei' ja 'รคra' ahelad (kui
removeSingleAraAndEi == True);
Yldiselt on nii, et ... |
def sum(self):
"""
Compute the sum across records.
"""
return self._constructor(self.values.sum(axis=self.baseaxes, keepdims=True)) | Compute the sum across records. | Below is the the instruction that describes the task:
### Input:
Compute the sum across records.
### Response:
def sum(self):
"""
Compute the sum across records.
"""
return self._constructor(self.values.sum(axis=self.baseaxes, keepdims=True)) |
def query(
self, queryEngine, query_str, vendorSpecific=None, do_post=False, **kwargs
):
"""See Also: queryResponse()
Args:
queryEngine:
query_str:
vendorSpecific:
do_post:
**kwargs:
Returns:
"""
response = self.que... | See Also: queryResponse()
Args:
queryEngine:
query_str:
vendorSpecific:
do_post:
**kwargs:
Returns: | Below is the the instruction that describes the task:
### Input:
See Also: queryResponse()
Args:
queryEngine:
query_str:
vendorSpecific:
do_post:
**kwargs:
Returns:
### Response:
def query(
self, queryEngine, query_str, vendorSpecific=None... |
def passageLoop(parent, new_tree, xpath1, xpath2=None, preceding_siblings=False, following_siblings=False):
""" Loop over passages to construct and increment new tree given a parent and XPaths
:param parent: Parent on which to perform xpath
:param new_tree: Parent on which to add nodes
:param xpath1: L... | Loop over passages to construct and increment new tree given a parent and XPaths
:param parent: Parent on which to perform xpath
:param new_tree: Parent on which to add nodes
:param xpath1: List of xpath elements
:type xpath1: [str]
:param xpath2: List of xpath elements
:type xpath2: [str]
... | Below is the the instruction that describes the task:
### Input:
Loop over passages to construct and increment new tree given a parent and XPaths
:param parent: Parent on which to perform xpath
:param new_tree: Parent on which to add nodes
:param xpath1: List of xpath elements
:type xpath1: [str]
... |
def _map(self, event):
"""Extract elements from an operation event and map to a named event."""
description = event.get('description', '')
start_time = google_base.parse_rfc3339_utc_string(
event.get('timestamp', ''))
for name, regex in _EVENT_REGEX_MAP.items():
match = regex.match(descri... | Extract elements from an operation event and map to a named event. | Below is the the instruction that describes the task:
### Input:
Extract elements from an operation event and map to a named event.
### Response:
def _map(self, event):
"""Extract elements from an operation event and map to a named event."""
description = event.get('description', '')
start_time = googl... |
def open(self, dbname=None):
'''
Open database from the path with the name or latest.
If there are no yet databases, create a new implicitly.
:return:
'''
databases = self.list()
if self.is_closed():
self.db_path = os.path.join(self.path, dbname or (d... | Open database from the path with the name or latest.
If there are no yet databases, create a new implicitly.
:return: | Below is the the instruction that describes the task:
### Input:
Open database from the path with the name or latest.
If there are no yet databases, create a new implicitly.
:return:
### Response:
def open(self, dbname=None):
'''
Open database from the path with the name or latest.... |
def main():
"""
Entry point
"""
parser = ArgumentParser()
parser.add_argument("direction",
choices=(
"up", "down", "left", "right",
"next", "prev"
),
help="Direction to put... | Entry point | Below is the the instruction that describes the task:
### Input:
Entry point
### Response:
def main():
"""
Entry point
"""
parser = ArgumentParser()
parser.add_argument("direction",
choices=(
"up", "down", "left", "right",
... |
def start(self):
"""
Start executor with additional checks.
Checks if previous executor isn't running then start process
(executor) and wait until it's started.
:returns: itself
:rtype: Executor
"""
if self.pre_start_check():
# Some other exec... | Start executor with additional checks.
Checks if previous executor isn't running then start process
(executor) and wait until it's started.
:returns: itself
:rtype: Executor | Below is the the instruction that describes the task:
### Input:
Start executor with additional checks.
Checks if previous executor isn't running then start process
(executor) and wait until it's started.
:returns: itself
:rtype: Executor
### Response:
def start(self):
"""
... |
def process_delivery(message, notification):
"""Function to process a delivery notification"""
mail = message['mail']
delivery = message['delivery']
if 'timestamp' in delivery:
delivered_datetime = clean_time(delivery['timestamp'])
else:
delivered_datetime = None
deliveries = [... | Function to process a delivery notification | Below is the the instruction that describes the task:
### Input:
Function to process a delivery notification
### Response:
def process_delivery(message, notification):
"""Function to process a delivery notification"""
mail = message['mail']
delivery = message['delivery']
if 'timestamp' in delivery... |
def check(self):
"""
Compare the :func:`os.stat` for the pam_env style environmnt file
`path` with the previous result `old_st`, which may be :data:`None` if
the previous stat attempt failed. Reload its contents if the file has
changed or appeared since last attempt.
:re... | Compare the :func:`os.stat` for the pam_env style environmnt file
`path` with the previous result `old_st`, which may be :data:`None` if
the previous stat attempt failed. Reload its contents if the file has
changed or appeared since last attempt.
:returns:
New :func:`os.stat... | Below is the the instruction that describes the task:
### Input:
Compare the :func:`os.stat` for the pam_env style environmnt file
`path` with the previous result `old_st`, which may be :data:`None` if
the previous stat attempt failed. Reload its contents if the file has
changed or appeared ... |
def delete(self):
"""Delete the draft."""
response = self.session.request("delete:Message", [ self.message_id ])
self.data = response
return self | Delete the draft. | Below is the the instruction that describes the task:
### Input:
Delete the draft.
### Response:
def delete(self):
"""Delete the draft."""
response = self.session.request("delete:Message", [ self.message_id ])
self.data = response
return self |
def mongodb(line):
'''
>>> import pprint
>>> input_line1 = '2017-08-17T07:56:33.489+0200 I REPL [signalProcessingThread] shutting down replication subsystems'
>>> output_line1 = mongodb(input_line1)
>>> pprint.pprint(output_line1)
{'data': {'component': 'REPL',
'context': '[sig... | >>> import pprint
>>> input_line1 = '2017-08-17T07:56:33.489+0200 I REPL [signalProcessingThread] shutting down replication subsystems'
>>> output_line1 = mongodb(input_line1)
>>> pprint.pprint(output_line1)
{'data': {'component': 'REPL',
'context': '[signalProcessingThread]',
... | Below is the the instruction that describes the task:
### Input:
>>> import pprint
>>> input_line1 = '2017-08-17T07:56:33.489+0200 I REPL [signalProcessingThread] shutting down replication subsystems'
>>> output_line1 = mongodb(input_line1)
>>> pprint.pprint(output_line1)
{'data': {'component': ... |
def fromXml(cls, xparent):
"""
Loads the settings for this dataset to the inputted parent xml.
:param xparent | <xml.etree.ElementTree.Element>
"""
output = cls()
for xentry in xparent:
key = xentry.get('key')
if not key:
... | Loads the settings for this dataset to the inputted parent xml.
:param xparent | <xml.etree.ElementTree.Element> | Below is the the instruction that describes the task:
### Input:
Loads the settings for this dataset to the inputted parent xml.
:param xparent | <xml.etree.ElementTree.Element>
### Response:
def fromXml(cls, xparent):
"""
Loads the settings for this dataset to the inputted pa... |
def _get_action_type(self, action):
'''
Get action type.
:param action:
:return:
'''
action_name = next(iter(action or {'': None}))
if ':' not in action_name:
action_name = '{}:{}'.format(self.CALL_TYPE, action_name)
return action_name.split('... | Get action type.
:param action:
:return: | Below is the the instruction that describes the task:
### Input:
Get action type.
:param action:
:return:
### Response:
def _get_action_type(self, action):
'''
Get action type.
:param action:
:return:
'''
action_name = next(iter(action or {'': None}))... |
def start(self):
"""Start the process with daemonization.
If the process is already started this call should exit with code
ALREADY_RUNNING. Otherwise it must call the 'daemonize' method and then
call 'run'.
"""
if self.pid is not None:
LOG.error(
... | Start the process with daemonization.
If the process is already started this call should exit with code
ALREADY_RUNNING. Otherwise it must call the 'daemonize' method and then
call 'run'. | Below is the the instruction that describes the task:
### Input:
Start the process with daemonization.
If the process is already started this call should exit with code
ALREADY_RUNNING. Otherwise it must call the 'daemonize' method and then
call 'run'.
### Response:
def start(self):
... |
def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5381
for c in s:
h = h * 33 + ord(c)
return h | String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`). | Below is the the instruction that describes the task:
### Input:
String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).
### Response:
def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5... |
def is_middleware(func) -> bool:
"""
test whether it is a middleware
:return: Boolean
"""
if inspect.isfunction(func):
_check = func
_name = func.__name__
else:
_check = func.__call__
_name = func.__class__.__name__
if not inspect.iscoroutinefunction(_check)... | test whether it is a middleware
:return: Boolean | Below is the the instruction that describes the task:
### Input:
test whether it is a middleware
:return: Boolean
### Response:
def is_middleware(func) -> bool:
"""
test whether it is a middleware
:return: Boolean
"""
if inspect.isfunction(func):
_check = func
_name = func.... |
def stage_tc_batch(self, owner, staging_data):
"""Stage data in ThreatConnect Platform using batch API.
Args:
owner (str): The ThreatConnect owner to submit batch job.
staging_data (dict): A dict of ThreatConnect batch data.
"""
batch = self.tcex.batch(owner)
... | Stage data in ThreatConnect Platform using batch API.
Args:
owner (str): The ThreatConnect owner to submit batch job.
staging_data (dict): A dict of ThreatConnect batch data. | Below is the the instruction that describes the task:
### Input:
Stage data in ThreatConnect Platform using batch API.
Args:
owner (str): The ThreatConnect owner to submit batch job.
staging_data (dict): A dict of ThreatConnect batch data.
### Response:
def stage_tc_batch(self, own... |
def plot_cap_exposures_longshort(long_exposures, short_exposures, ax=None):
"""
Plots outputs of compute_cap_exposures as area charts
Parameters
----------
long_exposures, short_exposures : arrays
Arrays of long and short market cap exposures (output of
compute_cap_exposures).
"... | Plots outputs of compute_cap_exposures as area charts
Parameters
----------
long_exposures, short_exposures : arrays
Arrays of long and short market cap exposures (output of
compute_cap_exposures). | Below is the the instruction that describes the task:
### Input:
Plots outputs of compute_cap_exposures as area charts
Parameters
----------
long_exposures, short_exposures : arrays
Arrays of long and short market cap exposures (output of
compute_cap_exposures).
### Response:
def plot_... |
def p_namespace(p):
""" asm : NAMESPACE ID
"""
global NAMESPACE
NAMESPACE = normalize_namespace(p[2])
__DEBUG__('Setting namespace to ' + (NAMESPACE.rstrip(DOT) or DOT), level=1) | asm : NAMESPACE ID | Below is the the instruction that describes the task:
### Input:
asm : NAMESPACE ID
### Response:
def p_namespace(p):
""" asm : NAMESPACE ID
"""
global NAMESPACE
NAMESPACE = normalize_namespace(p[2])
__DEBUG__('Setting namespace to ' + (NAMESPACE.rstrip(DOT) or DOT), level=1) |
def get_appstruct(self):
""" return list of tuples keys and values corresponding to this model's
data """
result = []
for k in self._get_keys():
result.append((k, getattr(self, k)))
return result | return list of tuples keys and values corresponding to this model's
data | Below is the the instruction that describes the task:
### Input:
return list of tuples keys and values corresponding to this model's
data
### Response:
def get_appstruct(self):
""" return list of tuples keys and values corresponding to this model's
data """
result = []
for k... |
def _self_referential_fk(klass_model):
"""
Return whether this model has a self ref FK, and the name for the field
"""
for f in klass_model._meta.concrete_fields:
if f.related_model:
if issubclass(klass_model, f.related_model):
return f.attname
return None | Return whether this model has a self ref FK, and the name for the field | Below is the the instruction that describes the task:
### Input:
Return whether this model has a self ref FK, and the name for the field
### Response:
def _self_referential_fk(klass_model):
"""
Return whether this model has a self ref FK, and the name for the field
"""
for f in klass_model._meta.co... |
def parse_command_line() -> Namespace:
"""Parse command line options and set them to ``config``.
This function skips unknown command line options. After parsing options,
set log level and set options in ``tornado.options``.
"""
import tornado.options
parser.parse_known_args(namespace=config)
... | Parse command line options and set them to ``config``.
This function skips unknown command line options. After parsing options,
set log level and set options in ``tornado.options``. | Below is the the instruction that describes the task:
### Input:
Parse command line options and set them to ``config``.
This function skips unknown command line options. After parsing options,
set log level and set options in ``tornado.options``.
### Response:
def parse_command_line() -> Namespace:
""... |
def train(self, data=None, epochs=10, radius0=0, radiusN=1,
radiuscooling="linear",
scale0=0.1, scaleN=0.01, scalecooling="linear"):
"""Train the map on the current data in the Somoclu object.
:param data: Optional parameter to provide training data. It is not
... | Train the map on the current data in the Somoclu object.
:param data: Optional parameter to provide training data. It is not
necessary if the data was added via the method
`update_data`.
:type data: 2D numpy.array of float32.
:param epochs: The number of... | Below is the the instruction that describes the task:
### Input:
Train the map on the current data in the Somoclu object.
:param data: Optional parameter to provide training data. It is not
necessary if the data was added via the method
`update_data`.
:type ... |
def disconnect(self):
"""
Disconnects the tree connection.
"""
if not self._connected:
return
log.info("Session: %s, Tree: %s - Disconnecting from Tree Connect"
% (self.session.username, self.share_name))
req = SMB2TreeDisconnect()
l... | Disconnects the tree connection. | Below is the the instruction that describes the task:
### Input:
Disconnects the tree connection.
### Response:
def disconnect(self):
"""
Disconnects the tree connection.
"""
if not self._connected:
return
log.info("Session: %s, Tree: %s - Disconnecting from Tre... |
def RegisterHasher(cls, hasher_class):
"""Registers a hasher class.
The hasher classes are identified based on their lower case name.
Args:
hasher_class (type): class object of the hasher.
Raises:
KeyError: if hasher class is already set for the corresponding name.
"""
hasher_name... | Registers a hasher class.
The hasher classes are identified based on their lower case name.
Args:
hasher_class (type): class object of the hasher.
Raises:
KeyError: if hasher class is already set for the corresponding name. | Below is the the instruction that describes the task:
### Input:
Registers a hasher class.
The hasher classes are identified based on their lower case name.
Args:
hasher_class (type): class object of the hasher.
Raises:
KeyError: if hasher class is already set for the corresponding name.
... |
def _shorten_render(renderer, max_len):
"""Return a modified that returns the representation of expr, or '...' if
that representation is longer than `max_len`"""
def short_renderer(expr):
res = renderer(expr)
if len(res) > max_len:
return '...'
else:
return r... | Return a modified that returns the representation of expr, or '...' if
that representation is longer than `max_len` | Below is the the instruction that describes the task:
### Input:
Return a modified that returns the representation of expr, or '...' if
that representation is longer than `max_len`
### Response:
def _shorten_render(renderer, max_len):
"""Return a modified that returns the representation of expr, or '...' i... |
def set_chassis_location(location,
host=None,
admin_username=None,
admin_password=None):
'''
Set the location of the chassis.
location
The name of the location to be set on the chassis.
host
The chassis host.
... | Set the location of the chassis.
location
The name of the location to be set on the chassis.
host
The chassis host.
admin_username
The username used to access the chassis.
admin_password
The password used to access the chassis.
CLI Example:
.. code-block:: b... | Below is the the instruction that describes the task:
### Input:
Set the location of the chassis.
location
The name of the location to be set on the chassis.
host
The chassis host.
admin_username
The username used to access the chassis.
admin_password
The password... |
def bootstrap_results(self, init_state):
"""Returns an object with the same type as returned by `one_step`.
Args:
init_state: `Tensor` or Python `list` of `Tensor`s representing the
initial state(s) of the Markov chain(s).
Returns:
kernel_results: A (possibly nested) `tuple`, `namedtup... | Returns an object with the same type as returned by `one_step`.
Args:
init_state: `Tensor` or Python `list` of `Tensor`s representing the
initial state(s) of the Markov chain(s).
Returns:
kernel_results: A (possibly nested) `tuple`, `namedtuple` or `list` of
`Tensor`s representing ... | Below is the the instruction that describes the task:
### Input:
Returns an object with the same type as returned by `one_step`.
Args:
init_state: `Tensor` or Python `list` of `Tensor`s representing the
initial state(s) of the Markov chain(s).
Returns:
kernel_results: A (possibly neste... |
def _map_trajectory(self):
""" Return filepath as a class attribute"""
self.trajectory_map = {}
with open(self.filepath, 'r') as trajectory_file:
with closing(
mmap(
trajectory_file.fileno(), 0,
access=ACCESS_READ)) ... | Return filepath as a class attribute | Below is the the instruction that describes the task:
### Input:
Return filepath as a class attribute
### Response:
def _map_trajectory(self):
""" Return filepath as a class attribute"""
self.trajectory_map = {}
with open(self.filepath, 'r') as trajectory_file:
with closing(
... |
def kill(args):
"""
%prog kill [options] JOBNAMEPAT/JOBIDs
Kill jobs based on JOBNAME pattern matching (case-sensitive)
or list of JOBIDs (comma separated)
Examples:
%prog kill "pyth*" # Use regex
%prog kill 160253,160245,160252 # Use list of job ids
%prog kill all ... | %prog kill [options] JOBNAMEPAT/JOBIDs
Kill jobs based on JOBNAME pattern matching (case-sensitive)
or list of JOBIDs (comma separated)
Examples:
%prog kill "pyth*" # Use regex
%prog kill 160253,160245,160252 # Use list of job ids
%prog kill all # Everyth... | Below is the the instruction that describes the task:
### Input:
%prog kill [options] JOBNAMEPAT/JOBIDs
Kill jobs based on JOBNAME pattern matching (case-sensitive)
or list of JOBIDs (comma separated)
Examples:
%prog kill "pyth*" # Use regex
%prog kill 160253,160245,160252 #... |
def copy(
self,
extractor=None,
needs=None,
store=None,
data_writer=None,
persistence=None,
extractor_args=None):
"""
Use self as a template to build a new feature, replacing
values in kwargs
"""
... | Use self as a template to build a new feature, replacing
values in kwargs | Below is the the instruction that describes the task:
### Input:
Use self as a template to build a new feature, replacing
values in kwargs
### Response:
def copy(
self,
extractor=None,
needs=None,
store=None,
data_writer=None,
persiste... |
def get_save_as_filename(defaultfilename: str,
defaultextension: str,
title: str = "Save As") -> str:
"""
Provides a GUI "Save As" dialogue (via ``tkinter``) and returns the
filename.
"""
root = tkinter.Tk() # create and get Tk topmost window
# ... | Provides a GUI "Save As" dialogue (via ``tkinter``) and returns the
filename. | Below is the the instruction that describes the task:
### Input:
Provides a GUI "Save As" dialogue (via ``tkinter``) and returns the
filename.
### Response:
def get_save_as_filename(defaultfilename: str,
defaultextension: str,
title: str = "Save As") -> str:
... |
def extrusion(target, throat_perimeter='throat.perimeter',
throat_length='throat.length'):
r"""
Calculate surface area for an arbitrary shaped throat give the perimeter
and length.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with... | r"""
Calculate surface area for an arbitrary shaped throat give the perimeter
and length.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessa... | Below is the the instruction that describes the task:
### Input:
r"""
Calculate surface area for an arbitrary shaped throat give the perimeter
and length.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of th... |
def client_status(self, config_path):
"""Get status of client for a project, given path to its config."""
c = self.client_for(config_path)
status = "stopped"
if not c or not c.ensime:
status = 'unloaded'
elif c.ensime.is_ready():
status = 'ready'
e... | Get status of client for a project, given path to its config. | Below is the the instruction that describes the task:
### Input:
Get status of client for a project, given path to its config.
### Response:
def client_status(self, config_path):
"""Get status of client for a project, given path to its config."""
c = self.client_for(config_path)
status = "s... |
def crop(self, top=None, bottom=None, right=None, left=None):
"""Crop image.
:param float top: fraction to crop from the top margin
:param float bottom: fraction to crop from the bottom margin
:param float left: fraction to crop from the left margin
:param float right: f... | Crop image.
:param float top: fraction to crop from the top margin
:param float bottom: fraction to crop from the bottom margin
:param float left: fraction to crop from the left margin
:param float right: fraction to crop from the right margin | Below is the the instruction that describes the task:
### Input:
Crop image.
:param float top: fraction to crop from the top margin
:param float bottom: fraction to crop from the bottom margin
:param float left: fraction to crop from the left margin
:param float right: fract... |
def run(self):
"""Run the log monitor.
This will query Redis once every second to check if there are new log
files to monitor. It will also store those log files in Redis.
"""
while True:
self.update_log_filenames()
self.open_closed_files()
an... | Run the log monitor.
This will query Redis once every second to check if there are new log
files to monitor. It will also store those log files in Redis. | Below is the the instruction that describes the task:
### Input:
Run the log monitor.
This will query Redis once every second to check if there are new log
files to monitor. It will also store those log files in Redis.
### Response:
def run(self):
"""Run the log monitor.
This will... |
def get_interface_detail_output_interface_line_protocol_exception_info(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_de... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_interface_detail_output_interface_line_protocol_exception_info(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_... |
def apply_statusbar_settings(self):
"""Update status bar widgets settings"""
show_status_bar = CONF.get('main', 'show_status_bar')
self.statusBar().setVisible(show_status_bar)
if show_status_bar:
for widget, name in ((self.mem_status, 'memory_usage'),
... | Update status bar widgets settings | Below is the the instruction that describes the task:
### Input:
Update status bar widgets settings
### Response:
def apply_statusbar_settings(self):
"""Update status bar widgets settings"""
show_status_bar = CONF.get('main', 'show_status_bar')
self.statusBar().setVisible(show_status_bar... |
def setDirty(self, state=True):
"""
Flags the connection as being dirty and needing a rebuild.
:param state | <bool>
"""
self._dirty = state
# set if this connection should be visible
if self._inputNode and self._outputNode:
vis = self... | Flags the connection as being dirty and needing a rebuild.
:param state | <bool> | Below is the the instruction that describes the task:
### Input:
Flags the connection as being dirty and needing a rebuild.
:param state | <bool>
### Response:
def setDirty(self, state=True):
"""
Flags the connection as being dirty and needing a rebuild.
:pa... |
def insert_tabs(self, tab, no_tabs=1):
"""Adds no_tabs tabs before table, appends if tab > maxtabs
and marks grid as changed
"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
self.code_array.insert(tab, no_tabs, axis=2)
... | Adds no_tabs tabs before table, appends if tab > maxtabs
and marks grid as changed | Below is the the instruction that describes the task:
### Input:
Adds no_tabs tabs before table, appends if tab > maxtabs
and marks grid as changed
### Response:
def insert_tabs(self, tab, no_tabs=1):
"""Adds no_tabs tabs before table, appends if tab > maxtabs
and marks grid as changed
... |
def cls_slots(self, cls: CLASS_OR_CLASSNAME) -> List[SlotDefinition]:
""" Return the list of slots directly included in the class definition. Includes slots whose
domain is cls -- as declared in slot.domain or class.slots
Does not include slots declared in mixins, apply_to or is_a links
... | Return the list of slots directly included in the class definition. Includes slots whose
domain is cls -- as declared in slot.domain or class.slots
Does not include slots declared in mixins, apply_to or is_a links
@param cls: class name or class definition name
@return: all direct cla... | Below is the the instruction that describes the task:
### Input:
Return the list of slots directly included in the class definition. Includes slots whose
domain is cls -- as declared in slot.domain or class.slots
Does not include slots declared in mixins, apply_to or is_a links
@param cls... |
def precision(self, label=None):
"""
Returns precision or precision for a given label (category) if specified.
"""
if label is None:
return self.call("precision")
else:
return self.call("precision", float(label)) | Returns precision or precision for a given label (category) if specified. | Below is the the instruction that describes the task:
### Input:
Returns precision or precision for a given label (category) if specified.
### Response:
def precision(self, label=None):
"""
Returns precision or precision for a given label (category) if specified.
"""
if label is Non... |
def set_empty_for_all(self, row_column_list):
"""Keep all specified subplots completely empty.
:param row_column_list: a list containing (row, column) tuples to
specify the subplots, or None to indicate *all* subplots.
:type row_column_list: list or None
"""
for row... | Keep all specified subplots completely empty.
:param row_column_list: a list containing (row, column) tuples to
specify the subplots, or None to indicate *all* subplots.
:type row_column_list: list or None | Below is the the instruction that describes the task:
### Input:
Keep all specified subplots completely empty.
:param row_column_list: a list containing (row, column) tuples to
specify the subplots, or None to indicate *all* subplots.
:type row_column_list: list or None
### Response:
d... |
def handle_xmlrpc(self, request_text):
"""Handle a single XML-RPC request"""
response = self._marshaled_dispatch(request_text)
sys.stdout.write('Content-Type: text/xml\n')
sys.stdout.write('Content-Length: %d\n' % len(response))
sys.stdout.write('\n')
sys.stdout.write(... | Handle a single XML-RPC request | Below is the the instruction that describes the task:
### Input:
Handle a single XML-RPC request
### Response:
def handle_xmlrpc(self, request_text):
"""Handle a single XML-RPC request"""
response = self._marshaled_dispatch(request_text)
sys.stdout.write('Content-Type: text/xml\n')
... |
def lp10(self, subset_k, subset_p, weights={}):
"""Force reactions in K above epsilon while minimizing support of P.
This program forces reactions in subset K to attain flux > epsilon
while minimizing the sum of absolute flux values for reactions
in subset P (L1-regularization).
... | Force reactions in K above epsilon while minimizing support of P.
This program forces reactions in subset K to attain flux > epsilon
while minimizing the sum of absolute flux values for reactions
in subset P (L1-regularization). | Below is the the instruction that describes the task:
### Input:
Force reactions in K above epsilon while minimizing support of P.
This program forces reactions in subset K to attain flux > epsilon
while minimizing the sum of absolute flux values for reactions
in subset P (L1-regularization... |
def object_download(self, bucket, key, start_offset=0, byte_count=None):
"""Reads the contents of an object as text.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be read.
start_offset: the start offset of bytes to read.
byte_count: the number... | Reads the contents of an object as text.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be read.
start_offset: the start offset of bytes to read.
byte_count: the number of bytes to read. If None, it reads to the end.
Returns:
The text con... | Below is the the instruction that describes the task:
### Input:
Reads the contents of an object as text.
Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be read.
start_offset: the start offset of bytes to read.
byte_count: the number of bytes t... |
def data(self):
"""Data for packet creation."""
header = struct.pack('>BLB',
4, # version
self.created, # creation
self.algo_id) # public key algorithm ID
oid = util.prefix_len('>B', self.curve_i... | Data for packet creation. | Below is the the instruction that describes the task:
### Input:
Data for packet creation.
### Response:
def data(self):
"""Data for packet creation."""
header = struct.pack('>BLB',
4, # version
self.created, # creation
... |
def _zforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the vertical force
HISTORY:
2010-0... | Below is the the instruction that describes the task:
### Input:
NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUT... |
def to_packets(pages, strict=False):
"""Construct a list of packet data from a list of Ogg pages.
If strict is true, the first page must start a new packet,
and the last page must end the last packet.
"""
serial = pages[0].serial
sequence = pages[0].sequence
pac... | Construct a list of packet data from a list of Ogg pages.
If strict is true, the first page must start a new packet,
and the last page must end the last packet. | Below is the the instruction that describes the task:
### Input:
Construct a list of packet data from a list of Ogg pages.
If strict is true, the first page must start a new packet,
and the last page must end the last packet.
### Response:
def to_packets(pages, strict=False):
"""Construct ... |
def __get_host(node, vm_):
'''
Return public IP, private IP, or hostname for the libcloud 'node' object
'''
if __get_ssh_interface(vm_) == 'private_ips' or vm_['external_ip'] is None:
ip_address = node.private_ips[0]
log.info('Salt node data. Private_ip: %s', ip_address)
else:
... | Return public IP, private IP, or hostname for the libcloud 'node' object | Below is the the instruction that describes the task:
### Input:
Return public IP, private IP, or hostname for the libcloud 'node' object
### Response:
def __get_host(node, vm_):
'''
Return public IP, private IP, or hostname for the libcloud 'node' object
'''
if __get_ssh_interface(vm_) == 'private... |
def update_billing_info(self, billing_info):
"""Change this account's billing information to the given `BillingInfo`."""
url = urljoin(self._url, '/billing_info')
response = billing_info.http_request(url, 'PUT', billing_info,
{'Content-Type': 'application/xml; charset=utf-8'})
... | Change this account's billing information to the given `BillingInfo`. | Below is the the instruction that describes the task:
### Input:
Change this account's billing information to the given `BillingInfo`.
### Response:
def update_billing_info(self, billing_info):
"""Change this account's billing information to the given `BillingInfo`."""
url = urljoin(self._url, '/bi... |
def parse_date(date, default=None):
""" Parse a valid date """
if date == "":
if default is not None:
return default
else:
raise Exception("Unknown format for " + date)
for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H... | Parse a valid date | Below is the the instruction that describes the task:
### Input:
Parse a valid date
### Response:
def parse_date(date, default=None):
""" Parse a valid date """
if date == "":
if default is not None:
return default
else:
raise Exception("Unknown format for " + date)
... |
def list_tags(self, pattern: str = None) -> typing.List[str]:
"""
Returns list of tags, optionally matching "pattern"
:param pattern: optional pattern to filter results
:type pattern: str
:return: existing tags
:rtype: list of str
"""
tags: typing.List[st... | Returns list of tags, optionally matching "pattern"
:param pattern: optional pattern to filter results
:type pattern: str
:return: existing tags
:rtype: list of str | Below is the the instruction that describes the task:
### Input:
Returns list of tags, optionally matching "pattern"
:param pattern: optional pattern to filter results
:type pattern: str
:return: existing tags
:rtype: list of str
### Response:
def list_tags(self, pattern: str = Non... |
def delete_user(self, user):
"""Delete the given user.
Args:
user (string): User name.
Raises:
requests.HTTPError on failure.
"""
self.service.delete_user(
user, self.url_prefix, self.auth, self.session, self.session_send_opts) | Delete the given user.
Args:
user (string): User name.
Raises:
requests.HTTPError on failure. | Below is the the instruction that describes the task:
### Input:
Delete the given user.
Args:
user (string): User name.
Raises:
requests.HTTPError on failure.
### Response:
def delete_user(self, user):
"""Delete the given user.
Args:
user (stri... |
def atleast(cls, lits, bound=1, top_id=None, encoding=EncType.seqcounter):
"""
This method can be used for creating a CNF encoding of an AtLeastK
constraint, i.e. of :math:`\sum_{i=1}^{n}{x_i}\geq k`. The method
takes 1 mandatory argument ``lits`` and 3 default arguments can ... | This method can be used for creating a CNF encoding of an AtLeastK
constraint, i.e. of :math:`\sum_{i=1}^{n}{x_i}\geq k`. The method
takes 1 mandatory argument ``lits`` and 3 default arguments can be
specified: ``bound``, ``top_id``, and ``encoding``.
:param lits: a list... | Below is the the instruction that describes the task:
### Input:
This method can be used for creating a CNF encoding of an AtLeastK
constraint, i.e. of :math:`\sum_{i=1}^{n}{x_i}\geq k`. The method
takes 1 mandatory argument ``lits`` and 3 default arguments can be
specified: ``bo... |
def _get_supply_array_construct(self):
""" Returns a construct for an array of power supply data.
"""
bus_no = integer.setResultsName("bus_no")
s_rating = real.setResultsName("s_rating") # MVA
p_direction = real.setResultsName("p_direction") # CPF
p_bid_max = real.setResu... | Returns a construct for an array of power supply data. | Below is the the instruction that describes the task:
### Input:
Returns a construct for an array of power supply data.
### Response:
def _get_supply_array_construct(self):
""" Returns a construct for an array of power supply data.
"""
bus_no = integer.setResultsName("bus_no")
s_rat... |
def processRequest(self, request: Request, frm: str):
"""
Handle a REQUEST from the client.
If the request has already been executed, the node re-sends the reply to
the client. Otherwise, the node acknowledges the client request, adds it
to its list of client requests, and sends ... | Handle a REQUEST from the client.
If the request has already been executed, the node re-sends the reply to
the client. Otherwise, the node acknowledges the client request, adds it
to its list of client requests, and sends a PROPAGATE to the
remaining nodes.
:param request: the R... | Below is the the instruction that describes the task:
### Input:
Handle a REQUEST from the client.
If the request has already been executed, the node re-sends the reply to
the client. Otherwise, the node acknowledges the client request, adds it
to its list of client requests, and sends a PRO... |
def clean(self, text, **kwargs):
"""This is the master method that cleans all of the filth out of the
dirty dirty ``text``. All keyword arguments to this function are passed
through to the ``Filth.replace_with`` method to fine-tune how the
``Filth`` is cleaned.
"""
if sy... | This is the master method that cleans all of the filth out of the
dirty dirty ``text``. All keyword arguments to this function are passed
through to the ``Filth.replace_with`` method to fine-tune how the
``Filth`` is cleaned. | Below is the the instruction that describes the task:
### Input:
This is the master method that cleans all of the filth out of the
dirty dirty ``text``. All keyword arguments to this function are passed
through to the ``Filth.replace_with`` method to fine-tune how the
``Filth`` is cleaned.
... |
def netdev():
'''
.. versionchanged:: 2016.3.2
Return the network device stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.netdev
'''
def linux_netdev():
'''
linux specific i... | .. versionchanged:: 2016.3.2
Return the network device stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.netdev | Below is the the instruction that describes the task:
### Input:
.. versionchanged:: 2016.3.2
Return the network device stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.netdev
### Response:
def netdev... |
def get_conf_from_module(mod):
"""return configuration from module with defaults no worry about None type
"""
conf = ModuleConfig(CONF_SPEC)
# get imported module
mod = _get_correct_module(mod)
conf.set_module(mod)
# extarct from default object or from module
if hasattr(mod, 'defaul... | return configuration from module with defaults no worry about None type | Below is the the instruction that describes the task:
### Input:
return configuration from module with defaults no worry about None type
### Response:
def get_conf_from_module(mod):
"""return configuration from module with defaults no worry about None type
"""
conf = ModuleConfig(CONF_SPEC)
# ge... |
def read_from(self, provider, **options):
""" All :class:`Pointer` fields in the `Sequence` read the necessary
number of bytes from the data :class:`Provider` for their referenced
:attr:`~Pointer.data` object. Null pointer are ignored.
:param Provider provider: data :class:`Provider`.
... | All :class:`Pointer` fields in the `Sequence` read the necessary
number of bytes from the data :class:`Provider` for their referenced
:attr:`~Pointer.data` object. Null pointer are ignored.
:param Provider provider: data :class:`Provider`.
:keyword bool nested: if ``True`` all :class:`P... | Below is the the instruction that describes the task:
### Input:
All :class:`Pointer` fields in the `Sequence` read the necessary
number of bytes from the data :class:`Provider` for their referenced
:attr:`~Pointer.data` object. Null pointer are ignored.
:param Provider provider: data :clas... |
def get_default_url():
"""
Grab a default URL from bugzillarc [DEFAULT] url=X
"""
from bugzilla.base import _open_bugzillarc
cfg = _open_bugzillarc()
if cfg:
cfgurl = cfg.defaults().get("url", None)
if cfgurl is not None:
log.debug("bugzillarc: found cli url=%s", cfgu... | Grab a default URL from bugzillarc [DEFAULT] url=X | Below is the the instruction that describes the task:
### Input:
Grab a default URL from bugzillarc [DEFAULT] url=X
### Response:
def get_default_url():
"""
Grab a default URL from bugzillarc [DEFAULT] url=X
"""
from bugzilla.base import _open_bugzillarc
cfg = _open_bugzillarc()
if cfg:
... |
def QA_fetch_get_hkfund_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# ๆธฏ่ก HKMARKET
27 5 ้ฆๆธฏๆๆฐ FH
31 2 ้ฆๆธฏไธปๆฟ KH
48 ... | [summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# ๆธฏ่ก HKMARKET
27 5 ้ฆๆธฏๆๆฐ FH
31 2 ้ฆๆธฏไธปๆฟ KH
48 2 ้ฆๆธฏๅไธๆฟ KG
49 2 ้ฆๆธฏๅบ... | Below is the the instruction that describes the task:
### Input:
[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# ๆธฏ่ก HKMARKET
27 5 ้ฆๆธฏๆๆฐ FH
31 2 ้ฆๆธฏไธปๆฟ KH
... |
def p_expr_new(p):
'expr : NEW class_name_reference ctor_arguments'
p[0] = ast.New(p[2], p[3], lineno=p.lineno(1)) | expr : NEW class_name_reference ctor_arguments | Below is the the instruction that describes the task:
### Input:
expr : NEW class_name_reference ctor_arguments
### Response:
def p_expr_new(p):
'expr : NEW class_name_reference ctor_arguments'
p[0] = ast.New(p[2], p[3], lineno=p.lineno(1)) |
def get_data_blob(self, rawtx):
"""TODO add docstring"""
tx = deserialize.tx(rawtx)
data = control.get_data_blob(tx)
return serialize.data(data) | TODO add docstring | Below is the the instruction that describes the task:
### Input:
TODO add docstring
### Response:
def get_data_blob(self, rawtx):
"""TODO add docstring"""
tx = deserialize.tx(rawtx)
data = control.get_data_blob(tx)
return serialize.data(data) |
def lookupGeoInfo(positions):
"""Looks up lat/lon info with goole given a list
of positions as parsed by parsePositionFile.
Returns google results in form of dicionary
"""
list_data=[]
oldlat=0
oldlon=0
d={}
for pos in positions:
# Only lookup point if it is above threshold
... | Looks up lat/lon info with goole given a list
of positions as parsed by parsePositionFile.
Returns google results in form of dicionary | Below is the the instruction that describes the task:
### Input:
Looks up lat/lon info with goole given a list
of positions as parsed by parsePositionFile.
Returns google results in form of dicionary
### Response:
def lookupGeoInfo(positions):
"""Looks up lat/lon info with goole given a list
of pos... |
def DeleteGRRTempFile(path):
"""Delete a GRR temp file.
To limit possible damage the path must be absolute and either the
file must be within any of the Client.tempdir_roots or the file name
must begin with Client.tempfile_prefix.
Args:
path: path string to file to be deleted.
Raises:
OSError: Pe... | Delete a GRR temp file.
To limit possible damage the path must be absolute and either the
file must be within any of the Client.tempdir_roots or the file name
must begin with Client.tempfile_prefix.
Args:
path: path string to file to be deleted.
Raises:
OSError: Permission denied, or file not found... | Below is the the instruction that describes the task:
### Input:
Delete a GRR temp file.
To limit possible damage the path must be absolute and either the
file must be within any of the Client.tempdir_roots or the file name
must begin with Client.tempfile_prefix.
Args:
path: path string to file to be ... |
def connect_to_nsqd(self, host, port):
"""
Adds a connection to ``nsqd`` at the specified address.
:param host: the address to connect to
:param port: the port to connect to
"""
assert isinstance(host, string_types)
assert isinstance(port, int)
conn = As... | Adds a connection to ``nsqd`` at the specified address.
:param host: the address to connect to
:param port: the port to connect to | Below is the the instruction that describes the task:
### Input:
Adds a connection to ``nsqd`` at the specified address.
:param host: the address to connect to
:param port: the port to connect to
### Response:
def connect_to_nsqd(self, host, port):
"""
Adds a connection to ``nsqd``... |
def delete_change_set(awsclient, change_set_name, stack_name):
"""Delete specified change set. Currently we only use this during
automated regression testing. But we have plans so lets locate this
functionality here
:param awsclient:
:param change_set_name:
:param stack_name:
"""
client... | Delete specified change set. Currently we only use this during
automated regression testing. But we have plans so lets locate this
functionality here
:param awsclient:
:param change_set_name:
:param stack_name: | Below is the the instruction that describes the task:
### Input:
Delete specified change set. Currently we only use this during
automated regression testing. But we have plans so lets locate this
functionality here
:param awsclient:
:param change_set_name:
:param stack_name:
### Response:
def ... |
def IsDerivedFunction(clean_lines, linenum):
"""Check if current line contains an inherited function.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains a function with "override"
virt-specifier.
"""
... | Check if current line contains an inherited function.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains a function with "override"
virt-specifier. | Below is the the instruction that describes the task:
### Input:
Check if current line contains an inherited function.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains a function with "override"
vir... |
def down_ec2(instance_id, region, access_key_id, secret_access_key):
""" shutdown of an existing EC2 instance """
conn = connect_to_ec2(region, access_key_id, secret_access_key)
# get the instance_id from the state file, and stop the instance
instance = conn.stop_instances(instance_ids=instance_id)[0]
... | shutdown of an existing EC2 instance | Below is the the instruction that describes the task:
### Input:
shutdown of an existing EC2 instance
### Response:
def down_ec2(instance_id, region, access_key_id, secret_access_key):
""" shutdown of an existing EC2 instance """
conn = connect_to_ec2(region, access_key_id, secret_access_key)
# get the... |
def cartoon(args):
"""
%prog synteny.py
Generate cartoon illustration of SynFind.
"""
p = OptionParser(cartoon.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="10x7")
fig = plt.figure(1, (iopts.w, iopts.h))
root = fig.add_axes([0, 0, 1, 1])
# Panel A
A = Cartoon... | %prog synteny.py
Generate cartoon illustration of SynFind. | Below is the the instruction that describes the task:
### Input:
%prog synteny.py
Generate cartoon illustration of SynFind.
### Response:
def cartoon(args):
"""
%prog synteny.py
Generate cartoon illustration of SynFind.
"""
p = OptionParser(cartoon.__doc__)
opts, args, iopts = p.set_i... |
def getRaw(self, instance, **kwargs):
"""Returns raw field value (possible wrapped in BaseUnit)
"""
value = ObjectField.get(self, instance, **kwargs)
# getattr(instance, "Remarks") returns a BaseUnit
if callable(value):
value = value()
return value | Returns raw field value (possible wrapped in BaseUnit) | Below is the the instruction that describes the task:
### Input:
Returns raw field value (possible wrapped in BaseUnit)
### Response:
def getRaw(self, instance, **kwargs):
"""Returns raw field value (possible wrapped in BaseUnit)
"""
value = ObjectField.get(self, instance, **kwargs)
... |
def _try_coerce_args(self, values, other):
"""
Coerce values and other to dtype 'i8'. NaN and NaT convert to
the smallest i8, and will correctly round-trip to NaT if converted
back in _try_coerce_result. values is always ndarray-like, other
may not be
Parameters
... | Coerce values and other to dtype 'i8'. NaN and NaT convert to
the smallest i8, and will correctly round-trip to NaT if converted
back in _try_coerce_result. values is always ndarray-like, other
may not be
Parameters
----------
values : ndarray-like
other : ndarra... | Below is the the instruction that describes the task:
### Input:
Coerce values and other to dtype 'i8'. NaN and NaT convert to
the smallest i8, and will correctly round-trip to NaT if converted
back in _try_coerce_result. values is always ndarray-like, other
may not be
Parameters
... |
def log_results(self, output_path=None, run_id=None):
"""Saves files for the minimization.
Notes
-----
Currently saves a logfile with best individual and a pdb of
the best model.
"""
best_ind = self.halloffame[0]
model_params = self.parse_individual(
... | Saves files for the minimization.
Notes
-----
Currently saves a logfile with best individual and a pdb of
the best model. | Below is the the instruction that describes the task:
### Input:
Saves files for the minimization.
Notes
-----
Currently saves a logfile with best individual and a pdb of
the best model.
### Response:
def log_results(self, output_path=None, run_id=None):
"""Saves files for ... |
def hessian_component(self, index1, index2):
"""Compute the hessian of the energy for one atom pair"""
result = np.zeros((3, 3), float)
if index1 == index2:
for index3 in range(self.numc):
if self.scaling[index1, index3] > 0:
d_1 = 1/self.distances... | Compute the hessian of the energy for one atom pair | Below is the the instruction that describes the task:
### Input:
Compute the hessian of the energy for one atom pair
### Response:
def hessian_component(self, index1, index2):
"""Compute the hessian of the energy for one atom pair"""
result = np.zeros((3, 3), float)
if index1 == index2:
... |
def copy(self):
"""
m.copy() -- Return a 'deep' copy of the motif
"""
a = Motif()
a.__dict__ = self.__dict__.copy()
return a | m.copy() -- Return a 'deep' copy of the motif | Below is the the instruction that describes the task:
### Input:
m.copy() -- Return a 'deep' copy of the motif
### Response:
def copy(self):
"""
m.copy() -- Return a 'deep' copy of the motif
"""
a = Motif()
a.__dict__ = self.__dict__.copy()
return a |
async def fastStreamedQuery(self, url, *, headers=None, verify=True):
""" Send a GET request with short timeout, do not retry, and return streamed response. """
response = await self.session.get(url,
headers=self._buildHeaders(headers),
... | Send a GET request with short timeout, do not retry, and return streamed response. | Below is the the instruction that describes the task:
### Input:
Send a GET request with short timeout, do not retry, and return streamed response.
### Response:
async def fastStreamedQuery(self, url, *, headers=None, verify=True):
""" Send a GET request with short timeout, do not retry, and return streamed re... |
def solver(AA, N_max, symNx = 2, throw_out_modes=False):
""" Constructs the matrix A and the vector b from a timeseries of toy
action-angles AA to solve for the vector x = (J_0,J_1,J_2,S...) where
x contains all Fourier components of the generating function with |n|<N_max """
# Find all integer compone... | Constructs the matrix A and the vector b from a timeseries of toy
action-angles AA to solve for the vector x = (J_0,J_1,J_2,S...) where
x contains all Fourier components of the generating function with |n|<N_max | Below is the the instruction that describes the task:
### Input:
Constructs the matrix A and the vector b from a timeseries of toy
action-angles AA to solve for the vector x = (J_0,J_1,J_2,S...) where
x contains all Fourier components of the generating function with |n|<N_max
### Response:
def solver(AA, N... |
def val_factory(val, datatypes):
"""
return an instance of `val` that is of type `datatype`.
keep track of exceptions so we can produce meaningful error messages.
"""
exceptions = []
for dt in datatypes:
try:
if isinstance(val, dt):
return val
retu... | return an instance of `val` that is of type `datatype`.
keep track of exceptions so we can produce meaningful error messages. | Below is the the instruction that describes the task:
### Input:
return an instance of `val` that is of type `datatype`.
keep track of exceptions so we can produce meaningful error messages.
### Response:
def val_factory(val, datatypes):
"""
return an instance of `val` that is of type `datatype`.
k... |
def _getMemoryBit(cpu, bitbase, bitoffset):
""" Calculate address and bit offset given a base address and a bit offset
relative to that address (in the form of asm operands) """
assert bitbase.type == 'memory'
assert bitbase.size >= bitoffset.size
addr = bitbase.address()
... | Calculate address and bit offset given a base address and a bit offset
relative to that address (in the form of asm operands) | Below is the the instruction that describes the task:
### Input:
Calculate address and bit offset given a base address and a bit offset
relative to that address (in the form of asm operands)
### Response:
def _getMemoryBit(cpu, bitbase, bitoffset):
""" Calculate address and bit offset given a b... |
def detect_volume_shadow_copies(self):
"""Method to call vshadowmount and mount NTFS volume shadow copies.
:return: iterable with the :class:`Volume` objects of the VSS
:raises CommandNotFoundError: if the underlying command does not exist
:raises SubSystemError: if the underlying comma... | Method to call vshadowmount and mount NTFS volume shadow copies.
:return: iterable with the :class:`Volume` objects of the VSS
:raises CommandNotFoundError: if the underlying command does not exist
:raises SubSystemError: if the underlying command fails
:raises NoMountpointAvailableErro... | Below is the the instruction that describes the task:
### Input:
Method to call vshadowmount and mount NTFS volume shadow copies.
:return: iterable with the :class:`Volume` objects of the VSS
:raises CommandNotFoundError: if the underlying command does not exist
:raises SubSystemError: if t... |
def format(self, vertices):
"""Format instance to dump
vertices is dict of name to Vertex
"""
index = ' '.join(str(vertices[vn].index) for vn in self.vnames)
vcom = ' '.join(self.vnames) # for comment
return 'hex ({0:s}) {2:s} ({1[0]:d} {1[1]:d} {1[2]:d}) '\
... | Format instance to dump
vertices is dict of name to Vertex | Below is the the instruction that describes the task:
### Input:
Format instance to dump
vertices is dict of name to Vertex
### Response:
def format(self, vertices):
"""Format instance to dump
vertices is dict of name to Vertex
"""
index = ' '.join(str(vertices[vn].index) fo... |
def get_context_data(self, **kwargs):
""" Returns the context data to provide to the template. """
context = super().get_context_data(**kwargs)
post = self.object
topic = post.topic
# Handles the case when a poll is associated to the topic.
try:
if hasattr(t... | Returns the context data to provide to the template. | Below is the the instruction that describes the task:
### Input:
Returns the context data to provide to the template.
### Response:
def get_context_data(self, **kwargs):
""" Returns the context data to provide to the template. """
context = super().get_context_data(**kwargs)
post = self.ob... |
def get_mac_dot_app_dir(directory):
"""Returns parent directory of mac .app
Args:
directory (str): Current directory
Returns:
(str): Parent directory of mac .app
"""
return os.path.dirname(os.path.dirname(os.path.dirname(directory))) | Returns parent directory of mac .app
Args:
directory (str): Current directory
Returns:
(str): Parent directory of mac .app | Below is the the instruction that describes the task:
### Input:
Returns parent directory of mac .app
Args:
directory (str): Current directory
Returns:
(str): Parent directory of mac .app
### Response:
def get_mac_dot_app_dir(directory):
"""Returns parent directory of mac .app
Ar... |
def checkCorpNums(self, MemberCorpNum, CorpNumList):
""" ํดํ์
์กฐํ ๋๋ ํ์ธ, ์ต๋ 1000๊ฑด
args
MemberCorpNum : ํ๋นํ์ ์ฌ์
์๋ฒํธ
CorpNumList : ์กฐํํ ์ฌ์
์๋ฒํธ ๋ฐฐ์ด
return
ํดํ์
์ ๋ณด Object as List
raise
PopbillException
"""
if ... | ํดํ์
์กฐํ ๋๋ ํ์ธ, ์ต๋ 1000๊ฑด
args
MemberCorpNum : ํ๋นํ์ ์ฌ์
์๋ฒํธ
CorpNumList : ์กฐํํ ์ฌ์
์๋ฒํธ ๋ฐฐ์ด
return
ํดํ์
์ ๋ณด Object as List
raise
PopbillException | Below is the the instruction that describes the task:
### Input:
ํดํ์
์กฐํ ๋๋ ํ์ธ, ์ต๋ 1000๊ฑด
args
MemberCorpNum : ํ๋นํ์ ์ฌ์
์๋ฒํธ
CorpNumList : ์กฐํํ ์ฌ์
์๋ฒํธ ๋ฐฐ์ด
return
ํดํ์
์ ๋ณด Object as List
raise
PopbillException
### Response:
def ... |
def SLH_to_qutip(slh, full_space=None, time_symbol=None,
convert_as='pyfunc'):
"""Generate and return QuTiP representation matrices for the Hamiltonian
and the collapse operators. Any inhomogeneities in the Lindblad operators
(resulting from coherent drives) will be moved into the Hamiltoni... | Generate and return QuTiP representation matrices for the Hamiltonian
and the collapse operators. Any inhomogeneities in the Lindblad operators
(resulting from coherent drives) will be moved into the Hamiltonian, cf.
:func:`~qnet.algebra.circuit_algebra.move_drive_to_H`.
Args:
slh (SLH): The SL... | Below is the the instruction that describes the task:
### Input:
Generate and return QuTiP representation matrices for the Hamiltonian
and the collapse operators. Any inhomogeneities in the Lindblad operators
(resulting from coherent drives) will be moved into the Hamiltonian, cf.
:func:`~qnet.algebra.c... |
def register(self, name, option):
"""Register a new option with the namespace.
Args:
name (str): The name to register the option under.
option (option.Option): The option object to register.
Raises:
TypeError: If the option is not an option.Option ob... | Register a new option with the namespace.
Args:
name (str): The name to register the option under.
option (option.Option): The option object to register.
Raises:
TypeError: If the option is not an option.Option object.
ValueError: If the name is ... | Below is the the instruction that describes the task:
### Input:
Register a new option with the namespace.
Args:
name (str): The name to register the option under.
option (option.Option): The option object to register.
Raises:
TypeError: If the option is ... |
def get_content(self, offset, size):
"""Return the specified number of bytes from the current section."""
return _bfd.section_get_content(self.bfd, self._ptr, offset, size) | Return the specified number of bytes from the current section. | Below is the the instruction that describes the task:
### Input:
Return the specified number of bytes from the current section.
### Response:
def get_content(self, offset, size):
"""Return the specified number of bytes from the current section."""
return _bfd.section_get_content(self.bfd, self._ptr... |
def load_chkpt_vars(model_path):
""" Load all variables from a checkpoint to a dict.
Args:
model_path(str): path to a checkpoint.
Returns:
dict: a name:value dict
"""
model_path = get_checkpoint_path(model_path)
reader = tfv1.train.NewCheckpointReader(model_path)
var_names ... | Load all variables from a checkpoint to a dict.
Args:
model_path(str): path to a checkpoint.
Returns:
dict: a name:value dict | Below is the the instruction that describes the task:
### Input:
Load all variables from a checkpoint to a dict.
Args:
model_path(str): path to a checkpoint.
Returns:
dict: a name:value dict
### Response:
def load_chkpt_vars(model_path):
""" Load all variables from a checkpoint to a d... |
def get_resource_object_doc_lines() -> List[str]:
"""Generate documentation lines for all collected resource objects.
As API documentation is generated we keep a running list of objects used
in request parameters and responses. This section will generate
documentation for each object and provide an in... | Generate documentation lines for all collected resource objects.
As API documentation is generated we keep a running list of objects used
in request parameters and responses. This section will generate
documentation for each object and provide an inline reference in the API
documentation.
:return... | Below is the the instruction that describes the task:
### Input:
Generate documentation lines for all collected resource objects.
As API documentation is generated we keep a running list of objects used
in request parameters and responses. This section will generate
documentation for each object and p... |
def store_file(self, folder, name):
"""Stores the uploaded file in the given path."""
path = os.path.join(folder, name)
length = self.headers['content-length']
with open(path, 'wb') as sample:
sample.write(self.rfile.read(int(length)))
return path | Stores the uploaded file in the given path. | Below is the the instruction that describes the task:
### Input:
Stores the uploaded file in the given path.
### Response:
def store_file(self, folder, name):
"""Stores the uploaded file in the given path."""
path = os.path.join(folder, name)
length = self.headers['content-length']
... |
def for_model(self, model):
"""
QuerySet for all comments for a particular model (either an instance or
a class).
"""
ct = ContentType.objects.get_for_model(model)
qs = self.get_queryset().filter(content_type=ct)
if isinstance(model, models.Model):
qs ... | QuerySet for all comments for a particular model (either an instance or
a class). | Below is the the instruction that describes the task:
### Input:
QuerySet for all comments for a particular model (either an instance or
a class).
### Response:
def for_model(self, model):
"""
QuerySet for all comments for a particular model (either an instance or
a class).
... |
def create(self, name=None, **kwargs):
"""Create a new project.
:param name: The name of the project.
:returns: An instance of the newly create project.
:rtype: renku.models.projects.Project
"""
data = self._client.api.create_project({'name': name})
return self.M... | Create a new project.
:param name: The name of the project.
:returns: An instance of the newly create project.
:rtype: renku.models.projects.Project | Below is the the instruction that describes the task:
### Input:
Create a new project.
:param name: The name of the project.
:returns: An instance of the newly create project.
:rtype: renku.models.projects.Project
### Response:
def create(self, name=None, **kwargs):
"""Create a new... |
def get_counter(self, transport, bucket, key, r=None, pr=None,
basic_quorum=None, notfound_ok=None):
"""get_counter(bucket, key, r=None, pr=None, basic_quorum=None,\
notfound_ok=None)
Gets the value of a counter.
.. deprecated:: 2.1.0 (Riak 2.0) Riak ... | get_counter(bucket, key, r=None, pr=None, basic_quorum=None,\
notfound_ok=None)
Gets the value of a counter.
.. deprecated:: 2.1.0 (Riak 2.0) Riak 1.4-style counters are
deprecated in favor of the :class:`~riak.datatypes.Counter`
datatype.
.. note:... | Below is the the instruction that describes the task:
### Input:
get_counter(bucket, key, r=None, pr=None, basic_quorum=None,\
notfound_ok=None)
Gets the value of a counter.
.. deprecated:: 2.1.0 (Riak 2.0) Riak 1.4-style counters are
deprecated in favor of the :c... |
def visible_width(string):
"""Get the visible width of a unicode string.
Some CJK unicode characters are more than one byte unlike ASCII and latin unicode characters.
From: https://github.com/Robpol86/terminaltables/pull/9
:param str string: String to measure.
:return: String's width.
:rtype... | Get the visible width of a unicode string.
Some CJK unicode characters are more than one byte unlike ASCII and latin unicode characters.
From: https://github.com/Robpol86/terminaltables/pull/9
:param str string: String to measure.
:return: String's width.
:rtype: int | Below is the the instruction that describes the task:
### Input:
Get the visible width of a unicode string.
Some CJK unicode characters are more than one byte unlike ASCII and latin unicode characters.
From: https://github.com/Robpol86/terminaltables/pull/9
:param str string: String to measure.
... |
def _fix_sitk_bug(path, metadata):
"""There is a bug in simple ITK for Z axis in 3D images. This is a fix.
:param path: path to dicom file to read
:param metadata: metadata to correct
:return: corrected metadata
"""
ds = dicom.read_file(path)
try:
met... | There is a bug in simple ITK for Z axis in 3D images. This is a fix.
:param path: path to dicom file to read
:param metadata: metadata to correct
:return: corrected metadata | Below is the the instruction that describes the task:
### Input:
There is a bug in simple ITK for Z axis in 3D images. This is a fix.
:param path: path to dicom file to read
:param metadata: metadata to correct
:return: corrected metadata
### Response:
def _fix_sitk_bug(path, metadata):
... |
def check_md5(filename, stored_md5):
"""
Computes the md5 of filename and check if it matches with the supplied
string md5
Input
-----
filename : string
Path to a file.
md5 : string
Known md5 of filename to check against.
"""
computed_md5 = _get_file_md5(filename)
... | Computes the md5 of filename and check if it matches with the supplied
string md5
Input
-----
filename : string
Path to a file.
md5 : string
Known md5 of filename to check against. | Below is the the instruction that describes the task:
### Input:
Computes the md5 of filename and check if it matches with the supplied
string md5
Input
-----
filename : string
Path to a file.
md5 : string
Known md5 of filename to check against.
### Response:
def check_md5(fil... |
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' ... | Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test | Below is the the instruction that describes the task:
### Input:
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.