code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def trajectory_SgConst(Sg=0.1, delta_logt_dex=-0.01): ''' setup trajectories for constant radiation entropy. S_gamma/R where the radiation constant R = N_A*k (Dave Arnett, Supernova book, p. 212) This relates rho and T but the time scale for this is independent. Parameters ---------- ...
setup trajectories for constant radiation entropy. S_gamma/R where the radiation constant R = N_A*k (Dave Arnett, Supernova book, p. 212) This relates rho and T but the time scale for this is independent. Parameters ---------- Sg : float S_gamma/R, values between 0.1 and 10. reflec...
Below is the the instruction that describes the task: ### Input: setup trajectories for constant radiation entropy. S_gamma/R where the radiation constant R = N_A*k (Dave Arnett, Supernova book, p. 212) This relates rho and T but the time scale for this is independent. Parameters ---------...
def raw_writer(indent=None): """Returns a raw text writer co-routine. Yields: DataEvent: serialization events to write out Receives :class:`amazon.ion.core.IonEvent` or ``None`` when the co-routine yields ``HAS_PENDING`` :class:`WriteEventType` events. """ is_whitespace_str = ...
Returns a raw text writer co-routine. Yields: DataEvent: serialization events to write out Receives :class:`amazon.ion.core.IonEvent` or ``None`` when the co-routine yields ``HAS_PENDING`` :class:`WriteEventType` events.
Below is the the instruction that describes the task: ### Input: Returns a raw text writer co-routine. Yields: DataEvent: serialization events to write out Receives :class:`amazon.ion.core.IonEvent` or ``None`` when the co-routine yields ``HAS_PENDING`` :class:`WriteEventType` events. ...
def parse_session_cookie(cookie_to_cook): """ cookie_to_cook = http_header['cookie'] """ #print("cookie_to_cook: %s"%str(cookie_to_cook)) session_value = None tokens = cookie_to_cook.split(";") for tok in tokens: if 'remi_session=' in tok: #print("found session id: %s"%str(to...
cookie_to_cook = http_header['cookie']
Below is the the instruction that describes the task: ### Input: cookie_to_cook = http_header['cookie'] ### Response: def parse_session_cookie(cookie_to_cook): """ cookie_to_cook = http_header['cookie'] """ #print("cookie_to_cook: %s"%str(cookie_to_cook)) session_value = None tokens = cookie_to...
def writeToProto(self, proto): """ Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.writeToProto`. Write state to proto object. :param proto: TMRegionProto capnproto object """ proto.temporalImp = self.temporalImp proto.columnCount = self.columnCount proto.inputWidth = self.i...
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.writeToProto`. Write state to proto object. :param proto: TMRegionProto capnproto object
Below is the the instruction that describes the task: ### Input: Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.writeToProto`. Write state to proto object. :param proto: TMRegionProto capnproto object ### Response: def writeToProto(self, proto): """ Overrides :meth:`~nupic.bindings.re...
def create_token(self, user_id, permission_obj): """ 'permission_obj' param should be a string. e.g. '[{"access":"d_u_list","oid":{"id":"1576946496","type":"Domain"}}]' http://docs.exosite.com/portals/#add-user-permission """ headers = { 'User-Agent': s...
'permission_obj' param should be a string. e.g. '[{"access":"d_u_list","oid":{"id":"1576946496","type":"Domain"}}]' http://docs.exosite.com/portals/#add-user-permission
Below is the the instruction that describes the task: ### Input: 'permission_obj' param should be a string. e.g. '[{"access":"d_u_list","oid":{"id":"1576946496","type":"Domain"}}]' http://docs.exosite.com/portals/#add-user-permission ### Response: def create_token(self, user_id, permissio...
def output_data_ports(self, output_data_ports): """ Setter for _output_data_ports field See property :param dict output_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type :class:`rafcon.core.state_elements.data_port.OutputDataP...
Setter for _output_data_ports field See property :param dict output_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type :class:`rafcon.core.state_elements.data_port.OutputDataPort` :raises exceptions.TypeError: if the output_dat...
Below is the the instruction that describes the task: ### Input: Setter for _output_data_ports field See property :param dict output_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type :class:`rafcon.core.state_elements.data_port.Ou...
def bind(_self, **kwargs): """Bind attributes to the ``extra`` dict of each logged message record. This is used to add custom context to each logging call. Parameters ---------- **kwargs Mapping between keys and values that will be added to the ``extra`` dict. ...
Bind attributes to the ``extra`` dict of each logged message record. This is used to add custom context to each logging call. Parameters ---------- **kwargs Mapping between keys and values that will be added to the ``extra`` dict. Returns ------- :c...
Below is the the instruction that describes the task: ### Input: Bind attributes to the ``extra`` dict of each logged message record. This is used to add custom context to each logging call. Parameters ---------- **kwargs Mapping between keys and values that will be add...
def expand_files(self, modules): """get modules and errors from a list of modules and handle errors """ result, errors = utils.expand_modules( modules, self.config.black_list, self.config.black_list_re ) for error in errors: message = modname = error["mod"...
get modules and errors from a list of modules and handle errors
Below is the the instruction that describes the task: ### Input: get modules and errors from a list of modules and handle errors ### Response: def expand_files(self, modules): """get modules and errors from a list of modules and handle errors """ result, errors = utils.expand_modules( ...
def extract_lzh (archive, compression, cmd, verbosity, interactive, outdir): """Extract a LZH archive.""" opts = 'x' if verbosity > 1: opts += 'v' opts += "w=%s" % outdir return [cmd, opts, archive]
Extract a LZH archive.
Below is the the instruction that describes the task: ### Input: Extract a LZH archive. ### Response: def extract_lzh (archive, compression, cmd, verbosity, interactive, outdir): """Extract a LZH archive.""" opts = 'x' if verbosity > 1: opts += 'v' opts += "w=%s" % outdir return [cmd, o...
def delete_by_id( self, application_definition_id, custom_headers=None, raw=False, polling=True, **operation_config): """Deletes the managed application definition. :param application_definition_id: The fully qualified ID of the managed application definition, including the managed...
Deletes the managed application definition. :param application_definition_id: The fully qualified ID of the managed application definition, including the managed application name and the managed application definition resource type. Use the format, /subscriptions/{guid}/resourceGroup...
Below is the the instruction that describes the task: ### Input: Deletes the managed application definition. :param application_definition_id: The fully qualified ID of the managed application definition, including the managed application name and the managed application definition resour...
def attach_keypress(fig, scaling=1.1): """ Attach a key press event handler that configures keys for closing a figure and changing the figure size. Keys 'e' and 'c' respectively expand and contract the figure, and key 'q' closes it. **Note:** Resizing may not function correctly with all matplotlib ...
Attach a key press event handler that configures keys for closing a figure and changing the figure size. Keys 'e' and 'c' respectively expand and contract the figure, and key 'q' closes it. **Note:** Resizing may not function correctly with all matplotlib backends (a `bug <https://github.com/matplo...
Below is the the instruction that describes the task: ### Input: Attach a key press event handler that configures keys for closing a figure and changing the figure size. Keys 'e' and 'c' respectively expand and contract the figure, and key 'q' closes it. **Note:** Resizing may not function correctly wi...
def _matplotlib_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): ...
Draw a quantum circuit based on matplotlib. If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline. We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization. Args: circuit (QuantumCircuit): a quantum circuit scale (float): sca...
Below is the the instruction that describes the task: ### Input: Draw a quantum circuit based on matplotlib. If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline. We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization. Args: c...
def replace_runtime_class(self, name, body, **kwargs): """ replace the specified RuntimeClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_runtime_class(name, body, async_req=Tru...
replace the specified RuntimeClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_runtime_class(name, body, async_req=True) >>> result = thread.get() :param async_req bool ...
Below is the the instruction that describes the task: ### Input: replace the specified RuntimeClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_runtime_class(name, body, async_req=True) ...
def normalize(numbers, total=1.0): #from AI: A Modern Appproach """Multiply each number by a constant such that the sum is 1.0 (or total). >>> normalize([1,2,1]) [0.25, 0.5, 0.25] """ k = total / sum(numbers) return [k * n for n in numbers]
Multiply each number by a constant such that the sum is 1.0 (or total). >>> normalize([1,2,1]) [0.25, 0.5, 0.25]
Below is the the instruction that describes the task: ### Input: Multiply each number by a constant such that the sum is 1.0 (or total). >>> normalize([1,2,1]) [0.25, 0.5, 0.25] ### Response: def normalize(numbers, total=1.0): #from AI: A Modern Appproach """Multiply each number by a constant such tha...
def _generate_provenance(self): """Function to generate provenance at the end of the IF.""" # noinspection PyTypeChecker hazard = definition( self._provenance['hazard_keywords']['hazard']) exposures = [ definition(layer.keywords['exposure']) for layer in self.expo...
Function to generate provenance at the end of the IF.
Below is the the instruction that describes the task: ### Input: Function to generate provenance at the end of the IF. ### Response: def _generate_provenance(self): """Function to generate provenance at the end of the IF.""" # noinspection PyTypeChecker hazard = definition( self...
def run_expect_command(self, cmd, expect_end=None, timeout=3, wait_seconds=2): """ 执行 shell 命令并获取返回结果 :param timeout: :param wait_seconds: :param cmd: :param expect_end: :return: """ shell = self.ssh_session.invoke_shell() last_time = int(t...
执行 shell 命令并获取返回结果 :param timeout: :param wait_seconds: :param cmd: :param expect_end: :return:
Below is the the instruction that describes the task: ### Input: 执行 shell 命令并获取返回结果 :param timeout: :param wait_seconds: :param cmd: :param expect_end: :return: ### Response: def run_expect_command(self, cmd, expect_end=None, timeout=3, wait_seconds=2): """ 执...
def baseline_or_audit(self, allow_deletion=False, audit_only=False): """Baseline synchonization or audit. Both functions implemented in this routine because audit is a prerequisite for a baseline sync. In the case of baseline sync the last timestamp seen is recorded as client state. ...
Baseline synchonization or audit. Both functions implemented in this routine because audit is a prerequisite for a baseline sync. In the case of baseline sync the last timestamp seen is recorded as client state.
Below is the the instruction that describes the task: ### Input: Baseline synchonization or audit. Both functions implemented in this routine because audit is a prerequisite for a baseline sync. In the case of baseline sync the last timestamp seen is recorded as client state. ### Response: ...
def get_vnet(access_token, subscription_id, resource_group, vnet_name): '''Get details about the named virtual network. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vn...
Get details about the named virtual network. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vnet_name (str): Name of the VNet. Returns: HTTP response. VNet JSON...
Below is the the instruction that describes the task: ### Input: Get details about the named virtual network. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vnet_name (s...
def require_session(handler): """ Decorator to ensure a session is properly in the request """ @functools.wraps(handler) async def decorated(request: web.Request) -> web.Response: request_session_token = request.match_info['session'] session = session_from_request(request) if not ses...
Decorator to ensure a session is properly in the request
Below is the the instruction that describes the task: ### Input: Decorator to ensure a session is properly in the request ### Response: def require_session(handler): """ Decorator to ensure a session is properly in the request """ @functools.wraps(handler) async def decorated(request: web.Request) -> w...
def _realToVisibleColumn(self, text, realColumn): """If \t is used, real position of symbol in block and visible position differs This function converts real to visible """ generator = self._visibleCharPositionGenerator(text) for i in range(realColumn): val = next(gen...
If \t is used, real position of symbol in block and visible position differs This function converts real to visible
Below is the the instruction that describes the task: ### Input: If \t is used, real position of symbol in block and visible position differs This function converts real to visible ### Response: def _realToVisibleColumn(self, text, realColumn): """If \t is used, real position of symbol in block and...
async def get_sound_settings(self, target="") -> List[Setting]: """Get the current sound settings. :param str target: settings target, defaults to all. """ res = await self.services["audio"]["getSoundSettings"]({"target": target}) return [Setting.make(**x) for x in res]
Get the current sound settings. :param str target: settings target, defaults to all.
Below is the the instruction that describes the task: ### Input: Get the current sound settings. :param str target: settings target, defaults to all. ### Response: async def get_sound_settings(self, target="") -> List[Setting]: """Get the current sound settings. :param str target: setting...
def set_page_artid(self, page_start=None, page_end=None, artid=None): """Add artid, start, end pages to publication info of a reference. Args: page_start(Optional[string]): value for the field page_start page_end(Optional[string]): value for the field page_end artid(...
Add artid, start, end pages to publication info of a reference. Args: page_start(Optional[string]): value for the field page_start page_end(Optional[string]): value for the field page_end artid(Optional[string]): value for the field artid Raises: ValueEr...
Below is the the instruction that describes the task: ### Input: Add artid, start, end pages to publication info of a reference. Args: page_start(Optional[string]): value for the field page_start page_end(Optional[string]): value for the field page_end artid(Optional[str...
def internal2external_grad(xi, bounds): """ Calculate the internal to external gradiant Calculates the partial of external over internal """ ge = np.empty_like(xi) for i, (v, bound) in enumerate(zip(xi, bounds)): a = bound[0] # minimum b = bound[1] # maximum ...
Calculate the internal to external gradiant Calculates the partial of external over internal
Below is the the instruction that describes the task: ### Input: Calculate the internal to external gradiant Calculates the partial of external over internal ### Response: def internal2external_grad(xi, bounds): """ Calculate the internal to external gradiant Calculates the partial of ex...
def device_slug_to_id(slug): """Convert a d-- device slug to an integer. Args: slug (str): A slug in the format d--XXXX-XXXX-XXXX-XXXX Returns: int: The device id as an integer Raises: ArgumentError: if there is a malformed slug """ if not isinstance(slug, str): ...
Convert a d-- device slug to an integer. Args: slug (str): A slug in the format d--XXXX-XXXX-XXXX-XXXX Returns: int: The device id as an integer Raises: ArgumentError: if there is a malformed slug
Below is the the instruction that describes the task: ### Input: Convert a d-- device slug to an integer. Args: slug (str): A slug in the format d--XXXX-XXXX-XXXX-XXXX Returns: int: The device id as an integer Raises: ArgumentError: if there is a malformed slug ### Response: ...
def _check_reversed(self, node): """ check that the argument to `reversed` is a sequence """ try: argument = utils.safe_infer(utils.get_argument_from_call(node, position=0)) except utils.NoSuchArgumentError: pass else: if argument is astroid.Uninferabl...
check that the argument to `reversed` is a sequence
Below is the the instruction that describes the task: ### Input: check that the argument to `reversed` is a sequence ### Response: def _check_reversed(self, node): """ check that the argument to `reversed` is a sequence """ try: argument = utils.safe_infer(utils.get_argument_from_call(n...
def process_text_constructor(cleaner: Callable, tokenizer: Callable, append_indicators: bool, start_tok: str, end_tok: str): """Generate a function that will clean and tokenize text.""" def proces...
Generate a function that will clean and tokenize text.
Below is the the instruction that describes the task: ### Input: Generate a function that will clean and tokenize text. ### Response: def process_text_constructor(cleaner: Callable, tokenizer: Callable, append_indicators: bool, ...
def _ascii_tree(self, indent: str, no_types: bool, val_count: bool) -> str: """Return the receiver's subtree as ASCII art.""" def suffix(sn): return f" {{{sn.val_count}}}\n" if val_count else "\n" if not self.children: return "" cs = [] for c in self.child...
Return the receiver's subtree as ASCII art.
Below is the the instruction that describes the task: ### Input: Return the receiver's subtree as ASCII art. ### Response: def _ascii_tree(self, indent: str, no_types: bool, val_count: bool) -> str: """Return the receiver's subtree as ASCII art.""" def suffix(sn): return f" {{{sn.val_co...
def use_federated_vault_view(self): """Pass through to provider AuthorizationLookupSession.use_federated_vault_view""" self._vault_view = FEDERATED # self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked for session in self._get_provider_session...
Pass through to provider AuthorizationLookupSession.use_federated_vault_view
Below is the the instruction that describes the task: ### Input: Pass through to provider AuthorizationLookupSession.use_federated_vault_view ### Response: def use_federated_vault_view(self): """Pass through to provider AuthorizationLookupSession.use_federated_vault_view""" self._vault_view = FEDER...
def load_nifti(filename, to='auto'): ''' load_nifti(filename) yields the Nifti1Image or Nifti2Image referened by the given filename by using the nibabel load function. The optional argument to may be used to coerce the resulting data to a particular format; the following arguments are underst...
load_nifti(filename) yields the Nifti1Image or Nifti2Image referened by the given filename by using the nibabel load function. The optional argument to may be used to coerce the resulting data to a particular format; the following arguments are understood: * 'header' will yield just the image h...
Below is the the instruction that describes the task: ### Input: load_nifti(filename) yields the Nifti1Image or Nifti2Image referened by the given filename by using the nibabel load function. The optional argument to may be used to coerce the resulting data to a particular format; the following a...
def cancel_global_ip(self, global_ip_id): """Cancels the specified global IP address. :param int id: The ID of the global IP to be cancelled. """ service = self.client['Network_Subnet_IpAddress_Global'] ip_address = service.getObject(id=global_ip_id, mask='billingItem') ...
Cancels the specified global IP address. :param int id: The ID of the global IP to be cancelled.
Below is the the instruction that describes the task: ### Input: Cancels the specified global IP address. :param int id: The ID of the global IP to be cancelled. ### Response: def cancel_global_ip(self, global_ip_id): """Cancels the specified global IP address. :param int id: The ID of th...
def collect_fields(node): """ Get all the unique field names that are eligible for optimization Requested a function like this be added to the ``info`` object upstream in graphene_django: https://github.com/graphql-python/graphene-django/issues/230 """ fields = set() for leaf in node: ...
Get all the unique field names that are eligible for optimization Requested a function like this be added to the ``info`` object upstream in graphene_django: https://github.com/graphql-python/graphene-django/issues/230
Below is the the instruction that describes the task: ### Input: Get all the unique field names that are eligible for optimization Requested a function like this be added to the ``info`` object upstream in graphene_django: https://github.com/graphql-python/graphene-django/issues/230 ### Response: def ...
def key_to_scan_codes(key, error_if_missing=True): """ Returns a list of scan codes associated with this key (name or scan code). """ if _is_number(key): return (key,) elif _is_list(key): return sum((key_to_scan_codes(i) for i in key), ()) elif not _is_str(key): raise Val...
Returns a list of scan codes associated with this key (name or scan code).
Below is the the instruction that describes the task: ### Input: Returns a list of scan codes associated with this key (name or scan code). ### Response: def key_to_scan_codes(key, error_if_missing=True): """ Returns a list of scan codes associated with this key (name or scan code). """ if _is_numb...
def dump(pif, fp, **kwargs): """ Convert a single Physical Information Object, or a list of such objects, into a JSON-encoded text file. :param pif: Object or list of objects to serialize. :param fp: File-like object supporting .write() method to write the serialized object(s) to. :param kwargs: An...
Convert a single Physical Information Object, or a list of such objects, into a JSON-encoded text file. :param pif: Object or list of objects to serialize. :param fp: File-like object supporting .write() method to write the serialized object(s) to. :param kwargs: Any options available to json.dump().
Below is the the instruction that describes the task: ### Input: Convert a single Physical Information Object, or a list of such objects, into a JSON-encoded text file. :param pif: Object or list of objects to serialize. :param fp: File-like object supporting .write() method to write the serialized object(...
def get_unit_by_abbreviation(unit_abbreviation, **kwargs): """ Returns a single unit by abbreviation. Used as utility function to resolve string to id """ try: if unit_abbreviation is None: unit_abbreviation = '' unit_i = db.DBSession.query(Unit).filter(Unit.abbreviation=...
Returns a single unit by abbreviation. Used as utility function to resolve string to id
Below is the the instruction that describes the task: ### Input: Returns a single unit by abbreviation. Used as utility function to resolve string to id ### Response: def get_unit_by_abbreviation(unit_abbreviation, **kwargs): """ Returns a single unit by abbreviation. Used as utility function to resolv...
def handle_import(self, name, compilation, rule): """ Re-implementation of the core Sass import mechanism, which looks for files using the staticfiles storage and staticfiles finders. """ original_path = PurePath(name) search_exts = list(compilation.compiler.dynamic_exte...
Re-implementation of the core Sass import mechanism, which looks for files using the staticfiles storage and staticfiles finders.
Below is the the instruction that describes the task: ### Input: Re-implementation of the core Sass import mechanism, which looks for files using the staticfiles storage and staticfiles finders. ### Response: def handle_import(self, name, compilation, rule): """ Re-implementation of the cor...
def DefaultEnvironment(*args, **kw): """ Initial public entry point for creating the default construction Environment. After creating the environment, we overwrite our name (DefaultEnvironment) with the _fetch_DefaultEnvironment() function, which more efficiently returns the initialized default...
Initial public entry point for creating the default construction Environment. After creating the environment, we overwrite our name (DefaultEnvironment) with the _fetch_DefaultEnvironment() function, which more efficiently returns the initialized default construction environment without checking fo...
Below is the the instruction that describes the task: ### Input: Initial public entry point for creating the default construction Environment. After creating the environment, we overwrite our name (DefaultEnvironment) with the _fetch_DefaultEnvironment() function, which more efficiently returns the...
def set_left_table(self, left_table=None): """ Sets the left table for this join clause. If no table is specified, the first table in the query will be used :type left_table: str or dict or :class:`Table <querybuilder.tables.Table>` or None :param left_table: The left table bein...
Sets the left table for this join clause. If no table is specified, the first table in the query will be used :type left_table: str or dict or :class:`Table <querybuilder.tables.Table>` or None :param left_table: The left table being joined with. This can be a string of the table na...
Below is the the instruction that describes the task: ### Input: Sets the left table for this join clause. If no table is specified, the first table in the query will be used :type left_table: str or dict or :class:`Table <querybuilder.tables.Table>` or None :param left_table: The left tabl...
def _datetime_to_rfc3339(value, ignore_zone=True): """Convert a timestamp to a string. :type value: :class:`datetime.datetime` :param value: The datetime object to be converted to a string. :type ignore_zone: bool :param ignore_zone: If True, then the timezone (if any) of the datetime ...
Convert a timestamp to a string. :type value: :class:`datetime.datetime` :param value: The datetime object to be converted to a string. :type ignore_zone: bool :param ignore_zone: If True, then the timezone (if any) of the datetime object is ignored. :rtype: str :retur...
Below is the the instruction that describes the task: ### Input: Convert a timestamp to a string. :type value: :class:`datetime.datetime` :param value: The datetime object to be converted to a string. :type ignore_zone: bool :param ignore_zone: If True, then the timezone (if any) of the datetime ...
def _is_valid_imaging_dicom(dicom_header): """ Function will do some basic checks to see if this is a valid imaging dicom """ # if it is philips and multiframe dicom then we assume it is ok try: if common.is_philips([dicom_header]): if common.is_multiframe_dicom([dicom_header]): ...
Function will do some basic checks to see if this is a valid imaging dicom
Below is the the instruction that describes the task: ### Input: Function will do some basic checks to see if this is a valid imaging dicom ### Response: def _is_valid_imaging_dicom(dicom_header): """ Function will do some basic checks to see if this is a valid imaging dicom """ # if it is philips ...
def nlmsg_reserve(n, len_, pad): """Reserve room for additional data in a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L407 Reserves room for additional data at the tail of the an existing netlink message. Eventual padding required will be zeroed out. bytearray_ptr...
Reserve room for additional data in a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L407 Reserves room for additional data at the tail of the an existing netlink message. Eventual padding required will be zeroed out. bytearray_ptr() at the start of additional data or No...
Below is the the instruction that describes the task: ### Input: Reserve room for additional data in a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L407 Reserves room for additional data at the tail of the an existing netlink message. Eventual padding required will be z...
def sis_metadata(self): """Return Olympus SIS metadata from SIS and INI tags as dict.""" if not self.is_sis: return None tags = self.pages[0].tags result = {} try: result.update(tags['OlympusINI'].value) except Exception: pass t...
Return Olympus SIS metadata from SIS and INI tags as dict.
Below is the the instruction that describes the task: ### Input: Return Olympus SIS metadata from SIS and INI tags as dict. ### Response: def sis_metadata(self): """Return Olympus SIS metadata from SIS and INI tags as dict.""" if not self.is_sis: return None tags = self.pages[0]...
def unregister_model(self, storagemodel:object, modeldefinition = None, delete_queue=False): """ clear up an Queueservice for an StorageQueueModel in your Azure Storage Account Will delete the hole Queue if delete_queue Flag is True! required Parameter is: - storag...
clear up an Queueservice for an StorageQueueModel in your Azure Storage Account Will delete the hole Queue if delete_queue Flag is True! required Parameter is: - storagemodel: StorageQueueModel(Object) Optional Parameter is: - delete_queue: bool
Below is the the instruction that describes the task: ### Input: clear up an Queueservice for an StorageQueueModel in your Azure Storage Account Will delete the hole Queue if delete_queue Flag is True! required Parameter is: - storagemodel: StorageQueueModel(Object) ...
def data_received(self, data): """Add incoming data to buffer.""" data = data.decode('ascii') self.log.debug('received data: %s', data) self.telegram_buffer.append(data) for telegram in self.telegram_buffer.get_all(): self.handle_telegram(telegram)
Add incoming data to buffer.
Below is the the instruction that describes the task: ### Input: Add incoming data to buffer. ### Response: def data_received(self, data): """Add incoming data to buffer.""" data = data.decode('ascii') self.log.debug('received data: %s', data) self.telegram_buffer.append(data) ...
def atlasdb_open( path ): """ Open the atlas db. Return a connection. Return None if it doesn't exist """ if not os.path.exists(path): log.debug("Atlas DB doesn't exist at %s" % path) return None con = sqlite3.connect( path, isolation_level=None ) con.row_factory = atlas...
Open the atlas db. Return a connection. Return None if it doesn't exist
Below is the the instruction that describes the task: ### Input: Open the atlas db. Return a connection. Return None if it doesn't exist ### Response: def atlasdb_open( path ): """ Open the atlas db. Return a connection. Return None if it doesn't exist """ if not os.path.exists(path...
def validate(self): """ validate whether value in config file is correct. """ spec = self._create_specs() # support in future functions = {} validator = validate.Validator(functions=functions) self.config.configspec = spec result = self.config....
validate whether value in config file is correct.
Below is the the instruction that describes the task: ### Input: validate whether value in config file is correct. ### Response: def validate(self): """ validate whether value in config file is correct. """ spec = self._create_specs() # support in future functions ...
def add_table(self, rows, cols, left, top, width, height): """ Add a |GraphicFrame| object containing a table with the specified number of *rows* and *cols* and the specified position and size. *width* is evenly distributed between the columns of the new table. Likewise, *height*...
Add a |GraphicFrame| object containing a table with the specified number of *rows* and *cols* and the specified position and size. *width* is evenly distributed between the columns of the new table. Likewise, *height* is evenly distributed between the rows. Note that the ``.table`` prope...
Below is the the instruction that describes the task: ### Input: Add a |GraphicFrame| object containing a table with the specified number of *rows* and *cols* and the specified position and size. *width* is evenly distributed between the columns of the new table. Likewise, *height* is evenly...
def strToBytes(value): ''' :type value: ``str`` :param value: value to encode ''' kassert.is_of_types(value, (bytes, bytearray, six.string_types)) if isinstance(value, six.string_types): return bytes(bytearray([ord(x) for x in value])) elif isinstance(value, bytearray): retur...
:type value: ``str`` :param value: value to encode
Below is the the instruction that describes the task: ### Input: :type value: ``str`` :param value: value to encode ### Response: def strToBytes(value): ''' :type value: ``str`` :param value: value to encode ''' kassert.is_of_types(value, (bytes, bytearray, six.string_types)) if isinsta...
def replace_vertex_references(self, mask): """ Replace the vertex index references in every entity. Parameters ------------ mask : (len(self.vertices), ) int Contains new vertex indexes Alters ------------ entity.points in self.entities ...
Replace the vertex index references in every entity. Parameters ------------ mask : (len(self.vertices), ) int Contains new vertex indexes Alters ------------ entity.points in self.entities Replaced by mask[entity.points]
Below is the the instruction that describes the task: ### Input: Replace the vertex index references in every entity. Parameters ------------ mask : (len(self.vertices), ) int Contains new vertex indexes Alters ------------ entity.points in self.entities ...
def add_attribute(self, attrkey, attrvalue, append=False, oldvalue=None): """ Add an attribute to this feature. Feature attributes are stored as nested dictionaries. Each feature can only have one ID, so ID attribute mapping is 'string' to 'string'. All other attributes can hav...
Add an attribute to this feature. Feature attributes are stored as nested dictionaries. Each feature can only have one ID, so ID attribute mapping is 'string' to 'string'. All other attributes can have multiple values, so mapping is 'string' to 'dict of strings'. By default, a...
Below is the the instruction that describes the task: ### Input: Add an attribute to this feature. Feature attributes are stored as nested dictionaries. Each feature can only have one ID, so ID attribute mapping is 'string' to 'string'. All other attributes can have multiple values, so map...
def get_package_version(path): '''Extracts the version''' with open(VERSION_FILE, "rt") as f: verstrline = f.read() VERSION = r"^version = ['\"]([^'\"]*)['\"]" results = re.search(VERSION, verstrline, re.M) if results: version = results.group(1) else: raise RuntimeError...
Extracts the version
Below is the the instruction that describes the task: ### Input: Extracts the version ### Response: def get_package_version(path): '''Extracts the version''' with open(VERSION_FILE, "rt") as f: verstrline = f.read() VERSION = r"^version = ['\"]([^'\"]*)['\"]" results = re.search(VERSION, v...
def total_bytes_billed(self): """Return total bytes billed from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.totalBytesBilled :rtype: int or None :returns: total bytes processed by the job, or None if job is not...
Return total bytes billed from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.totalBytesBilled :rtype: int or None :returns: total bytes processed by the job, or None if job is not yet complete.
Below is the the instruction that describes the task: ### Input: Return total bytes billed from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.totalBytesBilled :rtype: int or None :returns: total bytes processed by th...
def formatException(self, ei): '''Indent traceback info for better readability''' out = super(CliFormatter, self).formatException(ei) return b'│' + format_multiline(out)
Indent traceback info for better readability
Below is the the instruction that describes the task: ### Input: Indent traceback info for better readability ### Response: def formatException(self, ei): '''Indent traceback info for better readability''' out = super(CliFormatter, self).formatException(ei) return b'│' + format_multiline(ou...
def update_in_ioloop(update): """Decorator that ensures an update() method is run in the tornado ioloop. Does this by checking the thread identity. Requires that the object to which the method is bound has the attributes :attr:`_ioloop_thread_id` (the result of thread.get_ident() in the ioloop thread) ...
Decorator that ensures an update() method is run in the tornado ioloop. Does this by checking the thread identity. Requires that the object to which the method is bound has the attributes :attr:`_ioloop_thread_id` (the result of thread.get_ident() in the ioloop thread) and :attr:`ioloop` (the ioloop in...
Below is the the instruction that describes the task: ### Input: Decorator that ensures an update() method is run in the tornado ioloop. Does this by checking the thread identity. Requires that the object to which the method is bound has the attributes :attr:`_ioloop_thread_id` (the result of thread.ge...
def _store_compound_info(self): """Update the compound_info dictionary with the current chunk of compound details Note that we use the inchikey as unique identifier. If we can't find an appropiate inchikey we just use a random string (uuid4) suffixed with UNKNOWN """ other_name_...
Update the compound_info dictionary with the current chunk of compound details Note that we use the inchikey as unique identifier. If we can't find an appropiate inchikey we just use a random string (uuid4) suffixed with UNKNOWN
Below is the the instruction that describes the task: ### Input: Update the compound_info dictionary with the current chunk of compound details Note that we use the inchikey as unique identifier. If we can't find an appropiate inchikey we just use a random string (uuid4) suffixed with UNKNOWN ### R...
def _get_offsets(self, aref, dim=0): """ Return a tuple of offsets of an ArrayRef object in all dimensions. The index order is right to left (c-code order). e.g. c[i+1][j-2] -> (-2, +1) If aref is actually a c_ast.ID, None will be returned. """ if isinstance(are...
Return a tuple of offsets of an ArrayRef object in all dimensions. The index order is right to left (c-code order). e.g. c[i+1][j-2] -> (-2, +1) If aref is actually a c_ast.ID, None will be returned.
Below is the the instruction that describes the task: ### Input: Return a tuple of offsets of an ArrayRef object in all dimensions. The index order is right to left (c-code order). e.g. c[i+1][j-2] -> (-2, +1) If aref is actually a c_ast.ID, None will be returned. ### Response: def _get_o...
def ret_list_minions(self): ''' Return minions that match via list ''' tgt = _tgt_set(self.tgt) return self._ret_minions(tgt.intersection)
Return minions that match via list
Below is the the instruction that describes the task: ### Input: Return minions that match via list ### Response: def ret_list_minions(self): ''' Return minions that match via list ''' tgt = _tgt_set(self.tgt) return self._ret_minions(tgt.intersection)
def find_all(self, predicate): """Returns a generator that produces a sequence of Entry objects for which the predicate returned True. Args: predicate: A callable that returns a value coercible to bool. """ for _nid, entry in self._registry.items(): if predicate(...
Returns a generator that produces a sequence of Entry objects for which the predicate returned True. Args: predicate: A callable that returns a value coercible to bool.
Below is the the instruction that describes the task: ### Input: Returns a generator that produces a sequence of Entry objects for which the predicate returned True. Args: predicate: A callable that returns a value coercible to bool. ### Response: def find_all(self, predicate): """Retu...
def transformFromNative(cls, obj): """ Convert the list of tuples in obj.value to strings. """ if obj.isNative: obj.isNative = False transformed = [] for tup in obj.value: transformed.append(periodToString(tup, cls.forceUTC)) ...
Convert the list of tuples in obj.value to strings.
Below is the the instruction that describes the task: ### Input: Convert the list of tuples in obj.value to strings. ### Response: def transformFromNative(cls, obj): """ Convert the list of tuples in obj.value to strings. """ if obj.isNative: obj.isNative = False ...
def cell_nodes_x(self): """The unstructured x-boundaries with shape (N, m) where m > 2""" decoder = self.decoder xcoord = self.xcoord data = self.data xbounds = decoder.get_cell_node_coord( data, coords=data.coords, axis='x') if self.plotter.convert_radian: ...
The unstructured x-boundaries with shape (N, m) where m > 2
Below is the the instruction that describes the task: ### Input: The unstructured x-boundaries with shape (N, m) where m > 2 ### Response: def cell_nodes_x(self): """The unstructured x-boundaries with shape (N, m) where m > 2""" decoder = self.decoder xcoord = self.xcoord data = sel...
def _retry_task(provider, job_descriptor, task_id, task_attempt): """Retry task_id (numeric id) assigning it task_attempt.""" td_orig = job_descriptor.find_task_descriptor(task_id) new_task_descriptors = [ job_model.TaskDescriptor({ 'task-id': task_id, 'task-attempt': task_attempt ...
Retry task_id (numeric id) assigning it task_attempt.
Below is the the instruction that describes the task: ### Input: Retry task_id (numeric id) assigning it task_attempt. ### Response: def _retry_task(provider, job_descriptor, task_id, task_attempt): """Retry task_id (numeric id) assigning it task_attempt.""" td_orig = job_descriptor.find_task_descriptor(task_i...
def show_files(md5): '''Renders template with `view` of the md5.''' if not WORKBENCH: return flask.redirect('/') md5_view = WORKBENCH.work_request('view', md5) return flask.render_template('templates/md5_view.html', md5_view=md5_view['view'], md5=md5)
Renders template with `view` of the md5.
Below is the the instruction that describes the task: ### Input: Renders template with `view` of the md5. ### Response: def show_files(md5): '''Renders template with `view` of the md5.''' if not WORKBENCH: return flask.redirect('/') md5_view = WORKBENCH.work_request('view', md5) return fla...
def verify(token, public_key, validate_nonce=None, algorithms=[DEFAULT_ALGORITHM]): """ Verify the validity of the given JWT using the given public key. :param token: JWM claim :param public_key: Public key to use when verifying the claim's signature. :param validate_nonce: Callable to use to valid...
Verify the validity of the given JWT using the given public key. :param token: JWM claim :param public_key: Public key to use when verifying the claim's signature. :param validate_nonce: Callable to use to validate the claim's nonce. :param algorithms: Allowable signing algorithms. Defaults to ['RS512'...
Below is the the instruction that describes the task: ### Input: Verify the validity of the given JWT using the given public key. :param token: JWM claim :param public_key: Public key to use when verifying the claim's signature. :param validate_nonce: Callable to use to validate the claim's nonce. ...
def sample(self, labels): """ labels: [b1, b2] Return true_log_probs: [b1, b2] samp_log_probs: [n_sample] neg_samples: [n_sample] """ # neg_samples = torch.empty(0).long() n_sample = self.n_sample n_tries = 2 * n_sample ...
labels: [b1, b2] Return true_log_probs: [b1, b2] samp_log_probs: [n_sample] neg_samples: [n_sample]
Below is the the instruction that describes the task: ### Input: labels: [b1, b2] Return true_log_probs: [b1, b2] samp_log_probs: [n_sample] neg_samples: [n_sample] ### Response: def sample(self, labels): """ labels: [b1, b2] Return ...
def _remove_observer(self, signal, observer): """Remove an observer to a valid signal. Parameters ---------- signal : str a valid signal. observer : @func an obervation function to be removed. """ if observer in self._observers[signal]: ...
Remove an observer to a valid signal. Parameters ---------- signal : str a valid signal. observer : @func an obervation function to be removed.
Below is the the instruction that describes the task: ### Input: Remove an observer to a valid signal. Parameters ---------- signal : str a valid signal. observer : @func an obervation function to be removed. ### Response: def _remove_observer(self, signal, ...
def progress(rest): "Display the progress of something: start|end|percent" if rest: left, right, amount = [piece.strip() for piece in rest.split('|')] ticks = min(int(round(float(amount) / 10)), 10) bar = "=" * ticks return "%s [%-10s] %s" % (left, bar, right)
Display the progress of something: start|end|percent
Below is the the instruction that describes the task: ### Input: Display the progress of something: start|end|percent ### Response: def progress(rest): "Display the progress of something: start|end|percent" if rest: left, right, amount = [piece.strip() for piece in rest.split('|')] ticks = min(int(round(floa...
def _addTags(self, **k): """Helper for :meth:`addTags`.""" for tag, thing in k.items(): if not isinstance(thing, (tuple, list)): thing = (thing,) typetag = defaulttagtype[tag] self.rawtagdict[tag] = encode(typetag, *thing) return self
Helper for :meth:`addTags`.
Below is the the instruction that describes the task: ### Input: Helper for :meth:`addTags`. ### Response: def _addTags(self, **k): """Helper for :meth:`addTags`.""" for tag, thing in k.items(): if not isinstance(thing, (tuple, list)): thing = (thing,) typet...
def get_grid_spatial_dimensions(self, variable): """Returns (width, height) for the given variable""" data = self.open_dataset(self.service).variables[variable.variable] dimensions = list(data.dimensions) return data.shape[dimensions.index(variable.x_dimension)], data.shape[dimensions.i...
Returns (width, height) for the given variable
Below is the the instruction that describes the task: ### Input: Returns (width, height) for the given variable ### Response: def get_grid_spatial_dimensions(self, variable): """Returns (width, height) for the given variable""" data = self.open_dataset(self.service).variables[variable.variable] ...
def clamp(n, lower, upper): """ Restricts the given number to a lower and upper bound (inclusive) :param n: input number :param lower: lower bound (inclusive) :param upper: upper bound (inclusive) :return: clamped number """ if lower > upper: lower, upper = upper, lower...
Restricts the given number to a lower and upper bound (inclusive) :param n: input number :param lower: lower bound (inclusive) :param upper: upper bound (inclusive) :return: clamped number
Below is the the instruction that describes the task: ### Input: Restricts the given number to a lower and upper bound (inclusive) :param n: input number :param lower: lower bound (inclusive) :param upper: upper bound (inclusive) :return: clamped number ### Response: def clamp(n, lower, u...
def check_next(self, tag): """ If next tag is link with same href, combine them. """ if (type(tag.next_sibling) == element.Tag and tag.next_sibling.name == 'a'): next_tag = tag.next_sibling if tag.get('href') and next_tag.get('href'): ...
If next tag is link with same href, combine them.
Below is the the instruction that describes the task: ### Input: If next tag is link with same href, combine them. ### Response: def check_next(self, tag): """ If next tag is link with same href, combine them. """ if (type(tag.next_sibling) == element.Tag and tag.nex...
def get_snapshot(name, config_path=_DEFAULT_CONFIG_PATH, with_packages=False): ''' Get detailed information about a snapshot. :param str name: The name of the snapshot given during snapshot creation. :param str config_path: The path to the configuration file for the aptly instance. :param bool with...
Get detailed information about a snapshot. :param str name: The name of the snapshot given during snapshot creation. :param str config_path: The path to the configuration file for the aptly instance. :param bool with_packages: Return a list of packages in the snapshot. :return: A dictionary containing...
Below is the the instruction that describes the task: ### Input: Get detailed information about a snapshot. :param str name: The name of the snapshot given during snapshot creation. :param str config_path: The path to the configuration file for the aptly instance. :param bool with_packages: Return a li...
def ParseFromUnicode(self, value): """Parse a string into a client URN. Convert case so that all URNs are of the form C.[0-9a-f]. Args: value: string value to parse """ precondition.AssertType(value, Text) value = value.strip() super(ClientURN, self).ParseFromUnicode(value) mat...
Parse a string into a client URN. Convert case so that all URNs are of the form C.[0-9a-f]. Args: value: string value to parse
Below is the the instruction that describes the task: ### Input: Parse a string into a client URN. Convert case so that all URNs are of the form C.[0-9a-f]. Args: value: string value to parse ### Response: def ParseFromUnicode(self, value): """Parse a string into a client URN. Convert case...
def merge_figures(figures): """ Generates a single Figure from a list of figures Parameters: ----------- figures : list(Figures) List of figures to be merged. """ figure={} data=[] for fig in figures: for trace in fig['data']: data.append(trace) layout=get_base_layout(figures) figure['data']=data ...
Generates a single Figure from a list of figures Parameters: ----------- figures : list(Figures) List of figures to be merged.
Below is the the instruction that describes the task: ### Input: Generates a single Figure from a list of figures Parameters: ----------- figures : list(Figures) List of figures to be merged. ### Response: def merge_figures(figures): """ Generates a single Figure from a list of figures Parameters: ---...
def _single_multichannel_mp_run(X, Phi, bound, selection_rule, stop_crit, max_iter, verbose=False, pad=0, random_state=None, memory=Memory(None)): """ run of the structured variant of the RSSMP algorithm """ rng = check_random_state(random_state) ...
run of the structured variant of the RSSMP algorithm
Below is the the instruction that describes the task: ### Input: run of the structured variant of the RSSMP algorithm ### Response: def _single_multichannel_mp_run(X, Phi, bound, selection_rule, stop_crit, max_iter, verbose=False, pad=0, random_state=...
def update_query(url, params, remove=None): """Updates a URL's query parameters. Replaces any current values if they are already present in the URL. Args: url (str): The URL to update. params (Mapping[str, str]): A mapping of query parameter keys to values. remove (Sequ...
Updates a URL's query parameters. Replaces any current values if they are already present in the URL. Args: url (str): The URL to update. params (Mapping[str, str]): A mapping of query parameter keys to values. remove (Sequence[str]): Parameters to remove from the query str...
Below is the the instruction that describes the task: ### Input: Updates a URL's query parameters. Replaces any current values if they are already present in the URL. Args: url (str): The URL to update. params (Mapping[str, str]): A mapping of query parameter keys to values. ...
def close(self): """ close all http connections. returns a deferred that fires once they're all closed. """ def validate_client(client): """ Validate that the connection is for the current client :param client: :return: ...
close all http connections. returns a deferred that fires once they're all closed.
Below is the the instruction that describes the task: ### Input: close all http connections. returns a deferred that fires once they're all closed. ### Response: def close(self): """ close all http connections. returns a deferred that fires once they're all closed. """ ...
def count_lines_in_file(self, fname=''): """ you wont believe what this method does """ i = 0 if fname == '': fname = self.fullname try: #with open(fname, encoding="utf8") as f: with codecs.open(fname, "r",encoding='utf8', errors='ignore') as f: ...
you wont believe what this method does
Below is the the instruction that describes the task: ### Input: you wont believe what this method does ### Response: def count_lines_in_file(self, fname=''): """ you wont believe what this method does """ i = 0 if fname == '': fname = self.fullname try: #wit...
def import_class(self, import_name): """ import selected class :param import_name, str, e.g. some.module.MyClass :return the class """ module_name, class_name = import_name.rsplit(".", 1) mod = import_module(module_name) check_class = getattr(mod, class_n...
import selected class :param import_name, str, e.g. some.module.MyClass :return the class
Below is the the instruction that describes the task: ### Input: import selected class :param import_name, str, e.g. some.module.MyClass :return the class ### Response: def import_class(self, import_name): """ import selected class :param import_name, str, e.g. some.module...
def check_expired_activation(self, activation_key): """ Check if ``activation_key`` is still valid. Raises a ``self.model.DoesNotExist`` exception if key is not present or ``activation_key`` is not a valid string :param activation_key: String containing the secret ...
Check if ``activation_key`` is still valid. Raises a ``self.model.DoesNotExist`` exception if key is not present or ``activation_key`` is not a valid string :param activation_key: String containing the secret SHA1 for a valid activation. :return: True if the k...
Below is the the instruction that describes the task: ### Input: Check if ``activation_key`` is still valid. Raises a ``self.model.DoesNotExist`` exception if key is not present or ``activation_key`` is not a valid string :param activation_key: String containing the secret SHA...
def initStateFrom(self, particleId, particleState, newBest): """Init all of our variable positions, velocities, and optionally the best result and best position from the given particle. If newBest is true, we get the best result and position for this new generation from the resultsDB, This is used when...
Init all of our variable positions, velocities, and optionally the best result and best position from the given particle. If newBest is true, we get the best result and position for this new generation from the resultsDB, This is used when evoloving a particle because the bestResult and position as sto...
Below is the the instruction that describes the task: ### Input: Init all of our variable positions, velocities, and optionally the best result and best position from the given particle. If newBest is true, we get the best result and position for this new generation from the resultsDB, This is used whe...
def decorated_with(func: astroid.FunctionDef, qnames: Iterable[str]) -> bool: """Determine if the `func` node has a decorator with the qualified name `qname`.""" decorators = func.decorators.nodes if func.decorators else [] for decorator_node in decorators: try: if any( i...
Determine if the `func` node has a decorator with the qualified name `qname`.
Below is the the instruction that describes the task: ### Input: Determine if the `func` node has a decorator with the qualified name `qname`. ### Response: def decorated_with(func: astroid.FunctionDef, qnames: Iterable[str]) -> bool: """Determine if the `func` node has a decorator with the qualified name `qna...
def write_config(self): """Write the configuration to a local file. :return: Boolean if successful """ json.dump( self.config, open(CONFIG_FILE, 'w'), indent=4, separators=(',', ': ') ) return True
Write the configuration to a local file. :return: Boolean if successful
Below is the the instruction that describes the task: ### Input: Write the configuration to a local file. :return: Boolean if successful ### Response: def write_config(self): """Write the configuration to a local file. :return: Boolean if successful """ json.dump( ...
def address_to_coords(self, address): """Convert address to coordinates""" base_coords = self.BASE_COORDS[self.region] get_cord = self.COORD_SERVERS[self.region] url_options = { "q": address, "lang": "eng", "origin": "livemap", "lat": base...
Convert address to coordinates
Below is the the instruction that describes the task: ### Input: Convert address to coordinates ### Response: def address_to_coords(self, address): """Convert address to coordinates""" base_coords = self.BASE_COORDS[self.region] get_cord = self.COORD_SERVERS[self.region] url_option...
def hist(table, field=-1, class_column=None, title='', verbosity=2, **kwargs): """Plot discrete PDFs >>> df = pd.DataFrame(pd.np.random.randn(99,3), columns=list('ABC')) >>> df['Class'] = pd.np.array((pd.np.matrix([1,1,1])*pd.np.matrix(df).T).T > 0) >>> len(hist(df, verbosity=0, class_column='...
Plot discrete PDFs >>> df = pd.DataFrame(pd.np.random.randn(99,3), columns=list('ABC')) >>> df['Class'] = pd.np.array((pd.np.matrix([1,1,1])*pd.np.matrix(df).T).T > 0) >>> len(hist(df, verbosity=0, class_column='Class')) 3
Below is the the instruction that describes the task: ### Input: Plot discrete PDFs >>> df = pd.DataFrame(pd.np.random.randn(99,3), columns=list('ABC')) >>> df['Class'] = pd.np.array((pd.np.matrix([1,1,1])*pd.np.matrix(df).T).T > 0) >>> len(hist(df, verbosity=0, class_column='Class')) 3 ### Respons...
def implicit_includes (self, feature, target_type): """ Returns the properties which specify implicit include paths to generated headers. This traverses all targets in this subvariant, and subvariants referred by <implcit-dependecy>properties. For all targets which are of typ...
Returns the properties which specify implicit include paths to generated headers. This traverses all targets in this subvariant, and subvariants referred by <implcit-dependecy>properties. For all targets which are of type 'target-type' (or for all targets, if 'target_type...
Below is the the instruction that describes the task: ### Input: Returns the properties which specify implicit include paths to generated headers. This traverses all targets in this subvariant, and subvariants referred by <implcit-dependecy>properties. For all targets which are o...
def get_template_names(self): """ Return the page's specified template name, or a fallback if one hasn't been chosen. """ posted_name = self.request.POST.get('template_name') if posted_name: return [posted_name,] else: return super(PagePreviewView,...
Return the page's specified template name, or a fallback if one hasn't been chosen.
Below is the the instruction that describes the task: ### Input: Return the page's specified template name, or a fallback if one hasn't been chosen. ### Response: def get_template_names(self): """ Return the page's specified template name, or a fallback if one hasn't been chosen. """ ...
def load(self): """ Extract tabular data as |TableData| instances from a JSON file. |load_source_desc_file| This method can be loading four types of JSON formats: **(1)** Single table data in a file: .. code-block:: json :caption: Acceptable JSON Sc...
Extract tabular data as |TableData| instances from a JSON file. |load_source_desc_file| This method can be loading four types of JSON formats: **(1)** Single table data in a file: .. code-block:: json :caption: Acceptable JSON Schema (1): single table ...
Below is the the instruction that describes the task: ### Input: Extract tabular data as |TableData| instances from a JSON file. |load_source_desc_file| This method can be loading four types of JSON formats: **(1)** Single table data in a file: .. code-block:: json ...
def is_training_name(name): """ **Guess** if this variable is only used in training. Only used internally to avoid too many logging. Do not use it. """ # TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES? # TODO or use get_slot_names() name = get_op_tensor_name(name)[0...
**Guess** if this variable is only used in training. Only used internally to avoid too many logging. Do not use it.
Below is the the instruction that describes the task: ### Input: **Guess** if this variable is only used in training. Only used internally to avoid too many logging. Do not use it. ### Response: def is_training_name(name): """ **Guess** if this variable is only used in training. Only used internall...
def resizeToMinimum(self): """ Resizes the dock toolbar to the minimum sizes. """ offset = self.padding() min_size = self.minimumPixmapSize() if self.position() in (XDockToolbar.Position.East, XDockToolbar.Position.West): ...
Resizes the dock toolbar to the minimum sizes.
Below is the the instruction that describes the task: ### Input: Resizes the dock toolbar to the minimum sizes. ### Response: def resizeToMinimum(self): """ Resizes the dock toolbar to the minimum sizes. """ offset = self.padding() min_size = self.minimumPixmapSize() ...
def doc(self, groups=None, set_location=True, **properties): """Add flask route to autodoc for automatic documentation Any route decorated with this method will be added to the list of routes to be documented by the generate() or html() methods. By default, the route is added to the 'a...
Add flask route to autodoc for automatic documentation Any route decorated with this method will be added to the list of routes to be documented by the generate() or html() methods. By default, the route is added to the 'all' group. By specifying group or groups argument, the route can...
Below is the the instruction that describes the task: ### Input: Add flask route to autodoc for automatic documentation Any route decorated with this method will be added to the list of routes to be documented by the generate() or html() methods. By default, the route is added to the 'all'...
def __generate(results): """ Static method which generates the Junit xml string from results :param results: Results as ResultList object. :return: Junit xml format string. """ doc, tag, text = Doc().tagtext() # Counters for testsuite tag info count = 0 ...
Static method which generates the Junit xml string from results :param results: Results as ResultList object. :return: Junit xml format string.
Below is the the instruction that describes the task: ### Input: Static method which generates the Junit xml string from results :param results: Results as ResultList object. :return: Junit xml format string. ### Response: def __generate(results): """ Static method which generates ...
def coroutine(func): """Decorator for priming generator-based coroutines. """ @wraps(func) def start(*args, **kwargs): g = func(*args, **kwargs) next(g) return g return start
Decorator for priming generator-based coroutines.
Below is the the instruction that describes the task: ### Input: Decorator for priming generator-based coroutines. ### Response: def coroutine(func): """Decorator for priming generator-based coroutines. """ @wraps(func) def start(*args, **kwargs): g = func(*args, **kwargs) next(g) ...
def add_edge(self, start, end, **kwargs): """ Add an edge between two nodes. The nodes will be automatically added if they are not present in the network. Parameters ---------- start: tuple Both the start and end nodes should specify the time slice as ...
Add an edge between two nodes. The nodes will be automatically added if they are not present in the network. Parameters ---------- start: tuple Both the start and end nodes should specify the time slice as (node_name, time_slice). Here, node_name can be an...
Below is the the instruction that describes the task: ### Input: Add an edge between two nodes. The nodes will be automatically added if they are not present in the network. Parameters ---------- start: tuple Both the start and end nodes should specify the time slice...
def reset(self): """ Kills old session and creates a new one with no proxies or headers """ # Kill old connection self.quit() # Clear chrome configs self.opts = webdriver.ChromeOptions() # Create new web driver self._create_session()
Kills old session and creates a new one with no proxies or headers
Below is the the instruction that describes the task: ### Input: Kills old session and creates a new one with no proxies or headers ### Response: def reset(self): """ Kills old session and creates a new one with no proxies or headers """ # Kill old connection self.quit() ...
def get_feed(self, buckets=None, since=None, results=15, start=0): """ Returns feed (news, blogs, reviews, audio, video) for the catalog artists; response depends on requested buckets Args: Kwargs: buckets (list): A list of strings specifying which feed items to retrieve ...
Returns feed (news, blogs, reviews, audio, video) for the catalog artists; response depends on requested buckets Args: Kwargs: buckets (list): A list of strings specifying which feed items to retrieve results (int): An integer number of results to return start (in...
Below is the the instruction that describes the task: ### Input: Returns feed (news, blogs, reviews, audio, video) for the catalog artists; response depends on requested buckets Args: Kwargs: buckets (list): A list of strings specifying which feed items to retrieve results...
def new_named_args(self, cur_named_args: Dict[str, Any]) -> Dict[str, Any]: """ create new named args updating current name args""" named_args = cur_named_args.copy() named_args.update(self.matchdict) return named_args
create new named args updating current name args
Below is the the instruction that describes the task: ### Input: create new named args updating current name args ### Response: def new_named_args(self, cur_named_args: Dict[str, Any]) -> Dict[str, Any]: """ create new named args updating current name args""" named_args = cur_named_args.copy() ...
def add(self, group_name, session): '''taobao.crm.group.add 卖家创建一个分组 卖家创建一个新的分组,接口返回一个创建成功的分组的id''' request = TOPRequest('taobao.crm.group.add') request['group_name'] = group_name self.create(self.execute(request, session), fields=['is_success', 'group_id']) retu...
taobao.crm.group.add 卖家创建一个分组 卖家创建一个新的分组,接口返回一个创建成功的分组的id
Below is the the instruction that describes the task: ### Input: taobao.crm.group.add 卖家创建一个分组 卖家创建一个新的分组,接口返回一个创建成功的分组的id ### Response: def add(self, group_name, session): '''taobao.crm.group.add 卖家创建一个分组 卖家创建一个新的分组,接口返回一个创建成功的分组的id''' request = TOPRequest('taobao...
def eye(root=None, zodb_uri=None, port=8080): """Serves a WSGI app to browse objects based on a root object or ZODB URI. """ if root is not None: root_factory = lambda request: Node(root) elif zodb_uri is not None: if '://' not in zodb_uri: # treat it as a file:// ...
Serves a WSGI app to browse objects based on a root object or ZODB URI.
Below is the the instruction that describes the task: ### Input: Serves a WSGI app to browse objects based on a root object or ZODB URI. ### Response: def eye(root=None, zodb_uri=None, port=8080): """Serves a WSGI app to browse objects based on a root object or ZODB URI. """ if root is not None: ...
def ready(ctx, quiet): """Show all the checks that can be released.""" user_config = ctx.obj cached_prs = {} for target in sorted(get_valid_checks()): # get the name of the current release tag cur_version = get_version_string(target) target_tag = get_release_tag_string(target, c...
Show all the checks that can be released.
Below is the the instruction that describes the task: ### Input: Show all the checks that can be released. ### Response: def ready(ctx, quiet): """Show all the checks that can be released.""" user_config = ctx.obj cached_prs = {} for target in sorted(get_valid_checks()): # get the name of ...
def _realGetLoader(n, default=_marker): """ Search all themes for a template named C{n}, returning a loader for it if found. If not found and a default is passed, the default will be returned. Otherwise C{RuntimeError} will be raised. This function is deprecated in favor of using a L{ThemedElement}...
Search all themes for a template named C{n}, returning a loader for it if found. If not found and a default is passed, the default will be returned. Otherwise C{RuntimeError} will be raised. This function is deprecated in favor of using a L{ThemedElement} for your view code, or calling ITemplateNam...
Below is the the instruction that describes the task: ### Input: Search all themes for a template named C{n}, returning a loader for it if found. If not found and a default is passed, the default will be returned. Otherwise C{RuntimeError} will be raised. This function is deprecated in favor of using a...
async def create_cred( self, cred_offer_json, cred_req_json: str, cred_attrs: dict, rr_size: int = None) -> (str, str): """ Create credential as Issuer out of credential request and dict of key:value (raw, unencoded) entries for attribu...
Create credential as Issuer out of credential request and dict of key:value (raw, unencoded) entries for attributes. Return credential json, and if cred def supports revocation, credential revocation identifier. Raise WalletState for closed wallet. If the credential definition supports...
Below is the the instruction that describes the task: ### Input: Create credential as Issuer out of credential request and dict of key:value (raw, unencoded) entries for attributes. Return credential json, and if cred def supports revocation, credential revocation identifier. Raise WalletSt...