code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _cell_scalar(self, name=None): """ Returns the cell scalars of a vtk object Parameters ---------- name : str Name of cell scalars to retrive. Returns ------- scalars : np.ndarray Numpy array of scalars """ if ...
Returns the cell scalars of a vtk object Parameters ---------- name : str Name of cell scalars to retrive. Returns ------- scalars : np.ndarray Numpy array of scalars
Below is the the instruction that describes the task: ### Input: Returns the cell scalars of a vtk object Parameters ---------- name : str Name of cell scalars to retrive. Returns ------- scalars : np.ndarray Numpy array of scalars ### Respon...
def _normalize_select_no_context(select, schema=None): """ SAME NORMALIZE, BUT NO SOURCE OF COLUMNS """ if not _Column: _late_import() if is_text(select): select = Data(value=select) else: select = wrap(select) output = select.copy() if not select.value: ...
SAME NORMALIZE, BUT NO SOURCE OF COLUMNS
Below is the the instruction that describes the task: ### Input: SAME NORMALIZE, BUT NO SOURCE OF COLUMNS ### Response: def _normalize_select_no_context(select, schema=None): """ SAME NORMALIZE, BUT NO SOURCE OF COLUMNS """ if not _Column: _late_import() if is_text(select): sel...
def initialize(self, config, context): """We initialize the window duration and slide interval """ if SlidingWindowBolt.WINDOW_DURATION_SECS in config: self.window_duration = int(config[SlidingWindowBolt.WINDOW_DURATION_SECS]) else: self.logger.fatal("Window Duration has to be specified in t...
We initialize the window duration and slide interval
Below is the the instruction that describes the task: ### Input: We initialize the window duration and slide interval ### Response: def initialize(self, config, context): """We initialize the window duration and slide interval """ if SlidingWindowBolt.WINDOW_DURATION_SECS in config: self.window_d...
def _encrypt_xor(a, b, aes): """ Returns encrypt(a ^ b). """ a = unhexlify("%0.32x" % (int((a), 16) ^ int(hexlify(b), 16))) return aes.encrypt(a)
Returns encrypt(a ^ b).
Below is the the instruction that describes the task: ### Input: Returns encrypt(a ^ b). ### Response: def _encrypt_xor(a, b, aes): """ Returns encrypt(a ^ b). """ a = unhexlify("%0.32x" % (int((a), 16) ^ int(hexlify(b), 16))) return aes.encrypt(a)
def add_event(self, name, time, chan): """Action: add a single event.""" self.annot.add_event(name, time, chan=chan) self.update_annotations()
Action: add a single event.
Below is the the instruction that describes the task: ### Input: Action: add a single event. ### Response: def add_event(self, name, time, chan): """Action: add a single event.""" self.annot.add_event(name, time, chan=chan) self.update_annotations()
def push(self): """ Push the changes back to the remote(s) after fetching """ print('pushing...') push_kwargs = {} push_args = [] if self.settings['push.tags']: push_kwargs['push'] = True if self.settings['push.all']: ...
Push the changes back to the remote(s) after fetching
Below is the the instruction that describes the task: ### Input: Push the changes back to the remote(s) after fetching ### Response: def push(self): """ Push the changes back to the remote(s) after fetching """ print('pushing...') push_kwargs = {} push_args = [...
def add_flow(self, flow): """ Add an :class:`Flow` flow to the scheduler. """ if hasattr(self, "_flow"): raise self.Error("Only one flow can be added to the scheduler.") # Check if we are already using a scheduler to run this flow flow.check_pid_file() ...
Add an :class:`Flow` flow to the scheduler.
Below is the the instruction that describes the task: ### Input: Add an :class:`Flow` flow to the scheduler. ### Response: def add_flow(self, flow): """ Add an :class:`Flow` flow to the scheduler. """ if hasattr(self, "_flow"): raise self.Error("Only one flow can be adde...
def share_project(project_id, usernames, read_only, share,**kwargs): """ Share an entire project with a list of users, identifed by their usernames. The read_only flag ('Y' or 'N') must be set to 'Y' to allow write access or sharing. The share flat ('Y' or 'N') must be set ...
Share an entire project with a list of users, identifed by their usernames. The read_only flag ('Y' or 'N') must be set to 'Y' to allow write access or sharing. The share flat ('Y' or 'N') must be set to 'Y' to allow the project to be shared with other users
Below is the the instruction that describes the task: ### Input: Share an entire project with a list of users, identifed by their usernames. The read_only flag ('Y' or 'N') must be set to 'Y' to allow write access or sharing. The share flat ('Y' or 'N') must be set to 'Y' to allow ...
def update_experiment(self, id, key, value): '''Update experiment''' if id not in self.experiments: return False self.experiments[id][key] = value self.write_file() return True
Update experiment
Below is the the instruction that describes the task: ### Input: Update experiment ### Response: def update_experiment(self, id, key, value): '''Update experiment''' if id not in self.experiments: return False self.experiments[id][key] = value self.write_file() r...
def _update_proxy(self, change): """ An observer which sends state change to the proxy. """ if change['name'] in ['row', 'column']: super(AbstractWidgetItem, self)._update_proxy(change) else: self.proxy.data_changed(change)
An observer which sends state change to the proxy.
Below is the the instruction that describes the task: ### Input: An observer which sends state change to the proxy. ### Response: def _update_proxy(self, change): """ An observer which sends state change to the proxy. """ if change['name'] in ['row', 'column']: super(AbstractWid...
def async_atomic(on_exception=None, raise_exception=True, **kwargs): ''' first argument will be a conn object :param func: :return: ''' if not raise_exception and not on_exception: async def default_on_exception(exc): resp_dict = {} resp_dict['status'] = type(exc)...
first argument will be a conn object :param func: :return:
Below is the the instruction that describes the task: ### Input: first argument will be a conn object :param func: :return: ### Response: def async_atomic(on_exception=None, raise_exception=True, **kwargs): ''' first argument will be a conn object :param func: :return: ''' if not ra...
def mode(data): """Compute an intelligent value for the mode The most common value in experimental is not very useful if there are a lot of digits after the comma. This method approaches this issue by rounding to bin size that is determined by the Freedman–Diaconis rule. Parameters -------...
Compute an intelligent value for the mode The most common value in experimental is not very useful if there are a lot of digits after the comma. This method approaches this issue by rounding to bin size that is determined by the Freedman–Diaconis rule. Parameters ---------- data: 1d ndarra...
Below is the the instruction that describes the task: ### Input: Compute an intelligent value for the mode The most common value in experimental is not very useful if there are a lot of digits after the comma. This method approaches this issue by rounding to bin size that is determined by the Freed...
def calculate_error(self): """Estimate the numerical error based on the fluxes calculated by the current and the last method. >>> from hydpy.models.test_v1 import * >>> parameterstep() >>> model.numvars.idx_method = 2 >>> results = numpy.asarray(fluxes.fastaccess._q_resu...
Estimate the numerical error based on the fluxes calculated by the current and the last method. >>> from hydpy.models.test_v1 import * >>> parameterstep() >>> model.numvars.idx_method = 2 >>> results = numpy.asarray(fluxes.fastaccess._q_results) >>> results[:4] = 0., 3.,...
Below is the the instruction that describes the task: ### Input: Estimate the numerical error based on the fluxes calculated by the current and the last method. >>> from hydpy.models.test_v1 import * >>> parameterstep() >>> model.numvars.idx_method = 2 >>> results = numpy.as...
def clean_already_reported(self, comments, file_name, position, message): """ message is potentially a list of messages to post. This is later converted into a string. """ for comment in comments: if ((comment['path'] == file_name and ...
message is potentially a list of messages to post. This is later converted into a string.
Below is the the instruction that describes the task: ### Input: message is potentially a list of messages to post. This is later converted into a string. ### Response: def clean_already_reported(self, comments, file_name, position, message): """ message is po...
def __ssh_gateway_config_dict(gateway): ''' Return a dictionary with gateway options. The result is used to provide arguments to __ssh_gateway_arguments method. ''' extended_kwargs = {} if gateway: extended_kwargs['ssh_gateway'] = gateway['ssh_gateway'] extended_kwargs['ssh_gatew...
Return a dictionary with gateway options. The result is used to provide arguments to __ssh_gateway_arguments method.
Below is the the instruction that describes the task: ### Input: Return a dictionary with gateway options. The result is used to provide arguments to __ssh_gateway_arguments method. ### Response: def __ssh_gateway_config_dict(gateway): ''' Return a dictionary with gateway options. The result is used ...
def export_losses_by_event(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ oq = dstore['oqparam'] writer = writers.CsvWriter(fmt=writers.FIVEDIGITS) dest = dstore.build_fname('losses_by_event', '', 'csv') if oq.calculation_...
:param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
Below is the the instruction that describes the task: ### Input: :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object ### Response: def export_losses_by_event(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore o...
def delete_table(self, instance_id, table_id, project_id=None): """ Deletes the specified table in Cloud Bigtable. Raises google.api_core.exceptions.NotFound if the table does not exist. :type instance_id: str :param instance_id: The ID of the Cloud Bigtable instance. :t...
Deletes the specified table in Cloud Bigtable. Raises google.api_core.exceptions.NotFound if the table does not exist. :type instance_id: str :param instance_id: The ID of the Cloud Bigtable instance. :type table_id: str :param table_id: The ID of the table in Cloud Bigtable. ...
Below is the the instruction that describes the task: ### Input: Deletes the specified table in Cloud Bigtable. Raises google.api_core.exceptions.NotFound if the table does not exist. :type instance_id: str :param instance_id: The ID of the Cloud Bigtable instance. :type table_id: s...
def patch_priority_class(self, name, body, **kwargs): """ partially update the specified PriorityClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_priority_class(name, body, async...
partially update the specified PriorityClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_priority_class(name, body, async_req=True) >>> result = thread.get() :param async_req boo...
Below is the the instruction that describes the task: ### Input: partially update the specified PriorityClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_priority_class(name, body, async_req=...
def create(self, to, channel, custom_message=values.unset): """ Create a new VerificationInstance :param unicode to: To phonenumber :param unicode channel: sms or call :param unicode custom_message: A custom message for this verification :returns: Newly created Verifica...
Create a new VerificationInstance :param unicode to: To phonenumber :param unicode channel: sms or call :param unicode custom_message: A custom message for this verification :returns: Newly created VerificationInstance :rtype: twilio.rest.preview.acc_security.service.verificati...
Below is the the instruction that describes the task: ### Input: Create a new VerificationInstance :param unicode to: To phonenumber :param unicode channel: sms or call :param unicode custom_message: A custom message for this verification :returns: Newly created VerificationInstanc...
def set_default_viewport(self): """ Calculates the viewport based on the configured aspect ratio. Will add black borders and center the viewport if the window do not match the configured viewport. If aspect ratio is None the viewport will be scaled to the entire w...
Calculates the viewport based on the configured aspect ratio. Will add black borders and center the viewport if the window do not match the configured viewport. If aspect ratio is None the viewport will be scaled to the entire window size regardless of size.
Below is the the instruction that describes the task: ### Input: Calculates the viewport based on the configured aspect ratio. Will add black borders and center the viewport if the window do not match the configured viewport. If aspect ratio is None the viewport will be scaled ...
def get_measurements( self, measurement='Weight', lower_bound=None, upper_bound=None ): """ Returns measurements of a given name between two dates.""" if upper_bound is None: upper_bound = datetime.date.today() if lower_bound is None: lower_bound = upper_bound...
Returns measurements of a given name between two dates.
Below is the the instruction that describes the task: ### Input: Returns measurements of a given name between two dates. ### Response: def get_measurements( self, measurement='Weight', lower_bound=None, upper_bound=None ): """ Returns measurements of a given name between two dates.""" i...
async def delete_reply_markup(self): """ Use this method to delete reply markup of messages sent by the bot or via the bot (for inline bots). :return: On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. :rtype: :obj:`...
Use this method to delete reply markup of messages sent by the bot or via the bot (for inline bots). :return: On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. :rtype: :obj:`typing.Union[types.Message, base.Boolean]`
Below is the the instruction that describes the task: ### Input: Use this method to delete reply markup of messages sent by the bot or via the bot (for inline bots). :return: On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. :r...
def isnumber(self, string, *args): """Is number args: string (str): match returns: bool """ try: n, u = utility.analyze_number(string) except SyntaxError: return False return True
Is number args: string (str): match returns: bool
Below is the the instruction that describes the task: ### Input: Is number args: string (str): match returns: bool ### Response: def isnumber(self, string, *args): """Is number args: string (str): match returns: bool ""...
def MatrixSolveLs(a, rhs, l2_reg): """ Matrix least-squares solve op. """ r = np.empty(rhs.shape).astype(a.dtype) for coord in np.ndindex(a.shape[:-2]): pos = coord + (Ellipsis,) r[pos] = np.linalg.lstsq(a[pos], rhs[pos])[0] return r,
Matrix least-squares solve op.
Below is the the instruction that describes the task: ### Input: Matrix least-squares solve op. ### Response: def MatrixSolveLs(a, rhs, l2_reg): """ Matrix least-squares solve op. """ r = np.empty(rhs.shape).astype(a.dtype) for coord in np.ndindex(a.shape[:-2]): pos = coord + (Ellipsis,...
def load_shellcode(shellcode, arch, start_offset=0, load_address=0): """ Load a new project based on a string of raw bytecode. :param shellcode: The data to load :param arch: The name of the arch to use, or an archinfo class :param start_offset: The offset into the data to start...
Load a new project based on a string of raw bytecode. :param shellcode: The data to load :param arch: The name of the arch to use, or an archinfo class :param start_offset: The offset into the data to start analysis (default 0) :param load_address: The address to place the data i...
Below is the the instruction that describes the task: ### Input: Load a new project based on a string of raw bytecode. :param shellcode: The data to load :param arch: The name of the arch to use, or an archinfo class :param start_offset: The offset into the data to start analysis (d...
def start(self): """ Creates a SSL connection to the iDigi Server and sends a ConnectionRequest message. """ self.log.info("Starting SSL Session for Monitor %s." % self.monitor_id) if self.socket is not None: raise Exception("Socket alrea...
Creates a SSL connection to the iDigi Server and sends a ConnectionRequest message.
Below is the the instruction that describes the task: ### Input: Creates a SSL connection to the iDigi Server and sends a ConnectionRequest message. ### Response: def start(self): """ Creates a SSL connection to the iDigi Server and sends a ConnectionRequest message. """ ...
def filter_t(func): """ Transformation for Sequence.filter :param func: filter function :return: transformation """ return Transformation('filter({0})'.format(name(func)), partial(filter, func), {ExecutionStrategies.PARALLEL})
Transformation for Sequence.filter :param func: filter function :return: transformation
Below is the the instruction that describes the task: ### Input: Transformation for Sequence.filter :param func: filter function :return: transformation ### Response: def filter_t(func): """ Transformation for Sequence.filter :param func: filter function :return: transformation """ ...
def Client(api_version, *args, **kwargs): """Return an neutron client. @param api_version: only 2.0 is supported now """ neutron_client = utils.get_client_class( API_NAME, api_version, API_VERSIONS, ) return neutron_client(*args, **kwargs)
Return an neutron client. @param api_version: only 2.0 is supported now
Below is the the instruction that describes the task: ### Input: Return an neutron client. @param api_version: only 2.0 is supported now ### Response: def Client(api_version, *args, **kwargs): """Return an neutron client. @param api_version: only 2.0 is supported now """ neutron_client = util...
def get_colour(index): """ get color number index. """ colours = [ 'red', 'blue', 'green', 'pink', 'yellow', 'magenta', 'orange', 'cyan', ] default_colour = 'purple' if index < len(colours): return colours[index] else: return default_colour
get color number index.
Below is the the instruction that describes the task: ### Input: get color number index. ### Response: def get_colour(index): """ get color number index. """ colours = [ 'red', 'blue', 'green', 'pink', 'yellow', 'magenta', 'orange', 'cyan', ] default_colour = 'purple' if index <...
def t_BOOL(self, t): r'true|false' t.value = True if t.value == 'true' else False return t
r'true|false
Below is the the instruction that describes the task: ### Input: r'true|false ### Response: def t_BOOL(self, t): r'true|false' t.value = True if t.value == 'true' else False return t
def listdir(p, match='*', exclude='', listtype='file', matchfun=None): """ list file(or folder) for this path (NOT recursive) :param p: :param match: :param exclude: :param listtype: ('file' | 'filepath' |'dir' | 'all') :param matchfun: match fun (default fnmatch.fnmatch) True/False = matchf...
list file(or folder) for this path (NOT recursive) :param p: :param match: :param exclude: :param listtype: ('file' | 'filepath' |'dir' | 'all') :param matchfun: match fun (default fnmatch.fnmatch) True/False = matchfun(name, pattern) :rtype:
Below is the the instruction that describes the task: ### Input: list file(or folder) for this path (NOT recursive) :param p: :param match: :param exclude: :param listtype: ('file' | 'filepath' |'dir' | 'all') :param matchfun: match fun (default fnmatch.fnmatch) True/False = matchfun(name, patte...
def get_listing(self): ''' This function gets all of the information that we need to either render or validate the form. It is structured to avoid duplicate DB queries ''' if not hasattr(self,'listing'): allEvents = self.get_allEvents() openEvents = allE...
This function gets all of the information that we need to either render or validate the form. It is structured to avoid duplicate DB queries
Below is the the instruction that describes the task: ### Input: This function gets all of the information that we need to either render or validate the form. It is structured to avoid duplicate DB queries ### Response: def get_listing(self): ''' This function gets all of the information t...
def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Performs SNMP GETNEXT query. Based on passed parameters, prepares SNMP GETNEXT packet (:RFC:`1905#section-4.2.2`) and schedules its transmission by :mod:`twisted` I/O framework at a later point of time...
Performs SNMP GETNEXT query. Based on passed parameters, prepares SNMP GETNEXT packet (:RFC:`1905#section-4.2.2`) and schedules its transmission by :mod:`twisted` I/O framework at a later point of time. Parameters ---------- snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine` Class instance...
Below is the the instruction that describes the task: ### Input: Performs SNMP GETNEXT query. Based on passed parameters, prepares SNMP GETNEXT packet (:RFC:`1905#section-4.2.2`) and schedules its transmission by :mod:`twisted` I/O framework at a later point of time. Parameters ---------- ...
def lookup_comment_list(self): """Lookup list of comments for an issue. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :returns: The pair (ISSUE, COMMENTS) where ISSUE is a dict for the main issue and COMMENTS is a list of comments on the issue. ~-~-~-~-~-~...
Lookup list of comments for an issue. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :returns: The pair (ISSUE, COMMENTS) where ISSUE is a dict for the main issue and COMMENTS is a list of comments on the issue. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~...
Below is the the instruction that describes the task: ### Input: Lookup list of comments for an issue. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :returns: The pair (ISSUE, COMMENTS) where ISSUE is a dict for the main issue and COMMENTS is a list of comments on the ...
def resample_nn_1d(a, centers): """Return one-dimensional nearest-neighbor indexes based on user-specified centers. Parameters ---------- a : array-like 1-dimensional array of numeric values from which to extract indexes of nearest-neighbors centers : array-like 1-dimensiona...
Return one-dimensional nearest-neighbor indexes based on user-specified centers. Parameters ---------- a : array-like 1-dimensional array of numeric values from which to extract indexes of nearest-neighbors centers : array-like 1-dimensional array of numeric values representing ...
Below is the the instruction that describes the task: ### Input: Return one-dimensional nearest-neighbor indexes based on user-specified centers. Parameters ---------- a : array-like 1-dimensional array of numeric values from which to extract indexes of nearest-neighbors centers : a...
def now_playing(self, **kwargs): """ Get the list of movies playing in theatres. This list refreshes every day. The maximum number of items this list will include is 100. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optiona...
Get the list of movies playing in theatres. This list refreshes every day. The maximum number of items this list will include is 100. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. Returns: A di...
Below is the the instruction that describes the task: ### Input: Get the list of movies playing in theatres. This list refreshes every day. The maximum number of items this list will include is 100. Args: page: (optional) Minimum value of 1. Expected value is an integer. la...
def read_key(suppress=False): """ Blocks until a keyboard event happens, then returns that event's name or, if missing, its scan code. """ event = read_event(suppress) return event.name or event.scan_code
Blocks until a keyboard event happens, then returns that event's name or, if missing, its scan code.
Below is the the instruction that describes the task: ### Input: Blocks until a keyboard event happens, then returns that event's name or, if missing, its scan code. ### Response: def read_key(suppress=False): """ Blocks until a keyboard event happens, then returns that event's name or, if missing,...
def backend_from_fname(name): """Determine backend module object from a file name.""" ext = splitext(name)[1] try: mime = EXTS_TO_MIMETYPES[ext] except KeyError: try: f = open(name, 'rb') except IOError as e: # The file may not exist, we are being asked...
Determine backend module object from a file name.
Below is the the instruction that describes the task: ### Input: Determine backend module object from a file name. ### Response: def backend_from_fname(name): """Determine backend module object from a file name.""" ext = splitext(name)[1] try: mime = EXTS_TO_MIMETYPES[ext] except KeyError...
def get_badge_image_url(pid, ext='svg'): """Return the badge for a DOI.""" return url_for('invenio_formatter_badges.badge', title=pid.pid_type, value=pid.pid_value, ext=ext)
Return the badge for a DOI.
Below is the the instruction that describes the task: ### Input: Return the badge for a DOI. ### Response: def get_badge_image_url(pid, ext='svg'): """Return the badge for a DOI.""" return url_for('invenio_formatter_badges.badge', title=pid.pid_type, value=pid.pid_value, ext=ext)
def design_z_filter_single_pole(filt_str, max_gain_freq): """ Finds the coefficients for a simple lowpass/highpass filter. This function just prints the coefficient values, besides the given filter equation and its power gain. There's 3 constraints used to find the coefficients: 1. The G value is defined ...
Finds the coefficients for a simple lowpass/highpass filter. This function just prints the coefficient values, besides the given filter equation and its power gain. There's 3 constraints used to find the coefficients: 1. The G value is defined by the max gain of 1 (0 dB) imposed at a specific frequency ...
Below is the the instruction that describes the task: ### Input: Finds the coefficients for a simple lowpass/highpass filter. This function just prints the coefficient values, besides the given filter equation and its power gain. There's 3 constraints used to find the coefficients: 1. The G value is defin...
def multipath_flush(device): ''' Device-Mapper Multipath flush CLI Example: .. code-block:: bash salt '*' devmap.multipath_flush mpath1 ''' if not os.path.exists(device): return '{0} does not exist'.format(device) cmd = 'multipath -f {0}'.format(device) return __salt_...
Device-Mapper Multipath flush CLI Example: .. code-block:: bash salt '*' devmap.multipath_flush mpath1
Below is the the instruction that describes the task: ### Input: Device-Mapper Multipath flush CLI Example: .. code-block:: bash salt '*' devmap.multipath_flush mpath1 ### Response: def multipath_flush(device): ''' Device-Mapper Multipath flush CLI Example: .. code-block:: bash...
def inflate(self): """Load the resource from the server, if not already loaded.""" if not self._is_inflated: if self._is_inflating: # catch infinite recursion when attempting to inflate # an object that doesn't have enough data to inflate msg...
Load the resource from the server, if not already loaded.
Below is the the instruction that describes the task: ### Input: Load the resource from the server, if not already loaded. ### Response: def inflate(self): """Load the resource from the server, if not already loaded.""" if not self._is_inflated: if self._is_inflating: # ...
def trend(self, order=LINEAR): '''Override Series.trend() to return a TimeSeries instance.''' coefficients = self.trend_coefficients(order) x = self.timestamps trend_y = LazyImport.numpy().polyval(coefficients, x) return TimeSeries(zip(x, trend_y))
Override Series.trend() to return a TimeSeries instance.
Below is the the instruction that describes the task: ### Input: Override Series.trend() to return a TimeSeries instance. ### Response: def trend(self, order=LINEAR): '''Override Series.trend() to return a TimeSeries instance.''' coefficients = self.trend_coefficients(order) x = self.timest...
def handle_request(self, filter_name, path): """ Handle image request :param filter_name: filter_name :param path: image_path :return: """ if filter_name in self._filter_sets: if self._filter_sets[filter_name]['cached']: cached_item_pat...
Handle image request :param filter_name: filter_name :param path: image_path :return:
Below is the the instruction that describes the task: ### Input: Handle image request :param filter_name: filter_name :param path: image_path :return: ### Response: def handle_request(self, filter_name, path): """ Handle image request :param filter_name: filter_name ...
def run(self): """ Run the given command and yield each line(s) one by one. .. note:: The difference between this method and :code:`self.execute()` is that :code:`self.execute()` wait for the process to end in order to return its output. """ ...
Run the given command and yield each line(s) one by one. .. note:: The difference between this method and :code:`self.execute()` is that :code:`self.execute()` wait for the process to end in order to return its output.
Below is the the instruction that describes the task: ### Input: Run the given command and yield each line(s) one by one. .. note:: The difference between this method and :code:`self.execute()` is that :code:`self.execute()` wait for the process to end in order to return...
def _locate_file(f, base_dir): """ Utility method for finding full path to a filename as string """ if base_dir == None: return f file_name = os.path.join(base_dir, f) real = os.path.realpath(file_name) #print_v('- Located %s at %s'%(f,real)) return real
Utility method for finding full path to a filename as string
Below is the the instruction that describes the task: ### Input: Utility method for finding full path to a filename as string ### Response: def _locate_file(f, base_dir): """ Utility method for finding full path to a filename as string """ if base_dir == None: return f file_name = os.pa...
def table(self, name, database=None, schema=None): """Create a table expression that references a particular a table called `name` in a MySQL database called `database`. Parameters ---------- name : str The name of the table to retrieve. database : str, optio...
Create a table expression that references a particular a table called `name` in a MySQL database called `database`. Parameters ---------- name : str The name of the table to retrieve. database : str, optional The database in which the table referred to by...
Below is the the instruction that describes the task: ### Input: Create a table expression that references a particular a table called `name` in a MySQL database called `database`. Parameters ---------- name : str The name of the table to retrieve. database : str...
def draw(self): """ Renders the class balance chart on the specified axes from support. """ # Number of colors is either number of classes or 2 colors = resolve_colors(len(self.support_)) if self._mode == BALANCE: self.ax.bar( np.arange(len(se...
Renders the class balance chart on the specified axes from support.
Below is the the instruction that describes the task: ### Input: Renders the class balance chart on the specified axes from support. ### Response: def draw(self): """ Renders the class balance chart on the specified axes from support. """ # Number of colors is either number of class...
def run_HTM_false_positive_experiment_synapses(num_neurons = 1, a = 512, dim = 16000, num_samples = 1000, num_dendrites = 500, test_dendrite_lengths = range(2, 32, 2), nu...
Run an experiment to test the false positive rate based on number of synapses per dendrite, dimension and sparsity. Uses a single neuron, with a threshold nonlinearity of theta = s/2. Based on figure 5B in the original SDR paper. The parameters used in generating the figure for this experiment are: 1. a =...
Below is the the instruction that describes the task: ### Input: Run an experiment to test the false positive rate based on number of synapses per dendrite, dimension and sparsity. Uses a single neuron, with a threshold nonlinearity of theta = s/2. Based on figure 5B in the original SDR paper. The parame...
def source_table(self): """Source table (`~astropy.table.Table`). Columns: GLON, GLAT, COUNTS """ table = Table() table['GLON'] = np.array([0, 45, 45], dtype='float32') table['GLAT'] = np.array([0, 0, 45], dtype='float32') table['COUNTS'] = np.array([100, 100, 1...
Source table (`~astropy.table.Table`). Columns: GLON, GLAT, COUNTS
Below is the the instruction that describes the task: ### Input: Source table (`~astropy.table.Table`). Columns: GLON, GLAT, COUNTS ### Response: def source_table(self): """Source table (`~astropy.table.Table`). Columns: GLON, GLAT, COUNTS """ table = Table() tab...
def read_smet(filename, mode): """Reads smet data and returns the data in required dataformat (pd df) See https://models.slf.ch/docserver/meteoio/SMET_specifications.pdf for further details on the specifications of this file format. Parameters ---- filename : SMET file to read mode : "...
Reads smet data and returns the data in required dataformat (pd df) See https://models.slf.ch/docserver/meteoio/SMET_specifications.pdf for further details on the specifications of this file format. Parameters ---- filename : SMET file to read mode : "d" for daily and "h" for hourly input ...
Below is the the instruction that describes the task: ### Input: Reads smet data and returns the data in required dataformat (pd df) See https://models.slf.ch/docserver/meteoio/SMET_specifications.pdf for further details on the specifications of this file format. Parameters ---- filename : SME...
def _get_pos(self): """ Get current position for scroll bar. """ if self._canvas.height >= self._max_height: return 0 else: return self._canvas.start_line / (self._max_height - self._canvas.height + 1)
Get current position for scroll bar.
Below is the the instruction that describes the task: ### Input: Get current position for scroll bar. ### Response: def _get_pos(self): """ Get current position for scroll bar. """ if self._canvas.height >= self._max_height: return 0 else: return self...
def more_statements(self, more_url): """Query the LRS for more statements :param more_url: URL from a StatementsResult object used to retrieve more statements :type more_url: str | unicode :return: LRS Response object with the returned StatementsResult object as content :rtype: ...
Query the LRS for more statements :param more_url: URL from a StatementsResult object used to retrieve more statements :type more_url: str | unicode :return: LRS Response object with the returned StatementsResult object as content :rtype: :class:`tincan.lrs_response.LRSResponse`
Below is the the instruction that describes the task: ### Input: Query the LRS for more statements :param more_url: URL from a StatementsResult object used to retrieve more statements :type more_url: str | unicode :return: LRS Response object with the returned StatementsResult object as con...
def obfn_reg(self): r"""Compute regularisation terms and contribution to objective function. Regularisation terms are :math:`\| Y \|_1` and :math:`\| Y \|_{2,1}`. """ rl21 = np.sum(self.wl21 * np.sqrt(np.sum(self.obfn_gvar()**2, a...
r"""Compute regularisation terms and contribution to objective function. Regularisation terms are :math:`\| Y \|_1` and :math:`\| Y \|_{2,1}`.
Below is the the instruction that describes the task: ### Input: r"""Compute regularisation terms and contribution to objective function. Regularisation terms are :math:`\| Y \|_1` and :math:`\| Y \|_{2,1}`. ### Response: def obfn_reg(self): r"""Compute regularisation terms and contribution...
def add_date_facet(self, *args, **kwargs): """Add a date factory facet""" self.facets.append(DateHistogramFacet(*args, **kwargs))
Add a date factory facet
Below is the the instruction that describes the task: ### Input: Add a date factory facet ### Response: def add_date_facet(self, *args, **kwargs): """Add a date factory facet""" self.facets.append(DateHistogramFacet(*args, **kwargs))
def triangle_normal(a,b,c): ''' triangle_normal(a, b, c) yields the normal vector of the triangle whose vertices are given by the points a, b, and c. If the points are 2D points, then 3D normal vectors are still yielded, that are always (0,0,1) or (0,0,-1). This function auto-threads over matrices, ...
triangle_normal(a, b, c) yields the normal vector of the triangle whose vertices are given by the points a, b, and c. If the points are 2D points, then 3D normal vectors are still yielded, that are always (0,0,1) or (0,0,-1). This function auto-threads over matrices, in which case they must be in equi...
Below is the the instruction that describes the task: ### Input: triangle_normal(a, b, c) yields the normal vector of the triangle whose vertices are given by the points a, b, and c. If the points are 2D points, then 3D normal vectors are still yielded, that are always (0,0,1) or (0,0,-1). This function...
def get_direct_derivatives(self, address): """Get all targets derived directly from the specified target. Note that the specified target itself is not returned. :API: public """ derivative_addrs = self._derivatives_by_derived_from.get(address, []) return [self.get_target(addr) for addr in deri...
Get all targets derived directly from the specified target. Note that the specified target itself is not returned. :API: public
Below is the the instruction that describes the task: ### Input: Get all targets derived directly from the specified target. Note that the specified target itself is not returned. :API: public ### Response: def get_direct_derivatives(self, address): """Get all targets derived directly from the specif...
def switchport_list(self): """list[dict]:A list of dictionary items describing the details of list of dictionary items describing the details of switch port""" urn = "{urn:brocade.com:mgmt:brocade-interface-ext}" result = [] request_interface = self.get_interface_switchport_requ...
list[dict]:A list of dictionary items describing the details of list of dictionary items describing the details of switch port
Below is the the instruction that describes the task: ### Input: list[dict]:A list of dictionary items describing the details of list of dictionary items describing the details of switch port ### Response: def switchport_list(self): """list[dict]:A list of dictionary items describing the details ...
def scene_color(frames): """parse a scene.color message""" # "scene.color" <scene_id> <color> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").uint8_3("color").assert_end().get() if results.command != "scene.color": raise MessagePar...
parse a scene.color message
Below is the the instruction that describes the task: ### Input: parse a scene.color message ### Response: def scene_color(frames): """parse a scene.color message""" # "scene.color" <scene_id> <color> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id...
def _append_log(self, specs): """ The log contains the tids and corresponding specifications used during launch with the specifications in JSON format. """ self._spec_log += specs # This should be removed log_path = os.path.join(self.root_directory, ("%s.log" % self.batch...
The log contains the tids and corresponding specifications used during launch with the specifications in JSON format.
Below is the the instruction that describes the task: ### Input: The log contains the tids and corresponding specifications used during launch with the specifications in JSON format. ### Response: def _append_log(self, specs): """ The log contains the tids and corresponding specifications ...
def SETNS(cpu, dest): """ Sets byte if not sign. :param cpu: current CPU. :param dest: destination operand. """ dest.write(Operators.ITEBV(dest.size, cpu.SF == False, 1, 0))
Sets byte if not sign. :param cpu: current CPU. :param dest: destination operand.
Below is the the instruction that describes the task: ### Input: Sets byte if not sign. :param cpu: current CPU. :param dest: destination operand. ### Response: def SETNS(cpu, dest): """ Sets byte if not sign. :param cpu: current CPU. :param dest: destination opera...
def _purge_jobs(timestamp): ''' Purge records from the returner tables. :param job_age_in_seconds: Purge jobs older than this :return: ''' with _get_serv() as cur: try: sql = 'delete from `jids` where jid in (select distinct jid from salt_returns where alter_time < %s)' ...
Purge records from the returner tables. :param job_age_in_seconds: Purge jobs older than this :return:
Below is the the instruction that describes the task: ### Input: Purge records from the returner tables. :param job_age_in_seconds: Purge jobs older than this :return: ### Response: def _purge_jobs(timestamp): ''' Purge records from the returner tables. :param job_age_in_seconds: Purge jobs o...
def set_completed(self, *, completition_date=None): """ Sets this message flag as completed :param completition_date: the datetime this followUp was completed """ self.__status = Flag.Complete completition_date = completition_date or dt.datetime.now() if completition_date...
Sets this message flag as completed :param completition_date: the datetime this followUp was completed
Below is the the instruction that describes the task: ### Input: Sets this message flag as completed :param completition_date: the datetime this followUp was completed ### Response: def set_completed(self, *, completition_date=None): """ Sets this message flag as completed :param completiti...
def _get_best_percentile(self, cluster, counts): ''' return all UMIs with counts >1% of the median counts in the cluster ''' if len(cluster) == 1: return list(cluster) else: threshold = np.median(list(counts.values()))/100 return [read for read in clu...
return all UMIs with counts >1% of the median counts in the cluster
Below is the the instruction that describes the task: ### Input: return all UMIs with counts >1% of the median counts in the cluster ### Response: def _get_best_percentile(self, cluster, counts): ''' return all UMIs with counts >1% of the median counts in the cluster ''' if len(clu...
def move_to(self, x, y, pre_dl=None, post_dl=None): """Move mouse to (x, y) **中文文档** 移动鼠标到 (x, y) 的坐标处。 """ self.delay(pre_dl) self.m.move(x, y) self.delay(post_dl)
Move mouse to (x, y) **中文文档** 移动鼠标到 (x, y) 的坐标处。
Below is the the instruction that describes the task: ### Input: Move mouse to (x, y) **中文文档** 移动鼠标到 (x, y) 的坐标处。 ### Response: def move_to(self, x, y, pre_dl=None, post_dl=None): """Move mouse to (x, y) **中文文档** 移动鼠标到 (x, y) 的坐标处。 """ self.delay(pre_dl) ...
def sha1(filename): """Return SHA1 of filename.""" filename = unmap_file(filename) if filename not in file_cache: cache_file(filename) if filename not in file_cache: return None pass if file_cache[filename].sha1: return file_cache[filename].sha1.hexdigest() ...
Return SHA1 of filename.
Below is the the instruction that describes the task: ### Input: Return SHA1 of filename. ### Response: def sha1(filename): """Return SHA1 of filename.""" filename = unmap_file(filename) if filename not in file_cache: cache_file(filename) if filename not in file_cache: retur...
def write_crtf(regions, filename, coordsys='fk5', fmt='.6f', radunit='deg'): """ Converts a `list` of `~regions.Region` to CRTF string and write to file. Parameters ---------- regions : `list` List of `~regions.Region` objects filename : `str` Filename in which the string is to ...
Converts a `list` of `~regions.Region` to CRTF string and write to file. Parameters ---------- regions : `list` List of `~regions.Region` objects filename : `str` Filename in which the string is to be written. Default is 'new.crtf' coordsys : `str`, optional Astropy Coordina...
Below is the the instruction that describes the task: ### Input: Converts a `list` of `~regions.Region` to CRTF string and write to file. Parameters ---------- regions : `list` List of `~regions.Region` objects filename : `str` Filename in which the string is to be written. Default ...
def replace_wildcards(string, wildcard, regex): """ Replace wildcard symbols with regular expressions :param wildcard: :type wildcard: _sre.SRE_Pattern :param regex: :type regex: str :rtype: tuple of (str, bool) """ replaced = False mat...
Replace wildcard symbols with regular expressions :param wildcard: :type wildcard: _sre.SRE_Pattern :param regex: :type regex: str :rtype: tuple of (str, bool)
Below is the the instruction that describes the task: ### Input: Replace wildcard symbols with regular expressions :param wildcard: :type wildcard: _sre.SRE_Pattern :param regex: :type regex: str :rtype: tuple of (str, bool) ### Response: def replace_wildcards(string, wi...
def do_dot2(self, args, arguments): """ :: Usage: dot2 FILENAME FORMAT Export the data in cvs format to a file. Former cvs command Arguments: FILENAME The filename FORMAT the export format, pdf, png, ... ...
:: Usage: dot2 FILENAME FORMAT Export the data in cvs format to a file. Former cvs command Arguments: FILENAME The filename FORMAT the export format, pdf, png, ...
Below is the the instruction that describes the task: ### Input: :: Usage: dot2 FILENAME FORMAT Export the data in cvs format to a file. Former cvs command Arguments: FILENAME The filename FORMAT the export format, pdf, ...
def fill_missing_info(info: dict, site_url: str = DEFAULT_SITE) -> dict: "Add missing info in a censored post info dict." try: md5, ext = find_censored_md5ext(info["id"]) except TypeError: # None returned by find_.. return info sample_ext = "jpg" if ext != "zip" else "webm" if inf...
Add missing info in a censored post info dict.
Below is the the instruction that describes the task: ### Input: Add missing info in a censored post info dict. ### Response: def fill_missing_info(info: dict, site_url: str = DEFAULT_SITE) -> dict: "Add missing info in a censored post info dict." try: md5, ext = find_censored_md5ext(info["id"]) ...
def to_ngrams(self, terms): ''' Converts terms to all possibe ngrams terms: list of terms ''' if len(terms) <= self.n: return terms if self.n == 1: n_grams = [[term] for term in terms] else: n_grams = [] for i in range(...
Converts terms to all possibe ngrams terms: list of terms
Below is the the instruction that describes the task: ### Input: Converts terms to all possibe ngrams terms: list of terms ### Response: def to_ngrams(self, terms): ''' Converts terms to all possibe ngrams terms: list of terms ''' if len(terms) <= self.n: ...
def get_daily_songs(self): """ 获取每日推荐歌曲 """ self._daily_playlist = douban.get_daily_songs() # 加入索引 for index, i in enumerate(self._daily_playlist): i['title'] = str(index + 1) + '/' + str(len(self._daily_playlist)) + ' ' + i['title']
获取每日推荐歌曲
Below is the the instruction that describes the task: ### Input: 获取每日推荐歌曲 ### Response: def get_daily_songs(self): """ 获取每日推荐歌曲 """ self._daily_playlist = douban.get_daily_songs() # 加入索引 for index, i in enumerate(self._daily_playlist): i['title'] = str(i...
def clean_code(self, name, forbidden): """ Remove lines containing items in 'forbidden' from the code. Helpful for executing converted notebooks that still retain IPython magic commands. """ code = self.read_code(name) code = code.split('\n') new_code = [...
Remove lines containing items in 'forbidden' from the code. Helpful for executing converted notebooks that still retain IPython magic commands.
Below is the the instruction that describes the task: ### Input: Remove lines containing items in 'forbidden' from the code. Helpful for executing converted notebooks that still retain IPython magic commands. ### Response: def clean_code(self, name, forbidden): """ Remove lines cont...
def parse_roles(self, fetched_role, params): """ Parse a single IAM role and fetch additional data """ role = {} role['instances_count'] = 'N/A' # When resuming upon throttling error, skip if already fetched if fetched_role['RoleName'] in self.roles: r...
Parse a single IAM role and fetch additional data
Below is the the instruction that describes the task: ### Input: Parse a single IAM role and fetch additional data ### Response: def parse_roles(self, fetched_role, params): """ Parse a single IAM role and fetch additional data """ role = {} role['instances_count'] = 'N/A' ...
def init_input_obj(self): """Section 4 - Create uwg objects from input parameters self.simTime # simulation time parameter obj self.weather # weather obj for simulation time period self.forcIP # Forcing obj self.forc ...
Section 4 - Create uwg objects from input parameters self.simTime # simulation time parameter obj self.weather # weather obj for simulation time period self.forcIP # Forcing obj self.forc # Empty forcing obj ...
Below is the the instruction that describes the task: ### Input: Section 4 - Create uwg objects from input parameters self.simTime # simulation time parameter obj self.weather # weather obj for simulation time period self.forcIP # Forcing ob...
def interpolate_bilinear_lonlat(self, lon, lat, values): """ Interpolate values at specific longitudes/latitudes using bilinear interpolation If a position does not have four neighbours, this currently returns NaN. Parameters ---------- lon, lat : :class:`~astropy.units...
Interpolate values at specific longitudes/latitudes using bilinear interpolation If a position does not have four neighbours, this currently returns NaN. Parameters ---------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude values as :class:`~astropy....
Below is the the instruction that describes the task: ### Input: Interpolate values at specific longitudes/latitudes using bilinear interpolation If a position does not have four neighbours, this currently returns NaN. Parameters ---------- lon, lat : :class:`~astropy.units.Quantit...
def xml_to_string(elem, qualified_name=None, public_id=None, system_id=None): """ Return a pretty-printed XML string for the Element. Also allows setting a document type. """ from xml.dom import minidom rough_string = ET.tostring(elem, 'utf-8') reparsed = minidom.parseString(rough_string) ...
Return a pretty-printed XML string for the Element. Also allows setting a document type.
Below is the the instruction that describes the task: ### Input: Return a pretty-printed XML string for the Element. Also allows setting a document type. ### Response: def xml_to_string(elem, qualified_name=None, public_id=None, system_id=None): """ Return a pretty-printed XML string for the Element. ...
def from_dict(config): ''' Instantiate a new ProxyConfig from a dictionary that represents a client configuration, as described in `the documentation`_. .. _the documentation: https://docs.docker.com/network/proxy/#configure-the-docker-client ''' return Proxy...
Instantiate a new ProxyConfig from a dictionary that represents a client configuration, as described in `the documentation`_. .. _the documentation: https://docs.docker.com/network/proxy/#configure-the-docker-client
Below is the the instruction that describes the task: ### Input: Instantiate a new ProxyConfig from a dictionary that represents a client configuration, as described in `the documentation`_. .. _the documentation: https://docs.docker.com/network/proxy/#configure-the-docker-client ### Re...
def compress(self, condition, axis=0, out=None): """Return selected slices of an array along given axis. Parameters ---------- condition : array_like, bool Array that selects which entries to return. N.B., if len(condition) is less than the size of the given axis...
Return selected slices of an array along given axis. Parameters ---------- condition : array_like, bool Array that selects which entries to return. N.B., if len(condition) is less than the size of the given axis, then output is truncated to the length of the ...
Below is the the instruction that describes the task: ### Input: Return selected slices of an array along given axis. Parameters ---------- condition : array_like, bool Array that selects which entries to return. N.B., if len(condition) is less than the size of the g...
def normalize(self, bias_range=1, poly_range=None, ignored_terms=None): """Normalizes the biases of the binary polynomial such that they fall in the provided range(s). If `poly_range` is provided, then `bias_range` will be treated as the range for the linear biases and `poly_range` will...
Normalizes the biases of the binary polynomial such that they fall in the provided range(s). If `poly_range` is provided, then `bias_range` will be treated as the range for the linear biases and `poly_range` will be used for the range of the other biases. Args: bias...
Below is the the instruction that describes the task: ### Input: Normalizes the biases of the binary polynomial such that they fall in the provided range(s). If `poly_range` is provided, then `bias_range` will be treated as the range for the linear biases and `poly_range` will be used for ...
def readcols(infile, cols=[0, 1, 2, 3], hms=False): """ Read the columns from an ASCII file as numpy arrays. Parameters ---------- infile : str Filename of ASCII file with array data as columns. cols : list of int List of 0-indexed column numbers for columns to be turned into n...
Read the columns from an ASCII file as numpy arrays. Parameters ---------- infile : str Filename of ASCII file with array data as columns. cols : list of int List of 0-indexed column numbers for columns to be turned into numpy arrays (DEFAULT- [0,1,2,3]). Returns -----...
Below is the the instruction that describes the task: ### Input: Read the columns from an ASCII file as numpy arrays. Parameters ---------- infile : str Filename of ASCII file with array data as columns. cols : list of int List of 0-indexed column numbers for columns to be turned i...
def del_application(self, application, sync=True): """ delete application from this company :param application: the subnet to be deleted from this company :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the application object on list to be re...
delete application from this company :param application: the subnet to be deleted from this company :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the application object on list to be removed on next save(). :return:
Below is the the instruction that describes the task: ### Input: delete application from this company :param application: the subnet to be deleted from this company :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the application object on list to be remo...
def start(self, on_add, on_update, on_delete): """ Starts monitoring the file path, passing along on_(add|update|delete) callbacks to a watchdog observer. Iterates over the files in the target path before starting the observer and calls the on_created callback before starting th...
Starts monitoring the file path, passing along on_(add|update|delete) callbacks to a watchdog observer. Iterates over the files in the target path before starting the observer and calls the on_created callback before starting the observer, so that existing files aren't missed.
Below is the the instruction that describes the task: ### Input: Starts monitoring the file path, passing along on_(add|update|delete) callbacks to a watchdog observer. Iterates over the files in the target path before starting the observer and calls the on_created callback before starting ...
def __process_by_python(self): """! @brief Performs processing using python code. """ self.__scores = {} for k in range(self.__kmin, self.__kmax): clusters = self.__calculate_clusters(k) if len(clusters) != k: self.__scores[k] =...
! @brief Performs processing using python code.
Below is the the instruction that describes the task: ### Input: ! @brief Performs processing using python code. ### Response: def __process_by_python(self): """! @brief Performs processing using python code. """ self.__scores = {} for k in range(self.__kmi...
def _call(self, x): """Return wavelet transform of ``x``.""" if self.impl == 'pywt': coeffs = pywt.wavedecn( x, wavelet=self.pywt_wavelet, level=self.nlevels, mode=self.pywt_pad_mode, axes=self.axes) return pywt.ravel_coeffs(coeffs, axes=self.axes)...
Return wavelet transform of ``x``.
Below is the the instruction that describes the task: ### Input: Return wavelet transform of ``x``. ### Response: def _call(self, x): """Return wavelet transform of ``x``.""" if self.impl == 'pywt': coeffs = pywt.wavedecn( x, wavelet=self.pywt_wavelet, level=self.nlevels...
def run(self, arguments=None, get_unknowns=False): """ Init point to execute the script. If `arguments` string is given, will evaluate the arguments, else evaluates sys.argv. Any inheriting class should extend the run method (but first calling BaseCmdLineTool.run(self)). ...
Init point to execute the script. If `arguments` string is given, will evaluate the arguments, else evaluates sys.argv. Any inheriting class should extend the run method (but first calling BaseCmdLineTool.run(self)).
Below is the the instruction that describes the task: ### Input: Init point to execute the script. If `arguments` string is given, will evaluate the arguments, else evaluates sys.argv. Any inheriting class should extend the run method (but first calling BaseCmdLineTool.run(self)). ### Respo...
def close(self): """Close the cursor""" if self.closed or self.connection.closed: return self._cursor.close() self.closed = True
Close the cursor
Below is the the instruction that describes the task: ### Input: Close the cursor ### Response: def close(self): """Close the cursor""" if self.closed or self.connection.closed: return self._cursor.close() self.closed = True
def _processSegmentUpdates(self, activeColumns): """ Go through the list of accumulated segment updates and process them as follows: if the segment update is too old, remove the update else if the cell received bottom-up, update its permanences else if it's still being predicted, leave it in th...
Go through the list of accumulated segment updates and process them as follows: if the segment update is too old, remove the update else if the cell received bottom-up, update its permanences else if it's still being predicted, leave it in the queue else remove it. :param activeColumns TODO: d...
Below is the the instruction that describes the task: ### Input: Go through the list of accumulated segment updates and process them as follows: if the segment update is too old, remove the update else if the cell received bottom-up, update its permanences else if it's still being predicted, leave ...
def heartbeat(self): """Heartbeat request to keep session alive. """ unique_id = self.new_unique_id() message = { 'op': 'heartbeat', 'id': unique_id, } self._send(message) return unique_id
Heartbeat request to keep session alive.
Below is the the instruction that describes the task: ### Input: Heartbeat request to keep session alive. ### Response: def heartbeat(self): """Heartbeat request to keep session alive. """ unique_id = self.new_unique_id() message = { 'op': 'heartbeat', 'id': ...
def get_value_from_user(sc): """ Prompts the user for a value for the symbol or choice 'sc'. For bool/tristate symbols and choices, provides a list of all the assignable values. """ if not sc.visibility: print(sc.name + " is not currently visible") return False prompt = "Val...
Prompts the user for a value for the symbol or choice 'sc'. For bool/tristate symbols and choices, provides a list of all the assignable values.
Below is the the instruction that describes the task: ### Input: Prompts the user for a value for the symbol or choice 'sc'. For bool/tristate symbols and choices, provides a list of all the assignable values. ### Response: def get_value_from_user(sc): """ Prompts the user for a value for the symbo...
def subsample(self, key, order='random', auto_resize=False, ID=None): """ Allows arbitrary slicing (subsampling) of the data. .. note:: When using order='random', the sampling is random for each of the measurements in the collection. Parameters --------...
Allows arbitrary slicing (subsampling) of the data. .. note:: When using order='random', the sampling is random for each of the measurements in the collection. Parameters ---------- {FCMeasurement_subsample_parameters} Returns ------- F...
Below is the the instruction that describes the task: ### Input: Allows arbitrary slicing (subsampling) of the data. .. note:: When using order='random', the sampling is random for each of the measurements in the collection. Parameters ---------- {FCMeasure...
def run_forever(self) -> None: '''Execute the tasky/asyncio event loop until terminated.''' Log.debug('running event loop until terminated') asyncio.ensure_future(self.init()) self.loop.run_forever() self.loop.close()
Execute the tasky/asyncio event loop until terminated.
Below is the the instruction that describes the task: ### Input: Execute the tasky/asyncio event loop until terminated. ### Response: def run_forever(self) -> None: '''Execute the tasky/asyncio event loop until terminated.''' Log.debug('running event loop until terminated') asyncio.ensure_...
def vi_score(self, x, index): """ Wrapper function for selecting appropriate score Parameters ---------- x : float A random variable index : int 0 or 1 depending on which latent variable Returns ---------- The gradient of the sca...
Wrapper function for selecting appropriate score Parameters ---------- x : float A random variable index : int 0 or 1 depending on which latent variable Returns ---------- The gradient of the scale latent variable at x
Below is the the instruction that describes the task: ### Input: Wrapper function for selecting appropriate score Parameters ---------- x : float A random variable index : int 0 or 1 depending on which latent variable Returns ---------- ...
def wait_for(self, job_id, base_path=None, interval=5): """ Wait for an asynchronous task to finish. Unlike the thin methods elsewhere on this object, this one is actually specific to how the Luminoso API works. This will poll an API endpoint to find out the status of the job nu...
Wait for an asynchronous task to finish. Unlike the thin methods elsewhere on this object, this one is actually specific to how the Luminoso API works. This will poll an API endpoint to find out the status of the job numbered `job_id`, repeating every 5 seconds (by default) until the jo...
Below is the the instruction that describes the task: ### Input: Wait for an asynchronous task to finish. Unlike the thin methods elsewhere on this object, this one is actually specific to how the Luminoso API works. This will poll an API endpoint to find out the status of the job numbered ...
def create_route(self, uri, sub_service): """Create the route for the URI. :param uri: string - URI to be routed :param sub_service: boolean - is the URI for a sub-service :returns: n/a """ if uri not in self.routes.keys(): logger.debug('Service ({0}): Creat...
Create the route for the URI. :param uri: string - URI to be routed :param sub_service: boolean - is the URI for a sub-service :returns: n/a
Below is the the instruction that describes the task: ### Input: Create the route for the URI. :param uri: string - URI to be routed :param sub_service: boolean - is the URI for a sub-service :returns: n/a ### Response: def create_route(self, uri, sub_service): """Create the route...
def _initialize_attributes(model_class, name, bases, attrs): """Initialize the attributes of the model.""" model_class._attributes = {} for k, v in attrs.iteritems(): if isinstance(v, Attribute): model_class._attributes[k] = v v.name = v.name or k
Initialize the attributes of the model.
Below is the the instruction that describes the task: ### Input: Initialize the attributes of the model. ### Response: def _initialize_attributes(model_class, name, bases, attrs): """Initialize the attributes of the model.""" model_class._attributes = {} for k, v in attrs.iteritems(): if isinst...
def process_response(self, request, response): """ Sets the cache and deals with caching headers if needed """ if not self.should_cache(request, response): # We don't need to update the cache, just return return response response = self.patch_headers(response) ...
Sets the cache and deals with caching headers if needed
Below is the the instruction that describes the task: ### Input: Sets the cache and deals with caching headers if needed ### Response: def process_response(self, request, response): """ Sets the cache and deals with caching headers if needed """ if not self.should_cache(request, response): ...
def update_extension_statistics(self, extension_statistics_update, publisher_name, extension_name): """UpdateExtensionStatistics. [Preview API] :param :class:`<ExtensionStatisticUpdate> <azure.devops.v5_0.gallery.models.ExtensionStatisticUpdate>` extension_statistics_update: :param str p...
UpdateExtensionStatistics. [Preview API] :param :class:`<ExtensionStatisticUpdate> <azure.devops.v5_0.gallery.models.ExtensionStatisticUpdate>` extension_statistics_update: :param str publisher_name: :param str extension_name:
Below is the the instruction that describes the task: ### Input: UpdateExtensionStatistics. [Preview API] :param :class:`<ExtensionStatisticUpdate> <azure.devops.v5_0.gallery.models.ExtensionStatisticUpdate>` extension_statistics_update: :param str publisher_name: :param str extensio...
def files(self): """ File uploads parsed into an instance of :class:`MultiDict`. This property contains file uploads parsed from an `multipart/form-data` encoded POST request body. The values are instances of :class:`cgi.FieldStorage`. """ files = MultiDict()...
File uploads parsed into an instance of :class:`MultiDict`. This property contains file uploads parsed from an `multipart/form-data` encoded POST request body. The values are instances of :class:`cgi.FieldStorage`.
Below is the the instruction that describes the task: ### Input: File uploads parsed into an instance of :class:`MultiDict`. This property contains file uploads parsed from an `multipart/form-data` encoded POST request body. The values are instances of :class:`cgi.FieldStorage`....
def add_distribution_list_alias(self, distribution_list, alias): """ :param distribution_list: a distribution list object to be used as a selector :param alias: email alias address :returns: None (the API itself returns nothing) """ self.request('Add...
:param distribution_list: a distribution list object to be used as a selector :param alias: email alias address :returns: None (the API itself returns nothing)
Below is the the instruction that describes the task: ### Input: :param distribution_list: a distribution list object to be used as a selector :param alias: email alias address :returns: None (the API itself returns nothing) ### Response: def add_distribution_list_alias(self, ...