code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def take(attributes, properties):
"""Returns a property set which include all
properties in 'properties' that have any of 'attributes'."""
assert is_iterable_typed(attributes, basestring)
assert is_iterable_typed(properties, basestring)
result = []
for e in properties:
if b2.util.set.int... | Returns a property set which include all
properties in 'properties' that have any of 'attributes'. | Below is the the instruction that describes the task:
### Input:
Returns a property set which include all
properties in 'properties' that have any of 'attributes'.
### Response:
def take(attributes, properties):
"""Returns a property set which include all
properties in 'properties' that have any of 'at... |
def unzip(file_obj):
"""
Take a path to a zipfile and checks if it is a valid zip file
and returns...
"""
files = []
# TODO: implement try-except here
zip = ZipFile(file_obj)
bad_file = zip.testzip()
if bad_file:
raise Exception('"%s" in the .zip archive is corrupt.' % bad_fi... | Take a path to a zipfile and checks if it is a valid zip file
and returns... | Below is the the instruction that describes the task:
### Input:
Take a path to a zipfile and checks if it is a valid zip file
and returns...
### Response:
def unzip(file_obj):
"""
Take a path to a zipfile and checks if it is a valid zip file
and returns...
"""
files = []
# TODO: implem... |
def keyPressEvent(self, event):
"""Qt Override."""
key = event.key()
if key in [Qt.Key_Up]:
self._parent.previous_row()
elif key in [Qt.Key_Down]:
self._parent.next_row()
elif key in [Qt.Key_Enter, Qt.Key_Return]:
self._parent.show_edit... | Qt Override. | Below is the the instruction that describes the task:
### Input:
Qt Override.
### Response:
def keyPressEvent(self, event):
"""Qt Override."""
key = event.key()
if key in [Qt.Key_Up]:
self._parent.previous_row()
elif key in [Qt.Key_Down]:
self._parent.n... |
def is_email(potential_email_address):
"""
Check if potential_email_address is a valid e-mail address.
Please note that this function has no false-negatives but many
false-positives. So if it returns that the input is not a valid
e-mail adress, it certainly isn't. If it returns True, it might still... | Check if potential_email_address is a valid e-mail address.
Please note that this function has no false-negatives but many
false-positives. So if it returns that the input is not a valid
e-mail adress, it certainly isn't. If it returns True, it might still be
invalid. For example, the domain could not ... | Below is the the instruction that describes the task:
### Input:
Check if potential_email_address is a valid e-mail address.
Please note that this function has no false-negatives but many
false-positives. So if it returns that the input is not a valid
e-mail adress, it certainly isn't. If it returns Tr... |
def electron_shell_str(shell, shellidx=None):
'''Return a string representing the data for an electron shell
If shellidx (index of the shell) is not None, it will also be printed
'''
am = shell['angular_momentum']
amchar = lut.amint_to_char(am)
amchar = amchar.upper()
shellidx_str = ''
... | Return a string representing the data for an electron shell
If shellidx (index of the shell) is not None, it will also be printed | Below is the the instruction that describes the task:
### Input:
Return a string representing the data for an electron shell
If shellidx (index of the shell) is not None, it will also be printed
### Response:
def electron_shell_str(shell, shellidx=None):
'''Return a string representing the data for an ele... |
def get(self, campaign_id, nick=None):
'''xxxxx.xxxxx.campaign.area.get
===================================
取得一个推广计划的投放地域设置'''
request = TOPRequest('xxxxx.xxxxx.campaign.area.get')
request['campaign_id'] = campaign_id
if nick!=None: request['nick'] = nick
self.cre... | xxxxx.xxxxx.campaign.area.get
===================================
取得一个推广计划的投放地域设置 | Below is the the instruction that describes the task:
### Input:
xxxxx.xxxxx.campaign.area.get
===================================
取得一个推广计划的投放地域设置
### Response:
def get(self, campaign_id, nick=None):
'''xxxxx.xxxxx.campaign.area.get
===================================
取得一个推广... |
def slamdunkOverallRatesPlot (self):
""" Generate the overall rates plot """
pconfig = {
'id': 'overallratesplot',
'title': 'Slamdunk: Overall conversion rates in reads',
'cpswitch': False,
'cpswitch_c_active': False,
'ylab': 'Number of reads'... | Generate the overall rates plot | Below is the the instruction that describes the task:
### Input:
Generate the overall rates plot
### Response:
def slamdunkOverallRatesPlot (self):
""" Generate the overall rates plot """
pconfig = {
'id': 'overallratesplot',
'title': 'Slamdunk: Overall conversion rates in ... |
def _resolve_responses(self):
"""
_resolve_responses
"""
while True:
message = self.res_queue.get()
if message is None:
_logger.debug("_resolve_responses thread is terminated")
return
self.__resolve_responses(message) | _resolve_responses | Below is the the instruction that describes the task:
### Input:
_resolve_responses
### Response:
def _resolve_responses(self):
"""
_resolve_responses
"""
while True:
message = self.res_queue.get()
if message is None:
_logger.debug("_resolve_r... |
def gen_select_list(sig_dic):
'''
For generating List view HTML file for SELECT.
for each item.
'''
view_jushi = '''<span class="label label-primary" style="margin-right:10px">'''
dic_tmp = sig_dic['dic']
for key in dic_tmp.keys():
tmp_str = '''{{% if '{0}' in postinfo.extinfo and p... | For generating List view HTML file for SELECT.
for each item. | Below is the the instruction that describes the task:
### Input:
For generating List view HTML file for SELECT.
for each item.
### Response:
def gen_select_list(sig_dic):
'''
For generating List view HTML file for SELECT.
for each item.
'''
view_jushi = '''<span class="label label-primary" ... |
def create(self, create_missing=None):
"""Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1235377
<https://bugzilla.redhat.com/show_bug.cgi?id=1235377>`_.
"""
return HostGroup(
self._server_config,
... | Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1235377
<https://bugzilla.redhat.com/show_bug.cgi?id=1235377>`_. | Below is the the instruction that describes the task:
### Input:
Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1235377
<https://bugzilla.redhat.com/show_bug.cgi?id=1235377>`_.
### Response:
def create(self, create_missing=None):
"... |
def _convert(self, format):
"""Return a new Image instance with the given format.
Returns self if the format is already the same.
"""
if self.format == format:
return self
else:
image = Image(self.pil_image)
image._format = format
... | Return a new Image instance with the given format.
Returns self if the format is already the same. | Below is the the instruction that describes the task:
### Input:
Return a new Image instance with the given format.
Returns self if the format is already the same.
### Response:
def _convert(self, format):
"""Return a new Image instance with the given format.
Returns self if the format is... |
def create_refresh_token(self, access_token_value):
# type: (str) -> str
"""
Creates an refresh token bound to the specified access token.
"""
if access_token_value not in self.access_tokens:
raise InvalidAccessToken('{} unknown'.format(access_token_value))
i... | Creates an refresh token bound to the specified access token. | Below is the the instruction that describes the task:
### Input:
Creates an refresh token bound to the specified access token.
### Response:
def create_refresh_token(self, access_token_value):
# type: (str) -> str
"""
Creates an refresh token bound to the specified access token.
"""... |
def get(self, nicks=[], fields=[]):
'''taobao.users.get 获取多个用户信息'''
request = TOPRequest('taobao.users.get')
request['nicks'] = ','.join(nicks)
if not fields:
user = User()
fields = user.fields
request['fields'] = ','.join(fields)
self.create(self.... | taobao.users.get 获取多个用户信息 | Below is the the instruction that describes the task:
### Input:
taobao.users.get 获取多个用户信息
### Response:
def get(self, nicks=[], fields=[]):
'''taobao.users.get 获取多个用户信息'''
request = TOPRequest('taobao.users.get')
request['nicks'] = ','.join(nicks)
if not fields:
user = ... |
def xform(self, left, right, repeating, base, sign):
"""
Return prefixes for tuple.
:param str left: left of the radix
:param str right: right of the radix
:param str repeating: repeating part
:param int base: the base in which value is displayed
:param int sign:... | Return prefixes for tuple.
:param str left: left of the radix
:param str right: right of the radix
:param str repeating: repeating part
:param int base: the base in which value is displayed
:param int sign: -1, 0, 1 as appropriate
:returns: the number string
:rty... | Below is the the instruction that describes the task:
### Input:
Return prefixes for tuple.
:param str left: left of the radix
:param str right: right of the radix
:param str repeating: repeating part
:param int base: the base in which value is displayed
:param int sign: -1,... |
def write(self, f):
""" Write namespace as INI file.
:param f: File object or path to file.
"""
if isinstance(f, str):
f = io.open(f, 'w', encoding='utf-8')
if not hasattr(f, 'read'):
raise AttributeError("Wrong type of file: {0}".format(type(f)))
... | Write namespace as INI file.
:param f: File object or path to file. | Below is the the instruction that describes the task:
### Input:
Write namespace as INI file.
:param f: File object or path to file.
### Response:
def write(self, f):
""" Write namespace as INI file.
:param f: File object or path to file.
"""
if isinstance(f, str):
... |
def raw_reader(queue=None):
"""Returns a raw binary reader co-routine.
Args:
queue (Optional[BufferQueue]): The buffer read data for parsing, if ``None`` a
new one will be created.
Yields:
IonEvent: parse events, will have an event type of ``INCOMPLETE`` if data is needed
... | Returns a raw binary reader co-routine.
Args:
queue (Optional[BufferQueue]): The buffer read data for parsing, if ``None`` a
new one will be created.
Yields:
IonEvent: parse events, will have an event type of ``INCOMPLETE`` if data is needed
in the middle of a value or ... | Below is the the instruction that describes the task:
### Input:
Returns a raw binary reader co-routine.
Args:
queue (Optional[BufferQueue]): The buffer read data for parsing, if ``None`` a
new one will be created.
Yields:
IonEvent: parse events, will have an event type of ``IN... |
def _fetch(self, endpoint_name, **params):
"""
Wrapper for making an api request from giphy
"""
params['api_key'] = self.api_key
resp = requests.get(self._endpoint(endpoint_name), params=params)
resp.raise_for_status()
data = resp.json()
self._check_or_r... | Wrapper for making an api request from giphy | Below is the the instruction that describes the task:
### Input:
Wrapper for making an api request from giphy
### Response:
def _fetch(self, endpoint_name, **params):
"""
Wrapper for making an api request from giphy
"""
params['api_key'] = self.api_key
resp = requests.get(s... |
def _set_clear_mpls_auto_bandwidth_statistics_lsp(self, v, load=False):
"""
Setter method for clear_mpls_auto_bandwidth_statistics_lsp, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_auto_bandwidth_statistics_lsp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _... | Setter method for clear_mpls_auto_bandwidth_statistics_lsp, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_auto_bandwidth_statistics_lsp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_clear_mpls_auto_bandwidth_statistics_lsp is considered as a private
method. ... | Below is the the instruction that describes the task:
### Input:
Setter method for clear_mpls_auto_bandwidth_statistics_lsp, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_auto_bandwidth_statistics_lsp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_clear_mpls_... |
def libvlc_media_list_index_of_item(p_ml, p_md):
'''Find index position of List media instance in media list.
Warning: the function will return the first matched position.
The L{libvlc_media_list_lock} should be held upon entering this function.
@param p_ml: a media list instance.
@param p_md: media... | Find index position of List media instance in media list.
Warning: the function will return the first matched position.
The L{libvlc_media_list_lock} should be held upon entering this function.
@param p_ml: a media list instance.
@param p_md: media instance.
@return: position of media instance or -1... | Below is the the instruction that describes the task:
### Input:
Find index position of List media instance in media list.
Warning: the function will return the first matched position.
The L{libvlc_media_list_lock} should be held upon entering this function.
@param p_ml: a media list instance.
@para... |
def times(self, a):
""" Multiply. """
return Vector(self.x*a, self.y*a, self.z*a) | Multiply. | Below is the the instruction that describes the task:
### Input:
Multiply.
### Response:
def times(self, a):
""" Multiply. """
return Vector(self.x*a, self.y*a, self.z*a) |
def calcWeightedAvg(data,weights):
'''
Generates a weighted average of simulated data. The Nth row of data is averaged
and then weighted by the Nth element of weights in an aggregate average.
Parameters
----------
data : numpy.array
An array of data with N rows of J floats
weights ... | Generates a weighted average of simulated data. The Nth row of data is averaged
and then weighted by the Nth element of weights in an aggregate average.
Parameters
----------
data : numpy.array
An array of data with N rows of J floats
weights : numpy.array
A length N array of weigh... | Below is the the instruction that describes the task:
### Input:
Generates a weighted average of simulated data. The Nth row of data is averaged
and then weighted by the Nth element of weights in an aggregate average.
Parameters
----------
data : numpy.array
An array of data with N rows of... |
def _make_like(self, column, format, value):
"""
make like condition
:param column: column object
:param format: '%_' '_%' '%_%'
:param value: column value
:return: condition object
"""
c = []
if format.startswith('%'):
c.appe... | make like condition
:param column: column object
:param format: '%_' '_%' '%_%'
:param value: column value
:return: condition object | Below is the the instruction that describes the task:
### Input:
make like condition
:param column: column object
:param format: '%_' '_%' '%_%'
:param value: column value
:return: condition object
### Response:
def _make_like(self, column, format, value):
"""
... |
def build(self, **kw):
"""Actually build the node.
This is called by the Taskmaster after it's decided that the
Node is out-of-date and must be rebuilt, and after the prepare()
method has gotten everything, uh, prepared.
This method is called from multiple threads in a parallel... | Actually build the node.
This is called by the Taskmaster after it's decided that the
Node is out-of-date and must be rebuilt, and after the prepare()
method has gotten everything, uh, prepared.
This method is called from multiple threads in a parallel build,
so only do thread ... | Below is the the instruction that describes the task:
### Input:
Actually build the node.
This is called by the Taskmaster after it's decided that the
Node is out-of-date and must be rebuilt, and after the prepare()
method has gotten everything, uh, prepared.
This method is called ... |
def niggli_reduce(lattice, eps=1e-5):
"""Run Niggli reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
eps:
float: Tolerance to check if difference of norms of two basis
... | Run Niggli reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
eps:
float: Tolerance to check if difference of norms of two basis
vectors is close to zero or not and if tw... | Below is the the instruction that describes the task:
### Input:
Run Niggli reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
eps:
float: Tolerance to check if difference of norms of t... |
def conditional_committors(source, sink, waypoint, msm):
"""
Computes the conditional committors :math:`q^{ABC^+}` which are is the
probability of starting in one state and visiting state B before A while
also visiting state C at some point.
Note that in the notation of Dickson et. al. this compute... | Computes the conditional committors :math:`q^{ABC^+}` which are is the
probability of starting in one state and visiting state B before A while
also visiting state C at some point.
Note that in the notation of Dickson et. al. this computes :math:`h_c(A,B)`,
with ``sources = A``, ``sinks = B``, ``waypoi... | Below is the the instruction that describes the task:
### Input:
Computes the conditional committors :math:`q^{ABC^+}` which are is the
probability of starting in one state and visiting state B before A while
also visiting state C at some point.
Note that in the notation of Dickson et. al. this compute... |
def btc_witness_script_deserialize(_script):
"""
Given a hex-encoded serialized witness script, turn it into a witness stack
(i.e. an array of Nones, ints, and strings)
"""
script = None
if isinstance(_script, str) and re.match('^[0-9a-fA-F]*$', _script):
# convert from hex to bin, safe... | Given a hex-encoded serialized witness script, turn it into a witness stack
(i.e. an array of Nones, ints, and strings) | Below is the the instruction that describes the task:
### Input:
Given a hex-encoded serialized witness script, turn it into a witness stack
(i.e. an array of Nones, ints, and strings)
### Response:
def btc_witness_script_deserialize(_script):
"""
Given a hex-encoded serialized witness script, turn it ... |
def mouse_move(self, event):
"""
The following gets back coordinates of the mouse on the canvas.
"""
if (self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE):
self.posX = event.xdata
self.posY = event.ydata
self.graphic_target(self.posX, self.po... | The following gets back coordinates of the mouse on the canvas. | Below is the the instruction that describes the task:
### Input:
The following gets back coordinates of the mouse on the canvas.
### Response:
def mouse_move(self, event):
"""
The following gets back coordinates of the mouse on the canvas.
"""
if (self.ui.tabWidget.currentIndex() ==... |
def _query_response_to_snapshot(response_pb, collection, expected_prefix):
"""Parse a query response protobuf to a document snapshot.
Args:
response_pb (google.cloud.proto.firestore.v1beta1.\
firestore_pb2.RunQueryResponse): A
collection (~.firestore_v1beta1.collection.CollectionRef... | Parse a query response protobuf to a document snapshot.
Args:
response_pb (google.cloud.proto.firestore.v1beta1.\
firestore_pb2.RunQueryResponse): A
collection (~.firestore_v1beta1.collection.CollectionReference): A
reference to the collection that initiated the query.
... | Below is the the instruction that describes the task:
### Input:
Parse a query response protobuf to a document snapshot.
Args:
response_pb (google.cloud.proto.firestore.v1beta1.\
firestore_pb2.RunQueryResponse): A
collection (~.firestore_v1beta1.collection.CollectionReference): A
... |
def __callback (self, odom):
'''
Callback function to receive and save Pose3d.
@param odom: ROS Odometry received
@type odom: Odometry
'''
pose = odometry2Pose3D(odom)
self.lock.acquire()
self.data = pose
self.lock.release() | Callback function to receive and save Pose3d.
@param odom: ROS Odometry received
@type odom: Odometry | Below is the the instruction that describes the task:
### Input:
Callback function to receive and save Pose3d.
@param odom: ROS Odometry received
@type odom: Odometry
### Response:
def __callback (self, odom):
'''
Callback function to receive and save Pose3d.
@p... |
def set_nested(data, value, *keys):
"""Assign to a nested dictionary.
:param dict data: Dictionary to mutate
:param value: Value to set
:param list *keys: List of nested keys
>>> data = {}
>>> set_nested(data, 'hi', 'k0', 'k1', 'k2')
>>> data
{'k0': {'k1': {'k2': 'hi'}}}
"""
i... | Assign to a nested dictionary.
:param dict data: Dictionary to mutate
:param value: Value to set
:param list *keys: List of nested keys
>>> data = {}
>>> set_nested(data, 'hi', 'k0', 'k1', 'k2')
>>> data
{'k0': {'k1': {'k2': 'hi'}}} | Below is the the instruction that describes the task:
### Input:
Assign to a nested dictionary.
:param dict data: Dictionary to mutate
:param value: Value to set
:param list *keys: List of nested keys
>>> data = {}
>>> set_nested(data, 'hi', 'k0', 'k1', 'k2')
>>> data
{'k0': {'k1': {'k... |
def get_raw_file():
"""
Get the raw divider file in a string array.
:return: the array
:rtype: str
"""
with open("{0}/dividers.txt".format(
os.path.abspath(
os.path.dirname(__file__)
)
), mode="r") as file_handler:
lines = file_handler.readlines()
... | Get the raw divider file in a string array.
:return: the array
:rtype: str | Below is the the instruction that describes the task:
### Input:
Get the raw divider file in a string array.
:return: the array
:rtype: str
### Response:
def get_raw_file():
"""
Get the raw divider file in a string array.
:return: the array
:rtype: str
"""
with open("{0}/dividers.... |
def DemangleName(self, name):
"Applies some simple heuristics to split names into (city, name)."
# Handle special cases where our heuristcs doesn't work.
# Example:"Triemli" --> ("Triemli", "Zurich").
if name in SPECIAL_NAMES:
return SPECIAL_NAMES[name]
# Expand abbreviations.
for abbrev... | Applies some simple heuristics to split names into (city, name). | Below is the the instruction that describes the task:
### Input:
Applies some simple heuristics to split names into (city, name).
### Response:
def DemangleName(self, name):
"Applies some simple heuristics to split names into (city, name)."
# Handle special cases where our heuristcs doesn't work.
# Ex... |
def normalise_rows(matrix):
""" Scales all rows to length 1. Fails when row is 0-length, so it
leaves these unchanged """
lengths = np.apply_along_axis(np.linalg.norm, 1, matrix)
if not (lengths > 0).all():
# raise ValueError('Cannot normalise 0 length vector to length 1')
# print(matri... | Scales all rows to length 1. Fails when row is 0-length, so it
leaves these unchanged | Below is the the instruction that describes the task:
### Input:
Scales all rows to length 1. Fails when row is 0-length, so it
leaves these unchanged
### Response:
def normalise_rows(matrix):
""" Scales all rows to length 1. Fails when row is 0-length, so it
leaves these unchanged """
lengths = n... |
def start(self, timeout=None, task=None, block_callbacks=False, role=None):
"""Start PostgreSQL
Waits for postmaster to open ports or terminate so pg_isready can be used to check startup completion
or failure.
:returns: True if start was initiated and postmaster ports are open, False i... | Start PostgreSQL
Waits for postmaster to open ports or terminate so pg_isready can be used to check startup completion
or failure.
:returns: True if start was initiated and postmaster ports are open, False if start failed | Below is the the instruction that describes the task:
### Input:
Start PostgreSQL
Waits for postmaster to open ports or terminate so pg_isready can be used to check startup completion
or failure.
:returns: True if start was initiated and postmaster ports are open, False if start failed
###... |
def clean_tenant_url(url_string):
"""
Removes the TENANT_TOKEN from a particular string
"""
if hasattr(settings, 'PUBLIC_SCHEMA_URLCONF'):
if (settings.PUBLIC_SCHEMA_URLCONF and
url_string.startswith(settings.PUBLIC_SCHEMA_URLCONF)):
url_string = url_string[len(settin... | Removes the TENANT_TOKEN from a particular string | Below is the the instruction that describes the task:
### Input:
Removes the TENANT_TOKEN from a particular string
### Response:
def clean_tenant_url(url_string):
"""
Removes the TENANT_TOKEN from a particular string
"""
if hasattr(settings, 'PUBLIC_SCHEMA_URLCONF'):
if (settings.PUBLIC_SCH... |
def get_last_update(op):
"""Return the most recent timestamp in the operation."""
last_update = get_end_time(op)
if not last_update:
last_event = get_last_event(op)
if last_event:
last_update = last_event['timestamp']
if not last_update:
last_update = get_create_time(op)
return last_updat... | Return the most recent timestamp in the operation. | Below is the the instruction that describes the task:
### Input:
Return the most recent timestamp in the operation.
### Response:
def get_last_update(op):
"""Return the most recent timestamp in the operation."""
last_update = get_end_time(op)
if not last_update:
last_event = get_last_event(op)
if la... |
def read_in_weight_table(self, in_weight_table):
"""
Read in weight table
"""
print("Reading the weight table...")
with open_csv(in_weight_table, "r") as csvfile:
reader = csv.reader(csvfile)
header_row = next(reader)
# check number of ... | Read in weight table | Below is the the instruction that describes the task:
### Input:
Read in weight table
### Response:
def read_in_weight_table(self, in_weight_table):
"""
Read in weight table
"""
print("Reading the weight table...")
with open_csv(in_weight_table, "r") as csvfile:
... |
def to_cartesian(r, theta, theta_units="radians"):
"""
Converts polar r, theta to cartesian x, y.
"""
assert theta_units in ['radians', 'degrees'],\
"kwarg theta_units must specified in radians or degrees"
# Convert to radians
if theta_units == "degrees":
theta = to_radians(thet... | Converts polar r, theta to cartesian x, y. | Below is the the instruction that describes the task:
### Input:
Converts polar r, theta to cartesian x, y.
### Response:
def to_cartesian(r, theta, theta_units="radians"):
"""
Converts polar r, theta to cartesian x, y.
"""
assert theta_units in ['radians', 'degrees'],\
"kwarg theta_units m... |
def SetStorageProfiler(self, storage_profiler):
"""Sets the storage profiler.
Args:
storage_profiler (StorageProfiler): storage profiler.
"""
self._storage_profiler = storage_profiler
if self._storage_file:
self._storage_file.SetStorageProfiler(storage_profiler) | Sets the storage profiler.
Args:
storage_profiler (StorageProfiler): storage profiler. | Below is the the instruction that describes the task:
### Input:
Sets the storage profiler.
Args:
storage_profiler (StorageProfiler): storage profiler.
### Response:
def SetStorageProfiler(self, storage_profiler):
"""Sets the storage profiler.
Args:
storage_profiler (StorageProfiler): sto... |
async def unpinChatMessage(self, chat_id):
""" See: https://core.telegram.org/bots/api#unpinchatmessage """
p = _strip(locals())
return await self._api_request('unpinChatMessage', _rectify(p)) | See: https://core.telegram.org/bots/api#unpinchatmessage | Below is the the instruction that describes the task:
### Input:
See: https://core.telegram.org/bots/api#unpinchatmessage
### Response:
async def unpinChatMessage(self, chat_id):
""" See: https://core.telegram.org/bots/api#unpinchatmessage """
p = _strip(locals())
return await self._api_req... |
def bookmark_rename(bookmark_id_or_name, new_bookmark_name):
"""
Executor for `globus bookmark rename`
"""
client = get_client()
bookmark_id = resolve_id_or_name(client, bookmark_id_or_name)["id"]
submit_data = {"name": new_bookmark_name}
res = client.update_bookmark(bookmark_id, submit_da... | Executor for `globus bookmark rename` | Below is the the instruction that describes the task:
### Input:
Executor for `globus bookmark rename`
### Response:
def bookmark_rename(bookmark_id_or_name, new_bookmark_name):
"""
Executor for `globus bookmark rename`
"""
client = get_client()
bookmark_id = resolve_id_or_name(client, bookmark... |
def peer(opt_peer, opt_username, opt_password, scope="module"):
'''peer bigip fixture'''
p = BigIP(opt_peer, opt_username, opt_password)
return p | peer bigip fixture | Below is the the instruction that describes the task:
### Input:
peer bigip fixture
### Response:
def peer(opt_peer, opt_username, opt_password, scope="module"):
'''peer bigip fixture'''
p = BigIP(opt_peer, opt_username, opt_password)
return p |
def convert_enamldef_def_to_func(token_stream):
""" A token stream processor which processes all enaml declarative functions
to allow using `def` instead of `func`. It does this by transforming DEF
tokens to NAME within enamldef blocks and then changing the token value to
`func`.
Notes
-... | A token stream processor which processes all enaml declarative functions
to allow using `def` instead of `func`. It does this by transforming DEF
tokens to NAME within enamldef blocks and then changing the token value to
`func`.
Notes
------
Use this at your own risk! This was a feature... | Below is the the instruction that describes the task:
### Input:
A token stream processor which processes all enaml declarative functions
to allow using `def` instead of `func`. It does this by transforming DEF
tokens to NAME within enamldef blocks and then changing the token value to
`func`.
... |
def create_versions(self, project_id, versions):
""" Accepts result of getVersions()
"""
for v in versions:
self.create_version(project_id, v) | Accepts result of getVersions() | Below is the the instruction that describes the task:
### Input:
Accepts result of getVersions()
### Response:
def create_versions(self, project_id, versions):
""" Accepts result of getVersions()
"""
for v in versions:
self.create_version(project_id, v) |
def get_cpu_info(self):
"""
Retrieves CPU info from client
"""
info = snap7.snap7types.S7CpuInfo()
result = self.library.Cli_GetCpuInfo(self.pointer, byref(info))
check_error(result, context="client")
return info | Retrieves CPU info from client | Below is the the instruction that describes the task:
### Input:
Retrieves CPU info from client
### Response:
def get_cpu_info(self):
"""
Retrieves CPU info from client
"""
info = snap7.snap7types.S7CpuInfo()
result = self.library.Cli_GetCpuInfo(self.pointer, byref(info))
... |
def write_updates_to_csv(self, updates):
"""
Given a list of updates, write the updates out to the provided CSV
file.
Args:
updates (list): List of Update objects.
"""
with open(self._csv_file_name, 'w') as csvfile:
csvwriter = self.csv_writer(csv... | Given a list of updates, write the updates out to the provided CSV
file.
Args:
updates (list): List of Update objects. | Below is the the instruction that describes the task:
### Input:
Given a list of updates, write the updates out to the provided CSV
file.
Args:
updates (list): List of Update objects.
### Response:
def write_updates_to_csv(self, updates):
"""
Given a list of updates, wr... |
def adapt(self, d, x):
"""
Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array)
"""
# create input matrix and target vector
self.x_mem[:,1:] = self.x_mem[:,:-1]
... | Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array) | Below is the the instruction that describes the task:
### Input:
Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array)
### Response:
def adapt(self, d, x):
"""
Adapt weights according one... |
def is_python_interpreter(filename):
"""Evaluate wether a file is a python interpreter or not."""
real_filename = os.path.realpath(filename) # To follow symlink if existent
if (not osp.isfile(real_filename) or
not is_python_interpreter_valid_name(filename)):
return False
elif is_... | Evaluate wether a file is a python interpreter or not. | Below is the the instruction that describes the task:
### Input:
Evaluate wether a file is a python interpreter or not.
### Response:
def is_python_interpreter(filename):
"""Evaluate wether a file is a python interpreter or not."""
real_filename = os.path.realpath(filename) # To follow symlink if existe... |
def get_states(self, dump_optimizer=False):
"""Gets updater states.
Parameters
----------
dump_optimizer : bool, default False
Whether to also save the optimizer itself. This would also save optimizer
information such as learning rate and weight decay schedules.
... | Gets updater states.
Parameters
----------
dump_optimizer : bool, default False
Whether to also save the optimizer itself. This would also save optimizer
information such as learning rate and weight decay schedules. | Below is the the instruction that describes the task:
### Input:
Gets updater states.
Parameters
----------
dump_optimizer : bool, default False
Whether to also save the optimizer itself. This would also save optimizer
information such as learning rate and weight dec... |
def mv_normal_like(x, mu, tau):
R"""
Multivariate normal log-likelihood
.. math::
f(x \mid \pi, T) = \frac{|T|^{1/2}}{(2\pi)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}T(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter sequence.
- `Tau` : (k,k) ... | R"""
Multivariate normal log-likelihood
.. math::
f(x \mid \pi, T) = \frac{|T|^{1/2}}{(2\pi)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}T(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter sequence.
- `Tau` : (k,k) Positive definite precision matrix.
... | Below is the the instruction that describes the task:
### Input:
R"""
Multivariate normal log-likelihood
.. math::
f(x \mid \pi, T) = \frac{|T|^{1/2}}{(2\pi)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}T(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter... |
def process_buffer(self, i_block, receive_buffer):
"""Blocking function to process the received heaps.
This is run in an executor.
"""
self._log.info("Worker thread processing block %i", i_block)
time_overall0 = time.time()
time_unpack = 0.0
time_write = 0.0
... | Blocking function to process the received heaps.
This is run in an executor. | Below is the the instruction that describes the task:
### Input:
Blocking function to process the received heaps.
This is run in an executor.
### Response:
def process_buffer(self, i_block, receive_buffer):
"""Blocking function to process the received heaps.
This is run in an executor.
... |
def date_from_relative_week_year(base_date, time, dow, ordinal=1):
"""
Converts relative day to time
Eg. this tuesday, last tuesday
"""
# If there is an ordinal (next 3 weeks) => return a start and end range
# Reset date to start of the day
relative_date = datetime(base_date.year, base_date.... | Converts relative day to time
Eg. this tuesday, last tuesday | Below is the the instruction that describes the task:
### Input:
Converts relative day to time
Eg. this tuesday, last tuesday
### Response:
def date_from_relative_week_year(base_date, time, dow, ordinal=1):
"""
Converts relative day to time
Eg. this tuesday, last tuesday
"""
# If there is a... |
def convert_dict_to_datetime(obj_map):
"""converts dictionary representations of datetime back to datetime obj"""
converted_map = {}
for key, value in obj_map.items():
if isinstance(value, dict) and 'tzinfo' in value.keys():
converted_map[key] = datetime.datetime(**value)
elif is... | converts dictionary representations of datetime back to datetime obj | Below is the the instruction that describes the task:
### Input:
converts dictionary representations of datetime back to datetime obj
### Response:
def convert_dict_to_datetime(obj_map):
"""converts dictionary representations of datetime back to datetime obj"""
converted_map = {}
for key, value in obj_... |
def get_trust_id(self):
"""Gets the ``Trust`` ``Id`` for this authorization.
return: (osid.id.Id) - the trust ``Id``
raise: IllegalState - ``has_trust()`` is ``false``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid... | Gets the ``Trust`` ``Id`` for this authorization.
return: (osid.id.Id) - the trust ``Id``
raise: IllegalState - ``has_trust()`` is ``false``
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Gets the ``Trust`` ``Id`` for this authorization.
return: (osid.id.Id) - the trust ``Id``
raise: IllegalState - ``has_trust()`` is ``false``
*compliance: mandatory -- This method must be implemented.*
### Response:
def get_... |
def setTransducer(self, edfsignal, transducer):
"""
Sets the transducer of signal edfsignal
:param edfsignal: int
:param transducer: str
Notes
-----
This function is optional for every signal and can be called only after opening a file in writemode and before th... | Sets the transducer of signal edfsignal
:param edfsignal: int
:param transducer: str
Notes
-----
This function is optional for every signal and can be called only after opening a file in writemode and before the first sample write action. | Below is the the instruction that describes the task:
### Input:
Sets the transducer of signal edfsignal
:param edfsignal: int
:param transducer: str
Notes
-----
This function is optional for every signal and can be called only after opening a file in writemode and before t... |
def _NormalizedVolumeIdentifiers(
self, volume_system, volume_identifiers, prefix='v'):
"""Normalizes volume identifiers.
Args:
volume_system (VolumeSystem): volume system.
volume_identifiers (list[int|str]): allowed volume identifiers, formatted
as an integer or string with prefix.... | Normalizes volume identifiers.
Args:
volume_system (VolumeSystem): volume system.
volume_identifiers (list[int|str]): allowed volume identifiers, formatted
as an integer or string with prefix.
prefix (Optional[str]): volume identifier prefix.
Returns:
list[str]: volume identi... | Below is the the instruction that describes the task:
### Input:
Normalizes volume identifiers.
Args:
volume_system (VolumeSystem): volume system.
volume_identifiers (list[int|str]): allowed volume identifiers, formatted
as an integer or string with prefix.
prefix (Optional[str]): v... |
def items(self):
"""
Get a queryset, cache infos for standardized access to them later
then compute the maximum of entries to define the priority
of each items.
"""
queryset = self.get_queryset()
self.cache_infos(queryset)
self.set_max_entries()
re... | Get a queryset, cache infos for standardized access to them later
then compute the maximum of entries to define the priority
of each items. | Below is the the instruction that describes the task:
### Input:
Get a queryset, cache infos for standardized access to them later
then compute the maximum of entries to define the priority
of each items.
### Response:
def items(self):
"""
Get a queryset, cache infos for standardize... |
def docx_extraction(docx, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given a .docx file, returns the raw text associated with the given .docx file.
The .docx file may be provided as base64 encoded data or as a filepath.
Example usage:
.. code-block:: python
>>> fro... | Given a .docx file, returns the raw text associated with the given .docx file.
The .docx file may be provided as base64 encoded data or as a filepath.
Example usage:
.. code-block:: python
>>> from indicoio import docx_extraction
>>> results = docx_extraction(docx_file)
:param docx: Th... | Below is the the instruction that describes the task:
### Input:
Given a .docx file, returns the raw text associated with the given .docx file.
The .docx file may be provided as base64 encoded data or as a filepath.
Example usage:
.. code-block:: python
>>> from indicoio import docx_extraction... |
def from_xso_item(cls, xso_item):
"""
Create a :class:`Item` with the :attr:`jid` set to the
:attr:`.xso.Item.jid` obtained from `xso_item`. Then update that
instance with `xso_item` using :meth:`update_from_xso_item` and return
it.
"""
item = cls(xso_item.jid)
... | Create a :class:`Item` with the :attr:`jid` set to the
:attr:`.xso.Item.jid` obtained from `xso_item`. Then update that
instance with `xso_item` using :meth:`update_from_xso_item` and return
it. | Below is the the instruction that describes the task:
### Input:
Create a :class:`Item` with the :attr:`jid` set to the
:attr:`.xso.Item.jid` obtained from `xso_item`. Then update that
instance with `xso_item` using :meth:`update_from_xso_item` and return
it.
### Response:
def from_xso_item... |
def put(self, entity):
"""Adds an entity to be committed.
Ensures the transaction is not marked readonly.
Please see documentation at
:meth:`~google.cloud.datastore.batch.Batch.put`
:type entity: :class:`~google.cloud.datastore.entity.Entity`
:param entity: the entity t... | Adds an entity to be committed.
Ensures the transaction is not marked readonly.
Please see documentation at
:meth:`~google.cloud.datastore.batch.Batch.put`
:type entity: :class:`~google.cloud.datastore.entity.Entity`
:param entity: the entity to be saved.
:raises: :cla... | Below is the the instruction that describes the task:
### Input:
Adds an entity to be committed.
Ensures the transaction is not marked readonly.
Please see documentation at
:meth:`~google.cloud.datastore.batch.Batch.put`
:type entity: :class:`~google.cloud.datastore.entity.Entity`
... |
def disaggregate(self, sitecol, ruptures, iml4, truncnorm, epsilons,
monitor=Monitor()):
"""
Disaggregate (separate) PoE in different contributions.
:param sitecol: a SiteCollection with N sites
:param ruptures: an iterator over ruptures with the same TRT
:p... | Disaggregate (separate) PoE in different contributions.
:param sitecol: a SiteCollection with N sites
:param ruptures: an iterator over ruptures with the same TRT
:param iml4: a 4d array of IMLs of shape (N, R, M, P)
:param truncnorm: an instance of scipy.stats.truncnorm
:param ... | Below is the the instruction that describes the task:
### Input:
Disaggregate (separate) PoE in different contributions.
:param sitecol: a SiteCollection with N sites
:param ruptures: an iterator over ruptures with the same TRT
:param iml4: a 4d array of IMLs of shape (N, R, M, P)
:... |
def format_time(x):
"""Formats date values
This function formats :class:`datetime.datetime` and
:class:`datetime.timedelta` objects (and the corresponding numpy objects)
using the :func:`xarray.core.formatting.format_timestamp` and the
:func:`xarray.core.formatting.format_timedelta` functions.
... | Formats date values
This function formats :class:`datetime.datetime` and
:class:`datetime.timedelta` objects (and the corresponding numpy objects)
using the :func:`xarray.core.formatting.format_timestamp` and the
:func:`xarray.core.formatting.format_timedelta` functions.
Parameters
----------
... | Below is the the instruction that describes the task:
### Input:
Formats date values
This function formats :class:`datetime.datetime` and
:class:`datetime.timedelta` objects (and the corresponding numpy objects)
using the :func:`xarray.core.formatting.format_timestamp` and the
:func:`xarray.core.fo... |
def copy(self: BaseBoardT) -> BaseBoardT:
"""Creates a copy of the board."""
board = type(self)(None)
board.pawns = self.pawns
board.knights = self.knights
board.bishops = self.bishops
board.rooks = self.rooks
board.queens = self.queens
board.kings = self... | Creates a copy of the board. | Below is the the instruction that describes the task:
### Input:
Creates a copy of the board.
### Response:
def copy(self: BaseBoardT) -> BaseBoardT:
"""Creates a copy of the board."""
board = type(self)(None)
board.pawns = self.pawns
board.knights = self.knights
board.bish... |
def Convert(self, metadata, config, token=None):
"""Converts DNSClientConfiguration to ExportedDNSClientConfiguration."""
result = ExportedDNSClientConfiguration(
metadata=metadata,
dns_servers=" ".join(config.dns_server),
dns_suffixes=" ".join(config.dns_suffix))
yield result | Converts DNSClientConfiguration to ExportedDNSClientConfiguration. | Below is the the instruction that describes the task:
### Input:
Converts DNSClientConfiguration to ExportedDNSClientConfiguration.
### Response:
def Convert(self, metadata, config, token=None):
"""Converts DNSClientConfiguration to ExportedDNSClientConfiguration."""
result = ExportedDNSClientConfiguration... |
def get_programs():
"""Returns a generator that yields the available executable programs
:returns: a generator that yields the programs available after a refresh_listing()
:rtype: generator
"""
programs = []
os.environ['PATH'] += os.pathsep + os.getcwd()
for p in os.environ['PATH'].split(os... | Returns a generator that yields the available executable programs
:returns: a generator that yields the programs available after a refresh_listing()
:rtype: generator | Below is the the instruction that describes the task:
### Input:
Returns a generator that yields the available executable programs
:returns: a generator that yields the programs available after a refresh_listing()
:rtype: generator
### Response:
def get_programs():
"""Returns a generator that yields t... |
def islink(path):
'''
Equivalent to os.path.islink()
'''
if six.PY3 or not salt.utils.platform.is_windows():
return os.path.islink(path)
if not HAS_WIN32FILE:
log.error('Cannot check if %s is a link, missing required modules', path)
if not _is_reparse_point(path):
retur... | Equivalent to os.path.islink() | Below is the the instruction that describes the task:
### Input:
Equivalent to os.path.islink()
### Response:
def islink(path):
'''
Equivalent to os.path.islink()
'''
if six.PY3 or not salt.utils.platform.is_windows():
return os.path.islink(path)
if not HAS_WIN32FILE:
log.error... |
def cp(src, dst, overwrite=False):
"""
Copy files to a new location.
:param src: list (or string) of paths of files to copy
:param dst: file or folder to copy item(s) to
:param overwrite: IF the file already exists, should I overwrite it?
"""
if not isinstance(src, list):
src = [sr... | Copy files to a new location.
:param src: list (or string) of paths of files to copy
:param dst: file or folder to copy item(s) to
:param overwrite: IF the file already exists, should I overwrite it? | Below is the the instruction that describes the task:
### Input:
Copy files to a new location.
:param src: list (or string) of paths of files to copy
:param dst: file or folder to copy item(s) to
:param overwrite: IF the file already exists, should I overwrite it?
### Response:
def cp(src, dst, overwr... |
def choices(cls, blank=False):
""" Choices for Enum
:return: List of tuples (<value>, <human-readable value>)
:rtype: list
"""
choices = sorted([(key, value) for key, value in cls.values.items()], key=lambda x: x[0])
if blank:
choices.insert(0, ('', Enum.Value... | Choices for Enum
:return: List of tuples (<value>, <human-readable value>)
:rtype: list | Below is the the instruction that describes the task:
### Input:
Choices for Enum
:return: List of tuples (<value>, <human-readable value>)
:rtype: list
### Response:
def choices(cls, blank=False):
""" Choices for Enum
:return: List of tuples (<value>, <human-readable value>)
... |
def states(self):
"""Returns a set containing the enabled states."""
state_list = []
for state in States:
if state.value & self._states != 0:
state_list.append(state)
if (self._flashing_states & States.FILTER) != 0:
state_list.append(States.FILTER... | Returns a set containing the enabled states. | Below is the the instruction that describes the task:
### Input:
Returns a set containing the enabled states.
### Response:
def states(self):
"""Returns a set containing the enabled states."""
state_list = []
for state in States:
if state.value & self._states != 0:
... |
def next(self):
"""
Reads the next dataset row.
:return: the next row
:rtype: Instance
"""
if not self.__has_more():
raise StopIteration()
else:
return javabridge.get_env().get_string(self.__next()) | Reads the next dataset row.
:return: the next row
:rtype: Instance | Below is the the instruction that describes the task:
### Input:
Reads the next dataset row.
:return: the next row
:rtype: Instance
### Response:
def next(self):
"""
Reads the next dataset row.
:return: the next row
:rtype: Instance
"""
if not self.... |
def xirr(values, dates, guess=0):
"""
Function to calculate the internal rate of return (IRR) using payments and non-periodic dates. It resembles the
excel function XIRR().
Excel reference: https://support.office.com/en-ie/article/xirr-function-de1242ec-6477-445b-b11b-a303ad9adc9d
:param values: t... | Function to calculate the internal rate of return (IRR) using payments and non-periodic dates. It resembles the
excel function XIRR().
Excel reference: https://support.office.com/en-ie/article/xirr-function-de1242ec-6477-445b-b11b-a303ad9adc9d
:param values: the payments of which at least one has to be ne... | Below is the the instruction that describes the task:
### Input:
Function to calculate the internal rate of return (IRR) using payments and non-periodic dates. It resembles the
excel function XIRR().
Excel reference: https://support.office.com/en-ie/article/xirr-function-de1242ec-6477-445b-b11b-a303ad9adc9... |
def to_price_index(returns, start=100):
"""
Returns a price index given a series of returns.
Args:
* returns: Expects a return series
* start (number): Starting level
Assumes arithmetic returns.
Formula is: cumprod (1+r)
"""
return (returns.replace(to_replace=np.nan, value... | Returns a price index given a series of returns.
Args:
* returns: Expects a return series
* start (number): Starting level
Assumes arithmetic returns.
Formula is: cumprod (1+r) | Below is the the instruction that describes the task:
### Input:
Returns a price index given a series of returns.
Args:
* returns: Expects a return series
* start (number): Starting level
Assumes arithmetic returns.
Formula is: cumprod (1+r)
### Response:
def to_price_index(returns, ... |
def get_user_subscription_to_discussion(recID, uid):
"""
Returns the type of subscription for the given user to this
discussion. This does not check authorizations (for eg. if user
was subscribed, but is suddenly no longer authorized).
:param recID: record ID
:param uid: user id
:return:
... | Returns the type of subscription for the given user to this
discussion. This does not check authorizations (for eg. if user
was subscribed, but is suddenly no longer authorized).
:param recID: record ID
:param uid: user id
:return:
- 0 if user is not subscribed to discussion
... | Below is the the instruction that describes the task:
### Input:
Returns the type of subscription for the given user to this
discussion. This does not check authorizations (for eg. if user
was subscribed, but is suddenly no longer authorized).
:param recID: record ID
:param uid: user id
:return... |
def conv_uuid(self, column, name, **kwargs):
"""Convert UUID filter."""
return [f(column, name, **kwargs) for f in self.uuid_filters] | Convert UUID filter. | Below is the the instruction that describes the task:
### Input:
Convert UUID filter.
### Response:
def conv_uuid(self, column, name, **kwargs):
"""Convert UUID filter."""
return [f(column, name, **kwargs) for f in self.uuid_filters] |
def _get_depencency_var_name(self, dependency):
"""
Returns the variable name assigned to the given dependency or None if the dependency has
not yet been registered.
Args:
dependency (str): Thet dependency that needs to be imported.
Returns:
str or None
... | Returns the variable name assigned to the given dependency or None if the dependency has
not yet been registered.
Args:
dependency (str): Thet dependency that needs to be imported.
Returns:
str or None | Below is the the instruction that describes the task:
### Input:
Returns the variable name assigned to the given dependency or None if the dependency has
not yet been registered.
Args:
dependency (str): Thet dependency that needs to be imported.
Returns:
str or None... |
def get(self, index):
"""
Get the element by index. If index is out of bounds for
the internal list, None is returned. Indexes cannot be
negative.
:param int index: retrieve element by positive index in list
:rtype: SubElement or None
"""
if self ... | Get the element by index. If index is out of bounds for
the internal list, None is returned. Indexes cannot be
negative.
:param int index: retrieve element by positive index in list
:rtype: SubElement or None | Below is the the instruction that describes the task:
### Input:
Get the element by index. If index is out of bounds for
the internal list, None is returned. Indexes cannot be
negative.
:param int index: retrieve element by positive index in list
:rtype: SubElement or None
#... |
def heldout_log_likelihood(self, test_mask=None):
"""
Compute the log likelihood of the masked data given the latent
discrete and continuous states.
"""
if test_mask is None:
# If a test mask is not supplied, use the negation of this object's mask
if self.... | Compute the log likelihood of the masked data given the latent
discrete and continuous states. | Below is the the instruction that describes the task:
### Input:
Compute the log likelihood of the masked data given the latent
discrete and continuous states.
### Response:
def heldout_log_likelihood(self, test_mask=None):
"""
Compute the log likelihood of the masked data given the latent
... |
def form(value):
"""
Format numbers in a nice way.
>>> form(0)
'0'
>>> form(0.0)
'0.0'
>>> form(0.0001)
'1.000E-04'
>>> form(1003.4)
'1,003'
>>> form(103.4)
'103'
>>> form(9.3)
'9.30000'
>>> form(-1.2)
'-1.2'
"""
if isinstance(value, FLOAT + INT):... | Format numbers in a nice way.
>>> form(0)
'0'
>>> form(0.0)
'0.0'
>>> form(0.0001)
'1.000E-04'
>>> form(1003.4)
'1,003'
>>> form(103.4)
'103'
>>> form(9.3)
'9.30000'
>>> form(-1.2)
'-1.2' | Below is the the instruction that describes the task:
### Input:
Format numbers in a nice way.
>>> form(0)
'0'
>>> form(0.0)
'0.0'
>>> form(0.0001)
'1.000E-04'
>>> form(1003.4)
'1,003'
>>> form(103.4)
'103'
>>> form(9.3)
'9.30000'
>>> form(-1.2)
'-1.2'
### Re... |
def police_priority_map_conform_map_pri1_conform(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
name_key = ET.SubElement(police_priority_map... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def police_priority_map_conform_map_pri1_conform(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-... |
def load_preset(self):
"""
Loads preset if it is specified in the .frigg.yml
"""
if 'preset' in self.settings.preview:
with open(os.path.join(os.path.dirname(__file__), 'presets.yaml')) as f:
presets = yaml.load(f.read())
if self.settings.preview[... | Loads preset if it is specified in the .frigg.yml | Below is the the instruction that describes the task:
### Input:
Loads preset if it is specified in the .frigg.yml
### Response:
def load_preset(self):
"""
Loads preset if it is specified in the .frigg.yml
"""
if 'preset' in self.settings.preview:
with open(os.path.join(... |
def summary(self):
'''
Create a dictionary with a summary of the updates in the collection.
Returns:
dict: Summary of the contents of the collection
.. code-block:: cfg
Summary of Updates:
{'Total': <total number of updates returned>,
'... | Create a dictionary with a summary of the updates in the collection.
Returns:
dict: Summary of the contents of the collection
.. code-block:: cfg
Summary of Updates:
{'Total': <total number of updates returned>,
'Available': <updates that are not downl... | Below is the the instruction that describes the task:
### Input:
Create a dictionary with a summary of the updates in the collection.
Returns:
dict: Summary of the contents of the collection
.. code-block:: cfg
Summary of Updates:
{'Total': <total number of upd... |
def handle_subscribe(self, request, path):
# type: (Subscribe, List[str]) -> CallbackResponses
"""Add to the list of request to notify, and notify the initial value of
the data held
Args:
request (Subscribe): The subscribe request
path (list): The relative path f... | Add to the list of request to notify, and notify the initial value of
the data held
Args:
request (Subscribe): The subscribe request
path (list): The relative path from ourself
Returns:
list: [(callback, Response)] that need to be called | Below is the the instruction that describes the task:
### Input:
Add to the list of request to notify, and notify the initial value of
the data held
Args:
request (Subscribe): The subscribe request
path (list): The relative path from ourself
Returns:
lis... |
def has_image(self, name: str) -> bool:
"""
Determines whether the server has a Docker image with a given name.
"""
path = "docker/images/{}".format(name)
r = self.__api.head(path)
if r.status_code == 204:
return True
elif r.status_code == 404:
... | Determines whether the server has a Docker image with a given name. | Below is the the instruction that describes the task:
### Input:
Determines whether the server has a Docker image with a given name.
### Response:
def has_image(self, name: str) -> bool:
"""
Determines whether the server has a Docker image with a given name.
"""
path = "docker/image... |
def _Close(self):
"""Closes the file-like object."""
# pylint: disable=protected-access
super(RawFile, self)._Close()
for file_object in self._file_objects:
file_object.close()
self._file_objects = [] | Closes the file-like object. | Below is the the instruction that describes the task:
### Input:
Closes the file-like object.
### Response:
def _Close(self):
"""Closes the file-like object."""
# pylint: disable=protected-access
super(RawFile, self)._Close()
for file_object in self._file_objects:
file_object.close()
se... |
def is_valid_port(instance: int):
"""Validates data is a valid port"""
if not isinstance(instance, (int, str)):
return True
return int(instance) in range(65535) | Validates data is a valid port | Below is the the instruction that describes the task:
### Input:
Validates data is a valid port
### Response:
def is_valid_port(instance: int):
"""Validates data is a valid port"""
if not isinstance(instance, (int, str)):
return True
return int(instance) in range(65535) |
def substitute_environ(self):
"""
Substitute environment variables into settings.
"""
for attr_name in dir(self):
if attr_name.startswith('_') or attr_name.upper() != attr_name:
continue
orig_value = getattr(self, attr_name)
is_require... | Substitute environment variables into settings. | Below is the the instruction that describes the task:
### Input:
Substitute environment variables into settings.
### Response:
def substitute_environ(self):
"""
Substitute environment variables into settings.
"""
for attr_name in dir(self):
if attr_name.startswith('_') o... |
def toolchain_spec_prepare_loaderplugins(
toolchain, spec,
loaderplugin_read_key,
handler_sourcepath_key,
loaderplugin_sourcepath_map_key=LOADERPLUGIN_SOURCEPATH_MAPS):
"""
A standard helper function for combining the filtered (e.g. using
``spec_update_sourcepath_filter_loade... | A standard helper function for combining the filtered (e.g. using
``spec_update_sourcepath_filter_loaderplugins``) loaderplugin
sourcepath mappings back into one that is usable with the standard
``toolchain_spec_compile_entries`` function.
Arguments:
toolchain
The toolchain
spec
... | Below is the the instruction that describes the task:
### Input:
A standard helper function for combining the filtered (e.g. using
``spec_update_sourcepath_filter_loaderplugins``) loaderplugin
sourcepath mappings back into one that is usable with the standard
``toolchain_spec_compile_entries`` function.... |
def _iter_qs(self):
"""Iterate over the Q values
"""
# work out how many Qs we need
cumum = log(self.qrange[1] / self.qrange[0]) / 2**(1/2.)
nplanes = int(max(ceil(cumum / self.deltam), 1))
dq = cumum / nplanes # pylint: disable=invalid-name
for i in xrange(nplan... | Iterate over the Q values | Below is the the instruction that describes the task:
### Input:
Iterate over the Q values
### Response:
def _iter_qs(self):
"""Iterate over the Q values
"""
# work out how many Qs we need
cumum = log(self.qrange[1] / self.qrange[0]) / 2**(1/2.)
nplanes = int(max(ceil(cumum ... |
def get(self,
singleExposure=False):
"""
*get the orbfitPositions object*
**Key Arguments:**
- ``singleExposure`` -- only execute fot a single exposure (useful for debugging)
**Return:**
- None
**Usage:**
See class docstring
... | *get the orbfitPositions object*
**Key Arguments:**
- ``singleExposure`` -- only execute fot a single exposure (useful for debugging)
**Return:**
- None
**Usage:**
See class docstring | Below is the the instruction that describes the task:
### Input:
*get the orbfitPositions object*
**Key Arguments:**
- ``singleExposure`` -- only execute fot a single exposure (useful for debugging)
**Return:**
- None
**Usage:**
See class docstring
###... |
def getFixedStar(ID, jd):
""" Returns a fixed star. """
star = swe.sweFixedStar(ID, jd)
_signInfo(star)
return star | Returns a fixed star. | Below is the the instruction that describes the task:
### Input:
Returns a fixed star.
### Response:
def getFixedStar(ID, jd):
""" Returns a fixed star. """
star = swe.sweFixedStar(ID, jd)
_signInfo(star)
return star |
def _calc_lm_step(self, damped_JTJ, grad, subblock=None):
"""Calculates a Levenberg-Marquard step w/o acceleration"""
delta0, res, rank, s = np.linalg.lstsq(damped_JTJ, -0.5*grad,
rcond=self.min_eigval)
if self._fresh_JTJ:
CLOG.debug('%d degenerate of %d total directi... | Calculates a Levenberg-Marquard step w/o acceleration | Below is the the instruction that describes the task:
### Input:
Calculates a Levenberg-Marquard step w/o acceleration
### Response:
def _calc_lm_step(self, damped_JTJ, grad, subblock=None):
"""Calculates a Levenberg-Marquard step w/o acceleration"""
delta0, res, rank, s = np.linalg.lstsq(damped_JT... |
def parse_relation(obj: dict) -> BioCRelation:
"""Deserialize a dict obj to a BioCRelation object"""
rel = BioCRelation()
rel.id = obj['id']
rel.infons = obj['infons']
for node in obj['nodes']:
rel.add_node(BioCNode(node['refid'], node['role']))
return rel | Deserialize a dict obj to a BioCRelation object | Below is the the instruction that describes the task:
### Input:
Deserialize a dict obj to a BioCRelation object
### Response:
def parse_relation(obj: dict) -> BioCRelation:
"""Deserialize a dict obj to a BioCRelation object"""
rel = BioCRelation()
rel.id = obj['id']
rel.infons = obj['infons']
... |
def cancel_bbuild(self, build_execution_configuration_id, **kwargs):
"""
Cancel the build execution defined with given executionConfigurationId.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
... | Cancel the build execution defined with given executionConfigurationId.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(respons... | Below is the the instruction that describes the task:
### Input:
Cancel the build execution defined with given executionConfigurationId.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked w... |
def apply(self, a, return_Ya=False):
r"""Apply the projection to an array.
The computation is carried out without explicitly forming the
matrix corresponding to the projection (which would be an array with
``shape==(N,N)``).
See also :py:meth:`_apply`.
"""
# is ... | r"""Apply the projection to an array.
The computation is carried out without explicitly forming the
matrix corresponding to the projection (which would be an array with
``shape==(N,N)``).
See also :py:meth:`_apply`. | Below is the the instruction that describes the task:
### Input:
r"""Apply the projection to an array.
The computation is carried out without explicitly forming the
matrix corresponding to the projection (which would be an array with
``shape==(N,N)``).
See also :py:meth:`_apply`.
#... |
def mpstatus_to_json(status):
'''Translate MPStatus in json string'''
msg_keys = list(status.msgs.keys())
data = '{'
for key in msg_keys[:-1]:
data += mavlink_to_json(status.msgs[key]) + ','
data += mavlink_to_json(status.msgs[msg_keys[-1]])
data += '}'
return data | Translate MPStatus in json string | Below is the the instruction that describes the task:
### Input:
Translate MPStatus in json string
### Response:
def mpstatus_to_json(status):
'''Translate MPStatus in json string'''
msg_keys = list(status.msgs.keys())
data = '{'
for key in msg_keys[:-1]:
data += mavlink_to_json(status.msgs... |
def send_rsp_recv_cmd(self, target, data, timeout):
"""While operating as *target* send response *data* to the remote
device and return new command data if received within
*timeout* seconds.
"""
return super(Device, self).send_rsp_recv_cmd(target, data, timeout) | While operating as *target* send response *data* to the remote
device and return new command data if received within
*timeout* seconds. | Below is the the instruction that describes the task:
### Input:
While operating as *target* send response *data* to the remote
device and return new command data if received within
*timeout* seconds.
### Response:
def send_rsp_recv_cmd(self, target, data, timeout):
"""While operating as *t... |
def EndEdit(self, row, col, grid, oldVal=None):
"""
End editing the cell. This function must check if the current
value of the editing control is valid and different from the
original value (available as oldval in its string form.) If
it has not changed then simply return None,... | End editing the cell. This function must check if the current
value of the editing control is valid and different from the
original value (available as oldval in its string form.) If
it has not changed then simply return None, otherwise return
the value in its string form.
*Mus... | Below is the the instruction that describes the task:
### Input:
End editing the cell. This function must check if the current
value of the editing control is valid and different from the
original value (available as oldval in its string form.) If
it has not changed then simply return None... |
def get_bucket_notification(self, bucket_name):
"""
Get notifications configured for the given bucket.
:param bucket_name: Bucket name.
"""
is_valid_bucket_name(bucket_name)
response = self._url_open(
"GET",
bucket_name=bucket_name,
q... | Get notifications configured for the given bucket.
:param bucket_name: Bucket name. | Below is the the instruction that describes the task:
### Input:
Get notifications configured for the given bucket.
:param bucket_name: Bucket name.
### Response:
def get_bucket_notification(self, bucket_name):
"""
Get notifications configured for the given bucket.
:param bucket_n... |
def operation_name(operation, ns):
"""
Convert an operation, obj(s) pair into a swagger operation id.
For compatability with Bravado, we want to use underscores instead of dots and
verb-friendly names. Example:
foo.retrieve => client.foo.retrieve()
foo.search_for.bar => client.fo... | Convert an operation, obj(s) pair into a swagger operation id.
For compatability with Bravado, we want to use underscores instead of dots and
verb-friendly names. Example:
foo.retrieve => client.foo.retrieve()
foo.search_for.bar => client.foo.search_for_bars() | Below is the the instruction that describes the task:
### Input:
Convert an operation, obj(s) pair into a swagger operation id.
For compatability with Bravado, we want to use underscores instead of dots and
verb-friendly names. Example:
foo.retrieve => client.foo.retrieve()
foo.searc... |
def angToPix(nside, lon, lat, nest=False):
"""
Input (lon, lat) in degrees instead of (theta, phi) in radians
"""
theta = np.radians(90. - lat)
phi = np.radians(lon)
return hp.ang2pix(nside, theta, phi, nest=nest) | Input (lon, lat) in degrees instead of (theta, phi) in radians | Below is the the instruction that describes the task:
### Input:
Input (lon, lat) in degrees instead of (theta, phi) in radians
### Response:
def angToPix(nside, lon, lat, nest=False):
"""
Input (lon, lat) in degrees instead of (theta, phi) in radians
"""
theta = np.radians(90. - lat)
phi = np.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.