code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _get_balance( self, get_address, min_confs ): """ Works only in test mode! Get the confirmed balance for an address """ bitcoind_opts = get_bitcoin_opts() bitcoind_host = bitcoind_opts['bitcoind_server'] bitcoind_port = bitcoind_opts['bitcoind_port'] b...
Works only in test mode! Get the confirmed balance for an address
Below is the the instruction that describes the task: ### Input: Works only in test mode! Get the confirmed balance for an address ### Response: def _get_balance( self, get_address, min_confs ): """ Works only in test mode! Get the confirmed balance for an address """ ...
def SetLogger(logger): """Sets the logger object to use for all 'LOG' breakpoint actions.""" global log_info_message global log_warning_message global log_error_message log_info_message = logger.info log_warning_message = logger.warning log_error_message = logger.error logger.addFilter(LineNoFilter())
Sets the logger object to use for all 'LOG' breakpoint actions.
Below is the the instruction that describes the task: ### Input: Sets the logger object to use for all 'LOG' breakpoint actions. ### Response: def SetLogger(logger): """Sets the logger object to use for all 'LOG' breakpoint actions.""" global log_info_message global log_warning_message global log_error_mes...
def dhcp_request(iface=None, **kargs): """Send a DHCP discover request and return the answer""" if conf.checkIPaddr != 0: warning("conf.checkIPaddr is not 0, I may not be able to match the answer") # noqa: E501 if iface is None: iface = conf.iface fam, hw = get_if_raw_hwaddr(iface) ...
Send a DHCP discover request and return the answer
Below is the the instruction that describes the task: ### Input: Send a DHCP discover request and return the answer ### Response: def dhcp_request(iface=None, **kargs): """Send a DHCP discover request and return the answer""" if conf.checkIPaddr != 0: warning("conf.checkIPaddr is not 0, I may not b...
def file_finder(dirname="."): """ Find the files in ``dirname`` under Mercurial version control according to the setuptools spec (see http://peak.telecommunity.com/DevCenter/setuptools#adding-support-for-other-revision-control-systems ). """ import distutils.log dirname = dirname or '.' try: valid_mgrs = man...
Find the files in ``dirname`` under Mercurial version control according to the setuptools spec (see http://peak.telecommunity.com/DevCenter/setuptools#adding-support-for-other-revision-control-systems ).
Below is the the instruction that describes the task: ### Input: Find the files in ``dirname`` under Mercurial version control according to the setuptools spec (see http://peak.telecommunity.com/DevCenter/setuptools#adding-support-for-other-revision-control-systems ). ### Response: def file_finder(dirname="."):...
async def available_resets(request: web.Request) -> web.Response: """ Indicate what parts of the user configuration are available for reset. """ return web.json_response({'options': _settings_reset_options}, status=200)
Indicate what parts of the user configuration are available for reset.
Below is the the instruction that describes the task: ### Input: Indicate what parts of the user configuration are available for reset. ### Response: async def available_resets(request: web.Request) -> web.Response: """ Indicate what parts of the user configuration are available for reset. """ return w...
def get_annotation_types(self, item_url): """ Retrieve the annotation types for the given item from the server :type item_url: String or Item :param item_url: URL of the item, or an Item object :rtype: List :returns: a List specifying the annotation types :raises: APIE...
Retrieve the annotation types for the given item from the server :type item_url: String or Item :param item_url: URL of the item, or an Item object :rtype: List :returns: a List specifying the annotation types :raises: APIError if the request was not successful
Below is the the instruction that describes the task: ### Input: Retrieve the annotation types for the given item from the server :type item_url: String or Item :param item_url: URL of the item, or an Item object :rtype: List :returns: a List specifying the annotation types ...
def move_file_to_directory(file_path, directory_path): """Moves file to given directory :param file_path: path to file to move :param directory_path: path to target directory where to move file """ file_name = os.path.basename(file_path) # get name of file if not os.pat...
Moves file to given directory :param file_path: path to file to move :param directory_path: path to target directory where to move file
Below is the the instruction that describes the task: ### Input: Moves file to given directory :param file_path: path to file to move :param directory_path: path to target directory where to move file ### Response: def move_file_to_directory(file_path, directory_path): """Moves file to giv...
def _build_deployments_object( contract_type: str, deployment_bytecode: Dict[str, Any], runtime_bytecode: Dict[str, Any], compiler: Dict[str, Any], address: HexStr, tx: HexStr, block: HexStr, manifest: Dict[str, Any], ) -> Iterable[Tuple[str, Any]]: """ Returns a dict with proper...
Returns a dict with properly formatted deployment data.
Below is the the instruction that describes the task: ### Input: Returns a dict with properly formatted deployment data. ### Response: def _build_deployments_object( contract_type: str, deployment_bytecode: Dict[str, Any], runtime_bytecode: Dict[str, Any], compiler: Dict[str, Any], address: Hex...
def _tx_timer_handler(self): """Method called every time the tx_timer times out, which can happen in two situations: either a Flow Control frame was not received in time, or the Separation Time Min is expired and a new frame must be sent.""" with self.tx_mutex: if (self.tx_s...
Method called every time the tx_timer times out, which can happen in two situations: either a Flow Control frame was not received in time, or the Separation Time Min is expired and a new frame must be sent.
Below is the the instruction that describes the task: ### Input: Method called every time the tx_timer times out, which can happen in two situations: either a Flow Control frame was not received in time, or the Separation Time Min is expired and a new frame must be sent. ### Response: def _tx_timer...
def activate_script(self): """activates the script command""" # must be rethought # ./scripts # deploydir/./scripts self._add_scope("script") self.scripts = {} self.script_files = [ "./scripts/script_*.txt", "~/.cloudmesh/scripts/script_*.txt"] ...
activates the script command
Below is the the instruction that describes the task: ### Input: activates the script command ### Response: def activate_script(self): """activates the script command""" # must be rethought # ./scripts # deploydir/./scripts self._add_scope("script") self.scripts = {...
def triangles_keep_cortex(triangles, cortex): """ Remove triangles with nodes not contained in the cortex label array """ # for or each face/triangle keep only those that only contain nodes within the list of cortex nodes input_shape = triangles.shape triangle_is_in_cortex = np.all(np.reshape(n...
Remove triangles with nodes not contained in the cortex label array
Below is the the instruction that describes the task: ### Input: Remove triangles with nodes not contained in the cortex label array ### Response: def triangles_keep_cortex(triangles, cortex): """ Remove triangles with nodes not contained in the cortex label array """ # for or each face/triangle k...
def from_df(cls, df:DataFrame, path:PathOrStr, cols:IntsOrStrs=0, folder:PathOrStr=None, suffix:str='', **kwargs)->'ItemList': "Get the filenames in `cols` of `df` with `folder` in front of them, `suffix` at the end." suffix = suffix or '' res = super().from_df(df, path=path, cols=cols, **kwargs...
Get the filenames in `cols` of `df` with `folder` in front of them, `suffix` at the end.
Below is the the instruction that describes the task: ### Input: Get the filenames in `cols` of `df` with `folder` in front of them, `suffix` at the end. ### Response: def from_df(cls, df:DataFrame, path:PathOrStr, cols:IntsOrStrs=0, folder:PathOrStr=None, suffix:str='', **kwargs)->'ItemList': "Get the fil...
def _spintaylor_aligned_prec_swapper(**p): """ SpinTaylorF2 is only single spin, it also struggles with anti-aligned spin waveforms. This construct chooses between the aligned-twospin TaylorF2 model and the precessing singlespin SpinTaylorF2 models. If aligned spins are given, use TaylorF2, if nonal...
SpinTaylorF2 is only single spin, it also struggles with anti-aligned spin waveforms. This construct chooses between the aligned-twospin TaylorF2 model and the precessing singlespin SpinTaylorF2 models. If aligned spins are given, use TaylorF2, if nonaligned spins are given use SpinTaylorF2. In the case...
Below is the the instruction that describes the task: ### Input: SpinTaylorF2 is only single spin, it also struggles with anti-aligned spin waveforms. This construct chooses between the aligned-twospin TaylorF2 model and the precessing singlespin SpinTaylorF2 models. If aligned spins are given, use Tayl...
def upload_activity(self, activity_file, data_type, name=None, description=None, activity_type=None, private=None, external_id=None): """ Uploads a GPS file (tcx, gpx) to create a new activity for current athlete. http://strava.github.io/api/v3/athlete/#get-details ...
Uploads a GPS file (tcx, gpx) to create a new activity for current athlete. http://strava.github.io/api/v3/athlete/#get-details :param activity_file: The file object to upload or file contents. :type activity_file: file or str :param data_type: File format for upload. Possible values:...
Below is the the instruction that describes the task: ### Input: Uploads a GPS file (tcx, gpx) to create a new activity for current athlete. http://strava.github.io/api/v3/athlete/#get-details :param activity_file: The file object to upload or file contents. :type activity_file: file or st...
def kick_drawer(self, port=0, **kwargs): """Kick drawer connected to the given port. In this implementation, cash drawers are identified according to the port in which they are connected. This relation between drawers and ports does not exists in the ESC/POS specification and it is just...
Kick drawer connected to the given port. In this implementation, cash drawers are identified according to the port in which they are connected. This relation between drawers and ports does not exists in the ESC/POS specification and it is just a design decision to normalize cash drawers...
Below is the the instruction that describes the task: ### Input: Kick drawer connected to the given port. In this implementation, cash drawers are identified according to the port in which they are connected. This relation between drawers and ports does not exists in the ESC/POS specificati...
def getListForEvent(self, event=None): ''' Get the list of names associated with a particular event. ''' names = list(self.guestlistname_set.annotate( guestType=Case( When(notes__isnull=False, then=F('notes')), default=Value(ugettext('Manually Added')), ...
Get the list of names associated with a particular event.
Below is the the instruction that describes the task: ### Input: Get the list of names associated with a particular event. ### Response: def getListForEvent(self, event=None): ''' Get the list of names associated with a particular event. ''' names = list(self.guestlistname_set.annotate( ...
def set(self, key, value): """Set a value at key and return a Future. :rtype: Iterable[tornado.concurrent.Future] """ value_encoded = encode(value) if key in self.data and self.data[key] == value_encoded: return [] self.data[key] = value_encoded ret...
Set a value at key and return a Future. :rtype: Iterable[tornado.concurrent.Future]
Below is the the instruction that describes the task: ### Input: Set a value at key and return a Future. :rtype: Iterable[tornado.concurrent.Future] ### Response: def set(self, key, value): """Set a value at key and return a Future. :rtype: Iterable[tornado.concurrent.Future] """ ...
def get_addresses_on_both_chains(wallet_obj, used=None, zero_balance=None): ''' Get addresses across both subchains based on the filter criteria passed in Returns a list of dicts of the following form: [ {'address': '1abc123...', 'path': 'm/0/9', 'pubkeyhex': '0123456...'}, ...
Get addresses across both subchains based on the filter criteria passed in Returns a list of dicts of the following form: [ {'address': '1abc123...', 'path': 'm/0/9', 'pubkeyhex': '0123456...'}, ..., ] Dicts may also contain WIF and privkeyhex if wallet_obj has private ...
Below is the the instruction that describes the task: ### Input: Get addresses across both subchains based on the filter criteria passed in Returns a list of dicts of the following form: [ {'address': '1abc123...', 'path': 'm/0/9', 'pubkeyhex': '0123456...'}, ..., ] ...
def _initPatterns(ptc): """ Helper function to take the different localized bits from ptc and create the regex strings. """ # TODO add code to parse the date formats and build the regexes up from sub-parts # TODO find all hard-coded uses of date/time seperators ptc.RE_DATE4 = r'''(?P<da...
Helper function to take the different localized bits from ptc and create the regex strings.
Below is the the instruction that describes the task: ### Input: Helper function to take the different localized bits from ptc and create the regex strings. ### Response: def _initPatterns(ptc): """ Helper function to take the different localized bits from ptc and create the regex strings. """ ...
def _create_session(self): """ Instantiate a new session object for use in connecting with SAP SuccessFactors """ session = requests.Session() session.timeout = self.SESSION_TIMEOUT oauth_access_token, expires_at = SAPSuccessFactorsAPIClient.get_oauth_access_token( ...
Instantiate a new session object for use in connecting with SAP SuccessFactors
Below is the the instruction that describes the task: ### Input: Instantiate a new session object for use in connecting with SAP SuccessFactors ### Response: def _create_session(self): """ Instantiate a new session object for use in connecting with SAP SuccessFactors """ session = r...
def each(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce each item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric """ if iterable is None: return _each_decorator(name, metri...
Measure time elapsed to produce each item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric
Below is the the instruction that describes the task: ### Input: Measure time elapsed to produce each item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric ### Response: def each(iterable = None, *, name = None, metric = call_default)...
def newDtd(self, name, ExternalID, SystemID): """Creation of a new DTD for the external subset. To create an internal subset, use xmlCreateIntSubset(). """ ret = libxml2mod.xmlNewDtd(self._o, name, ExternalID, SystemID) if ret is None:raise treeError('xmlNewDtd() failed') __tm...
Creation of a new DTD for the external subset. To create an internal subset, use xmlCreateIntSubset().
Below is the the instruction that describes the task: ### Input: Creation of a new DTD for the external subset. To create an internal subset, use xmlCreateIntSubset(). ### Response: def newDtd(self, name, ExternalID, SystemID): """Creation of a new DTD for the external subset. To create an ...
def random_deinterleave(text, separator_symbol="X"): """Create a fill-in-the-blanks training example from text. Split on spaces, then cut into segments at random points. Alternate segments are assigned to the two output strings. separator_symbol separates segments within each of the outputs. example: t...
Create a fill-in-the-blanks training example from text. Split on spaces, then cut into segments at random points. Alternate segments are assigned to the two output strings. separator_symbol separates segments within each of the outputs. example: text="The quick brown fox jumps over the lazy dog." ret...
Below is the the instruction that describes the task: ### Input: Create a fill-in-the-blanks training example from text. Split on spaces, then cut into segments at random points. Alternate segments are assigned to the two output strings. separator_symbol separates segments within each of the outputs. exa...
def find_kwupdate_location(self,hdr,keyword): """ Find the last keyword in the output header that comes before the new keyword in the original, full input headers. This will rely on the original ordering of keywords from the original input files in order to place the updated keyw...
Find the last keyword in the output header that comes before the new keyword in the original, full input headers. This will rely on the original ordering of keywords from the original input files in order to place the updated keyword in the correct location in case the keyword was remove...
Below is the the instruction that describes the task: ### Input: Find the last keyword in the output header that comes before the new keyword in the original, full input headers. This will rely on the original ordering of keywords from the original input files in order to place the updated k...
def _write(self, text): """Write text by respecting the current indentlevel""" spaces = ' ' * (self.indent * self.indentlevel) t = spaces + text.strip() + '\n' if hasattr(t, 'encode'): t = t.encode(self.encoding, 'xmlcharrefreplace') self.stream.write(t)
Write text by respecting the current indentlevel
Below is the the instruction that describes the task: ### Input: Write text by respecting the current indentlevel ### Response: def _write(self, text): """Write text by respecting the current indentlevel""" spaces = ' ' * (self.indent * self.indentlevel) t = spaces + text.strip() + '\n' ...
def get_orderbook(self, market, depth_type=BOTH_ORDERBOOK): """ Used to get retrieve the orderbook for a given market. The depth_type parameter is IGNORED under v2.0 and both orderbooks are always returned Endpoint: 1.1 /public/getorderbook 2.0 /pub/Market/GetMarketOrde...
Used to get retrieve the orderbook for a given market. The depth_type parameter is IGNORED under v2.0 and both orderbooks are always returned Endpoint: 1.1 /public/getorderbook 2.0 /pub/Market/GetMarketOrderBook :param market: String literal for the market (ex: BTC-LTC) ...
Below is the the instruction that describes the task: ### Input: Used to get retrieve the orderbook for a given market. The depth_type parameter is IGNORED under v2.0 and both orderbooks are always returned Endpoint: 1.1 /public/getorderbook 2.0 /pub/Market/GetMarketOrderBook ...
def build_one(self, object, lines, fasta, fw, newagp=None): """ Construct molecule using component fasta sequence """ components = [] total_bp = 0 for line in lines: if line.is_gap: seq = 'N' * line.gap_length if newagp: ...
Construct molecule using component fasta sequence
Below is the the instruction that describes the task: ### Input: Construct molecule using component fasta sequence ### Response: def build_one(self, object, lines, fasta, fw, newagp=None): """ Construct molecule using component fasta sequence """ components = [] total_bp = ...
def _GetDebuggeeDescription(self): """Formats debuggee description based on debuggee labels.""" return '-'.join(self._debuggee_labels[label] for label in _DESCRIPTION_LABELS if label in self._debuggee_labels)
Formats debuggee description based on debuggee labels.
Below is the the instruction that describes the task: ### Input: Formats debuggee description based on debuggee labels. ### Response: def _GetDebuggeeDescription(self): """Formats debuggee description based on debuggee labels.""" return '-'.join(self._debuggee_labels[label] for label in...
def _vel_disp_one(self, kwargs_profile, kwargs_aperture, kwargs_light, kwargs_anisotropy): """ computes one realisation of the velocity dispersion realized in the slit :param gamma: :param rho0_r0_gamma: :param r_eff: :param r_ani: :param R_slit: :param dR...
computes one realisation of the velocity dispersion realized in the slit :param gamma: :param rho0_r0_gamma: :param r_eff: :param r_ani: :param R_slit: :param dR_slit: :param FWHM: :return:
Below is the the instruction that describes the task: ### Input: computes one realisation of the velocity dispersion realized in the slit :param gamma: :param rho0_r0_gamma: :param r_eff: :param r_ani: :param R_slit: :param dR_slit: :param FWHM: :retur...
def parse_value(val): """Parse input string and return int, float or str depending on format. @param val: Input string. @return: Value of type int, float or str. """ mobj = re.match('(-{0,1}\d+)\s*(\sseconds|/\s*\w+)$', val) if mobj: return int(mobj.group(1)) m...
Parse input string and return int, float or str depending on format. @param val: Input string. @return: Value of type int, float or str.
Below is the the instruction that describes the task: ### Input: Parse input string and return int, float or str depending on format. @param val: Input string. @return: Value of type int, float or str. ### Response: def parse_value(val): """Parse input string and return int, float or str depend...
def postinit(self, body=None, finalbody=None): """Do some setup after initialisation. :param body: The try-except that the finally is attached to. :type body: list(TryExcept) or None :param finalbody: The contents of the ``finally`` block. :type finalbody: list(NodeNG) or None ...
Do some setup after initialisation. :param body: The try-except that the finally is attached to. :type body: list(TryExcept) or None :param finalbody: The contents of the ``finally`` block. :type finalbody: list(NodeNG) or None
Below is the the instruction that describes the task: ### Input: Do some setup after initialisation. :param body: The try-except that the finally is attached to. :type body: list(TryExcept) or None :param finalbody: The contents of the ``finally`` block. :type finalbody: list(NodeN...
def int_out_of_bounds(self, index, axis=0): """ examples if index is out of local processing bounds function is used to perform examples for index of type integer :param index: global index to examples as type int :param axis: current axis to examples :return: return input or ra...
examples if index is out of local processing bounds function is used to perform examples for index of type integer :param index: global index to examples as type int :param axis: current axis to examples :return: return input or raise error
Below is the the instruction that describes the task: ### Input: examples if index is out of local processing bounds function is used to perform examples for index of type integer :param index: global index to examples as type int :param axis: current axis to examples :return: retur...
def ParseFileObject(self, parser_mediator, file_object): """Parses a BSM file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object. Raises: Unab...
Parses a BSM file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object. Raises: UnableToParseFile: when the file cannot be parsed.
Below is the the instruction that describes the task: ### Input: Parses a BSM file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object. Raises: ...
def parse_blocks(self, text): """Extract the code and non-code blocks from given markdown text. Returns a list of block dictionaries. Each dictionary has at least the keys 'type' and 'content', containing the type of the block ('markdown', 'code') and the contents of the block....
Extract the code and non-code blocks from given markdown text. Returns a list of block dictionaries. Each dictionary has at least the keys 'type' and 'content', containing the type of the block ('markdown', 'code') and the contents of the block. Additional keys may be parsed a...
Below is the the instruction that describes the task: ### Input: Extract the code and non-code blocks from given markdown text. Returns a list of block dictionaries. Each dictionary has at least the keys 'type' and 'content', containing the type of the block ('markdown', 'code') and ...
def _handleClassAttr(self): ''' _handleClassAttr - Hack to ensure "class" and "style" show up in attributes when classes are set, and doesn't when no classes are present on associated tag. TODO: I don't like this hack. ''' if len(self.tag._classNames)...
_handleClassAttr - Hack to ensure "class" and "style" show up in attributes when classes are set, and doesn't when no classes are present on associated tag. TODO: I don't like this hack.
Below is the the instruction that describes the task: ### Input: _handleClassAttr - Hack to ensure "class" and "style" show up in attributes when classes are set, and doesn't when no classes are present on associated tag. TODO: I don't like this hack. ### Response: def _handleClass...
def send_msg(self, connection, data): """ Function to send messages Parameters ---------- connection: socket or connection data: data that can be serialized to json """ # serialize as JSON msg = json.dumps(data) # Prefix...
Function to send messages Parameters ---------- connection: socket or connection data: data that can be serialized to json
Below is the the instruction that describes the task: ### Input: Function to send messages Parameters ---------- connection: socket or connection data: data that can be serialized to json ### Response: def send_msg(self, connection, data): """ Functio...
def checkout_default_branch(self): """ git checkout default branch """ set_state(WORKFLOW_STATES.CHECKING_OUT_DEFAULT_BRANCH) cmd = "git", "checkout", self.config["default_branch"] self.run_cmd(cmd) set_state(WORKFLOW_STATES.CHECKED_OUT_DEFAULT_BRANCH)
git checkout default branch
Below is the the instruction that describes the task: ### Input: git checkout default branch ### Response: def checkout_default_branch(self): """ git checkout default branch """ set_state(WORKFLOW_STATES.CHECKING_OUT_DEFAULT_BRANCH) cmd = "git", "checkout", self.config["default_branch"] ...
def op_with_scalar_cast(a, b, f): """ Builds the graph to compute f(a, b). If only one of the two arguments is a scalar and the operation would cause a type error without casting, casts the scalar to match the tensor. :param a: a tf-compatible array or scalar :param b: a tf-compatible array or scalar ""...
Builds the graph to compute f(a, b). If only one of the two arguments is a scalar and the operation would cause a type error without casting, casts the scalar to match the tensor. :param a: a tf-compatible array or scalar :param b: a tf-compatible array or scalar
Below is the the instruction that describes the task: ### Input: Builds the graph to compute f(a, b). If only one of the two arguments is a scalar and the operation would cause a type error without casting, casts the scalar to match the tensor. :param a: a tf-compatible array or scalar :param b: a tf-comp...
def db_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ''' ret = {} query = ( 'SELE...
Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list
Below is the the instruction that describes the task: ### Input: Return dictionary with information about databases of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.db_list ### Response: def db_list(user=None, host=None, port=None, maintenance_db=None, passwo...
def render_description_meta_tag(context, is_og=False): """ Returns the description as meta or open graph tag. """ request = context['request'] content = '' # Try to get the description from the context object (e.g. DetailViews). if context.get('object'): try: content = c...
Returns the description as meta or open graph tag.
Below is the the instruction that describes the task: ### Input: Returns the description as meta or open graph tag. ### Response: def render_description_meta_tag(context, is_og=False): """ Returns the description as meta or open graph tag. """ request = context['request'] content = '' # Tr...
def poll(self, device_code, expires_in, interval, **kwargs): """Construct the device authentication poller. :param device_code: Device authentication code :type device_code: str :param expires_in: Device authentication code expiry (in seconds) :type in: int :pa...
Construct the device authentication poller. :param device_code: Device authentication code :type device_code: str :param expires_in: Device authentication code expiry (in seconds) :type in: int :param interval: Device authentication poll interval :type interval...
Below is the the instruction that describes the task: ### Input: Construct the device authentication poller. :param device_code: Device authentication code :type device_code: str :param expires_in: Device authentication code expiry (in seconds) :type in: int :param...
def invalid_return_type_error( return_type: GraphQLObjectType, result: Any, field_nodes: List[FieldNode] ) -> GraphQLError: """Create a GraphQLError for an invalid return type.""" return GraphQLError( f"Expected value of type '{return_type.name}' but got: {inspect(result)}.", field_nodes, ...
Create a GraphQLError for an invalid return type.
Below is the the instruction that describes the task: ### Input: Create a GraphQLError for an invalid return type. ### Response: def invalid_return_type_error( return_type: GraphQLObjectType, result: Any, field_nodes: List[FieldNode] ) -> GraphQLError: """Create a GraphQLError for an invalid return type.""...
def start(name, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) data = query(action='ve',...
Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine
Below is the the instruction that describes the task: ### Input: Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ### Response: def start(name, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ...
def content_status(self, content_status): """Sets the content_status of this IntegrationStatus. Status of integration content, e.g. dashboards # noqa: E501 :param content_status: The content_status of this IntegrationStatus. # noqa: E501 :type: str """ if content_stat...
Sets the content_status of this IntegrationStatus. Status of integration content, e.g. dashboards # noqa: E501 :param content_status: The content_status of this IntegrationStatus. # noqa: E501 :type: str
Below is the the instruction that describes the task: ### Input: Sets the content_status of this IntegrationStatus. Status of integration content, e.g. dashboards # noqa: E501 :param content_status: The content_status of this IntegrationStatus. # noqa: E501 :type: str ### Response: def ...
def show_and_plot_top_positions(returns, positions_alloc, show_and_plot=2, hide_positions=False, legend_loc='real_best', ax=None, **kwargs): """ Prints and/or plots the exposures of the top 10 held positions of a...
Prints and/or plots the exposures of the top 10 held positions of all time. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. positions_alloc : pd.DataFrame Portfolio allocation of...
Below is the the instruction that describes the task: ### Input: Prints and/or plots the exposures of the top 10 held positions of all time. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_shee...
def canonical_key(self, key): """Returns the canonical key for the given ``key``.""" if key.startswith('/'): return urlparse.urljoin(self.base_uri, key) else: return self.curies.expand(key)
Returns the canonical key for the given ``key``.
Below is the the instruction that describes the task: ### Input: Returns the canonical key for the given ``key``. ### Response: def canonical_key(self, key): """Returns the canonical key for the given ``key``.""" if key.startswith('/'): return urlparse.urljoin(self.base_uri, key) ...
def _publish_internal(self, push_messages): """Send push notifications The server will validate any type of syntax errors and the client will raise the proper exceptions for the user to handle. Each notification is of the form: { 'to': 'ExponentPushToken[xxx]', ...
Send push notifications The server will validate any type of syntax errors and the client will raise the proper exceptions for the user to handle. Each notification is of the form: { 'to': 'ExponentPushToken[xxx]', 'body': 'This text gets display in the notification...
Below is the the instruction that describes the task: ### Input: Send push notifications The server will validate any type of syntax errors and the client will raise the proper exceptions for the user to handle. Each notification is of the form: { 'to': 'ExponentPushToken...
def all_logging_disabled(highest_level=logging.CRITICAL): """Disable all logging temporarily. A context manager that will prevent any logging messages triggered during the body from being processed. Args: highest_level: the maximum logging level that is being blocked """ previous_level = l...
Disable all logging temporarily. A context manager that will prevent any logging messages triggered during the body from being processed. Args: highest_level: the maximum logging level that is being blocked
Below is the the instruction that describes the task: ### Input: Disable all logging temporarily. A context manager that will prevent any logging messages triggered during the body from being processed. Args: highest_level: the maximum logging level that is being blocked ### Response: def all_log...
def inception_v3(pretrained=False, ctx=cpu(), root=os.path.join(base.data_dir(), 'models'), **kwargs): r"""Inception v3 model from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_ paper. Parameters ---------- pretrained : bool, de...
r"""Inception v3 model from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_ paper. Parameters ---------- pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in ...
Below is the the instruction that describes the task: ### Input: r"""Inception v3 model from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_ paper. Parameters ---------- pretrained : bool, default False Whether to load the pretrained weig...
def hdd_disk_interface(self, hdd_disk_interface): """ Sets the hdd disk interface for this QEMU VM. :param hdd_disk_interface: QEMU hdd disk interface """ self._hdd_disk_interface = hdd_disk_interface log.info('QEMU VM "{name}" [{id}] has set the QEMU hdd disk interface...
Sets the hdd disk interface for this QEMU VM. :param hdd_disk_interface: QEMU hdd disk interface
Below is the the instruction that describes the task: ### Input: Sets the hdd disk interface for this QEMU VM. :param hdd_disk_interface: QEMU hdd disk interface ### Response: def hdd_disk_interface(self, hdd_disk_interface): """ Sets the hdd disk interface for this QEMU VM. :para...
def get_setting(self, key, default=NOT_SET): """ Gets a setting for the key. :raise KeyError: If the key is not set and default isn't provided. """ if self._arca is None: raise LazySettingProperty.SettingsNotReady return self._arca.settings.get(*self.get_settings_key...
Gets a setting for the key. :raise KeyError: If the key is not set and default isn't provided.
Below is the the instruction that describes the task: ### Input: Gets a setting for the key. :raise KeyError: If the key is not set and default isn't provided. ### Response: def get_setting(self, key, default=NOT_SET): """ Gets a setting for the key. :raise KeyError: If the key is not set...
def boltzmann_exploration(actions, utilities, temperature, action_counter): '''returns an action with a probability depending on utilities and temperature''' utilities = [utilities[x] for x in actions] temperature = max(temperature, 0.01) _max = max(utilities) _min = min(utilities) if _max == _m...
returns an action with a probability depending on utilities and temperature
Below is the the instruction that describes the task: ### Input: returns an action with a probability depending on utilities and temperature ### Response: def boltzmann_exploration(actions, utilities, temperature, action_counter): '''returns an action with a probability depending on utilities and temperature''...
def eval(self, code, mode='single'): """Evaluate code in the context of the frame.""" if isinstance(code, str): if isinstance(code, str): code = UTF8_COOKIE + code.encode('utf-8') code = compile(code, '<interactive>', mode) if mode != 'exec': r...
Evaluate code in the context of the frame.
Below is the the instruction that describes the task: ### Input: Evaluate code in the context of the frame. ### Response: def eval(self, code, mode='single'): """Evaluate code in the context of the frame.""" if isinstance(code, str): if isinstance(code, str): code = UTF8...
def QA_SU_save_index_day(engine, client=DATABASE): """save index_day Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_index_day(client=client)
save index_day Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
Below is the the instruction that describes the task: ### Input: save index_day Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) ### Response: def QA_SU_save_index_day(engine, client=DATABASE): """save index_day ...
def select_symbols(self, symbols, ret_list=False): """ Return a :class:`PseudoTable` with the pseudopotentials with the given list of chemical symbols. Args: symbols: str or list of symbols Prepend the symbol string with "-", to exclude pseudos. ret_list:...
Return a :class:`PseudoTable` with the pseudopotentials with the given list of chemical symbols. Args: symbols: str or list of symbols Prepend the symbol string with "-", to exclude pseudos. ret_list: if True a list of pseudos is returned instead of a :class:`PseudoTable...
Below is the the instruction that describes the task: ### Input: Return a :class:`PseudoTable` with the pseudopotentials with the given list of chemical symbols. Args: symbols: str or list of symbols Prepend the symbol string with "-", to exclude pseudos. ret_list: i...
def configure_debug_logger( self, log_level='DEBUG', log_format=ReportingFormats.STDOUT.value, custom_args='' ): """debug logger for stdout messages. Replacement for print() Note: Will try to overwrite minimum log level to enable requeste...
debug logger for stdout messages. Replacement for print() Note: Will try to overwrite minimum log level to enable requested log_level Args: log_level (str): desired log level for handle https://docs.python.org/3/library/logging.html#logging-levels log_format (str):...
Below is the the instruction that describes the task: ### Input: debug logger for stdout messages. Replacement for print() Note: Will try to overwrite minimum log level to enable requested log_level Args: log_level (str): desired log level for handle https://docs.python.or...
def calibrate(self, cali_data, cali_labels): """ Runs the DkNN on holdout data to calibrate the credibility metric. :param cali_data: np array of calibration data. :param cali_labels: np vector of calibration labels. """ self.nb_cali = cali_labels.shape[0] self.cali_activations = self.get_ac...
Runs the DkNN on holdout data to calibrate the credibility metric. :param cali_data: np array of calibration data. :param cali_labels: np vector of calibration labels.
Below is the the instruction that describes the task: ### Input: Runs the DkNN on holdout data to calibrate the credibility metric. :param cali_data: np array of calibration data. :param cali_labels: np vector of calibration labels. ### Response: def calibrate(self, cali_data, cali_labels): """ Run...
def web_upload(self, package): """ * Smart enough to not save things we already have * Idempotent, you can call as many times as you need * The caller names the package (its basename) """ pkg = request.files[package] self.index.from_data(package, pkg.read()) ...
* Smart enough to not save things we already have * Idempotent, you can call as many times as you need * The caller names the package (its basename)
Below is the the instruction that describes the task: ### Input: * Smart enough to not save things we already have * Idempotent, you can call as many times as you need * The caller names the package (its basename) ### Response: def web_upload(self, package): """ * Smart enough to...
def get_hosts_files(option): """ Find out the location of the `hosts` file. This looks in multiple places such as the `-i` option, current dir and ansible configuration files. The first match is returned as a list. """ if option is not None: return option.split(',') # Use hosts file...
Find out the location of the `hosts` file. This looks in multiple places such as the `-i` option, current dir and ansible configuration files. The first match is returned as a list.
Below is the the instruction that describes the task: ### Input: Find out the location of the `hosts` file. This looks in multiple places such as the `-i` option, current dir and ansible configuration files. The first match is returned as a list. ### Response: def get_hosts_files(option): """ Find ...
def get_top_gainers(self, as_json=False): """ :return: a list of dictionaries containing top gainers of the day """ url = self.top_gainer_url req = Request(url, None, self.headers) # this can raise HTTPError and URLError res = self.opener.open(req) # for p...
:return: a list of dictionaries containing top gainers of the day
Below is the the instruction that describes the task: ### Input: :return: a list of dictionaries containing top gainers of the day ### Response: def get_top_gainers(self, as_json=False): """ :return: a list of dictionaries containing top gainers of the day """ url = self.top_gainer_...
def review_metadata_csv_multi_user(filedir, metadata, csv_in, n_headers): """ Check validity of metadata for multi user. :param filedir: This field is the filepath of the directory whose csv has to be made. :param metadata: This field is the metadata generated from the load_metadata_csv...
Check validity of metadata for multi user. :param filedir: This field is the filepath of the directory whose csv has to be made. :param metadata: This field is the metadata generated from the load_metadata_csv function. :param csv_in: This field returns a reader object which iterates over t...
Below is the the instruction that describes the task: ### Input: Check validity of metadata for multi user. :param filedir: This field is the filepath of the directory whose csv has to be made. :param metadata: This field is the metadata generated from the load_metadata_csv function. :p...
def post(self, uMsg, wParam = None, lParam = None): """ Post a low-level window message asyncronically. @type uMsg: int @param uMsg: Message code. @param wParam: The type and meaning of this parameter depends on the message. @param lParam: The ...
Post a low-level window message asyncronically. @type uMsg: int @param uMsg: Message code. @param wParam: The type and meaning of this parameter depends on the message. @param lParam: The type and meaning of this parameter depends on the message. @rai...
Below is the the instruction that describes the task: ### Input: Post a low-level window message asyncronically. @type uMsg: int @param uMsg: Message code. @param wParam: The type and meaning of this parameter depends on the message. @param lParam: The typ...
async def set_version(self, tp, params, version=None, elem=None): """ Stores version to the stream if not stored yet :param tp: :param params: :param version: :param elem: :return: """ self.registry.set_tr(None) tw = TypeWrapper(tp, params...
Stores version to the stream if not stored yet :param tp: :param params: :param version: :param elem: :return:
Below is the the instruction that describes the task: ### Input: Stores version to the stream if not stored yet :param tp: :param params: :param version: :param elem: :return: ### Response: async def set_version(self, tp, params, version=None, elem=None): """ ...
def proximal_step(self, gradf=None): """Compute proximal update (gradient descent + constraint). Variables are mapped back and forth between input and frequency domains. """ if gradf is None: gradf = self.eval_grad() self.Vf[:] = self.Yf - (1. / self.L) * gr...
Compute proximal update (gradient descent + constraint). Variables are mapped back and forth between input and frequency domains.
Below is the the instruction that describes the task: ### Input: Compute proximal update (gradient descent + constraint). Variables are mapped back and forth between input and frequency domains. ### Response: def proximal_step(self, gradf=None): """Compute proximal update (gradient descent ...
def __get_table_limits(): """Here we simply take a count of each of the database tables so we know our upper limits for our random number calls then return a dictionary of them to the calling function...""" table_counts = { 'max_adjectives': None, 'max_names': None, 'max_nouns'...
Here we simply take a count of each of the database tables so we know our upper limits for our random number calls then return a dictionary of them to the calling function...
Below is the the instruction that describes the task: ### Input: Here we simply take a count of each of the database tables so we know our upper limits for our random number calls then return a dictionary of them to the calling function... ### Response: def __get_table_limits(): """Here we simply take...
def get_param_map(word, required_keys=None): """ get the optional arguments on a line Example ------- >>> iline = 0 >>> word = 'elset,instance=dummy2,generate' >>> params = get_param_map(iline, word, required_keys=['instance']) params = { 'elset' : None, 'instance' : 'du...
get the optional arguments on a line Example ------- >>> iline = 0 >>> word = 'elset,instance=dummy2,generate' >>> params = get_param_map(iline, word, required_keys=['instance']) params = { 'elset' : None, 'instance' : 'dummy2, 'generate' : None, }
Below is the the instruction that describes the task: ### Input: get the optional arguments on a line Example ------- >>> iline = 0 >>> word = 'elset,instance=dummy2,generate' >>> params = get_param_map(iline, word, required_keys=['instance']) params = { 'elset' : None, 'ins...
def process_extra_vars(extra_vars_list, force_json=True): """Returns a string that is valid JSON or YAML and contains all the variables in every extra_vars_opt inside of extra_vars_list. Args: parse_kv (bool): whether to allow key=value syntax. force_json (bool): if True, always output json. ...
Returns a string that is valid JSON or YAML and contains all the variables in every extra_vars_opt inside of extra_vars_list. Args: parse_kv (bool): whether to allow key=value syntax. force_json (bool): if True, always output json.
Below is the the instruction that describes the task: ### Input: Returns a string that is valid JSON or YAML and contains all the variables in every extra_vars_opt inside of extra_vars_list. Args: parse_kv (bool): whether to allow key=value syntax. force_json (bool): if True, always output js...
def get_pystache_parsed(mustache_file): """Return a ParsedTemplate instance based on the contents of $mustache_file.""" with open(mustache_file, 'r') as file_: parsed = pystache.parse(file_.read()) return parsed
Return a ParsedTemplate instance based on the contents of $mustache_file.
Below is the the instruction that describes the task: ### Input: Return a ParsedTemplate instance based on the contents of $mustache_file. ### Response: def get_pystache_parsed(mustache_file): """Return a ParsedTemplate instance based on the contents of $mustache_file.""" with open(mustache_file, '...
def preprocess_user_variables(userinput): """ <Purpose> Command parser for user variables. Takes the raw userinput and replaces each user variable with its set value. <Arguments> userinput: A raw user string <Side Effects> Each user variable will be replaced by the value that it was previously ...
<Purpose> Command parser for user variables. Takes the raw userinput and replaces each user variable with its set value. <Arguments> userinput: A raw user string <Side Effects> Each user variable will be replaced by the value that it was previously set to. <Exceptions> UserError: User typ...
Below is the the instruction that describes the task: ### Input: <Purpose> Command parser for user variables. Takes the raw userinput and replaces each user variable with its set value. <Arguments> userinput: A raw user string <Side Effects> Each user variable will be replaced by the value that...
def publish(self, message): """ If not stopping, publish a message to RabbitMQ. :param str message: The fully encoded message to publish """ if self._stopping: return self._logger.info("publishing\t%s" % message) properties = pika.BasicProperties(cont...
If not stopping, publish a message to RabbitMQ. :param str message: The fully encoded message to publish
Below is the the instruction that describes the task: ### Input: If not stopping, publish a message to RabbitMQ. :param str message: The fully encoded message to publish ### Response: def publish(self, message): """ If not stopping, publish a message to RabbitMQ. :param str messag...
def SelectComponent(ds, idxs): """ Select / reorder components from datapoints. Args: ds (DataFlow): input DataFlow. idxs (list[int]): a list of component indices. Example: .. code-block:: none original df produces: [c1, c2, c3] idxs: [2,1] this df: [c3, c...
Select / reorder components from datapoints. Args: ds (DataFlow): input DataFlow. idxs (list[int]): a list of component indices. Example: .. code-block:: none original df produces: [c1, c2, c3] idxs: [2,1] this df: [c3, c2]
Below is the the instruction that describes the task: ### Input: Select / reorder components from datapoints. Args: ds (DataFlow): input DataFlow. idxs (list[int]): a list of component indices. Example: .. code-block:: none original df produces: [c1, c2, c3] idxs: [2,...
def of(cls, *documents: BioCDocument): """ Returns a collection documents """ if len(documents) <= 0: raise ValueError("There has to be at least one document.") c = BioCCollection() for document in documents: if document is None: ra...
Returns a collection documents
Below is the the instruction that describes the task: ### Input: Returns a collection documents ### Response: def of(cls, *documents: BioCDocument): """ Returns a collection documents """ if len(documents) <= 0: raise ValueError("There has to be at least one document.") ...
def update_widget_attrs(self, bound_field, attrs): """ Update the dictionary of attributes used while rendering the input widget """ bound_field.form.update_widget_attrs(bound_field, attrs) widget_classes = self.widget.attrs.get('class', None) if widget_classes: ...
Update the dictionary of attributes used while rendering the input widget
Below is the the instruction that describes the task: ### Input: Update the dictionary of attributes used while rendering the input widget ### Response: def update_widget_attrs(self, bound_field, attrs): """ Update the dictionary of attributes used while rendering the input widget """ ...
def debug_line_out(self, p0: Union[Unit, Point2, Point3], p1: Union[Unit, Point2, Point3], color=None): """ Draws a line from p0 to p1. Don't forget to add 'await self._client.send_debug'. """ self._debug_lines.append( debug_pb.DebugLine( line=debug_pb.Line(p0=self.to_debug_p...
Draws a line from p0 to p1. Don't forget to add 'await self._client.send_debug'.
Below is the the instruction that describes the task: ### Input: Draws a line from p0 to p1. Don't forget to add 'await self._client.send_debug'. ### Response: def debug_line_out(self, p0: Union[Unit, Point2, Point3], p1: Union[Unit, Point2, Point3], color=None): """ Draws a line from p0 to p1. Don't forge...
def _setting(self, key, default): """Return the setting, checking config, then the appropriate environment variable, falling back to the default, caching the results. :param str key: The key to get :param any default: The default value if not set :return: str ""...
Return the setting, checking config, then the appropriate environment variable, falling back to the default, caching the results. :param str key: The key to get :param any default: The default value if not set :return: str
Below is the the instruction that describes the task: ### Input: Return the setting, checking config, then the appropriate environment variable, falling back to the default, caching the results. :param str key: The key to get :param any default: The default value if not set ...
def random_dag(nodes, edges): """Generate a random Directed Acyclic Graph (DAG) with a given number of nodes and edges.""" G = nx.DiGraph() for i in range(nodes): G.add_node(i) while edges > 0: a = randint(0,nodes-1) b=a while b==a: b = randint(0,nodes-1) ...
Generate a random Directed Acyclic Graph (DAG) with a given number of nodes and edges.
Below is the the instruction that describes the task: ### Input: Generate a random Directed Acyclic Graph (DAG) with a given number of nodes and edges. ### Response: def random_dag(nodes, edges): """Generate a random Directed Acyclic Graph (DAG) with a given number of nodes and edges.""" G = nx.DiGraph() ...
def download_badge(test_stats, # type: TestStats dest_folder='reports/junit' # type: str ): """ Downloads the badge corresponding to the provided success percentage, from https://img.shields.io. :param test_stats: :param dest_folder: :return: ...
Downloads the badge corresponding to the provided success percentage, from https://img.shields.io. :param test_stats: :param dest_folder: :return:
Below is the the instruction that describes the task: ### Input: Downloads the badge corresponding to the provided success percentage, from https://img.shields.io. :param test_stats: :param dest_folder: :return: ### Response: def download_badge(test_stats, # type: TestStats ...
def add_default_sequences(project): """Add or create the default sequences for the given project :param project: the project that needs default sequences :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ # create sequences for project seqs = [...
Add or create the default sequences for the given project :param project: the project that needs default sequences :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None
Below is the the instruction that describes the task: ### Input: Add or create the default sequences for the given project :param project: the project that needs default sequences :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None ### Response: def add_defaul...
def regtuple_to_numeric(items, qregs): """Takes (QuantumRegister, int) tuples and converts them into an integer array. Args: items (list): List of tuples of (QuantumRegister, int) to convert. qregs (dict): List of )QuantumRegister, int) tuples. Returns: nda...
Takes (QuantumRegister, int) tuples and converts them into an integer array. Args: items (list): List of tuples of (QuantumRegister, int) to convert. qregs (dict): List of )QuantumRegister, int) tuples. Returns: ndarray: Array of integers.
Below is the the instruction that describes the task: ### Input: Takes (QuantumRegister, int) tuples and converts them into an integer array. Args: items (list): List of tuples of (QuantumRegister, int) to convert. qregs (dict): List of )QuantumRegister, int) tuples. ...
def register(self, pattern, view=None): '''Allow decorator-style construction of URL pattern lists.''' if view is None: return partial(self.register, pattern) self.patterns.append(self._make_url((pattern, view))) return view
Allow decorator-style construction of URL pattern lists.
Below is the the instruction that describes the task: ### Input: Allow decorator-style construction of URL pattern lists. ### Response: def register(self, pattern, view=None): '''Allow decorator-style construction of URL pattern lists.''' if view is None: return partial(self.register, p...
def _extend_str(class_node, rvalue): """function to extend builtin str/unicode class""" code = dedent( """ class whatever(object): def join(self, iterable): return {rvalue} def replace(self, old, new, count=None): return {rvalue} def format(self, *args...
function to extend builtin str/unicode class
Below is the the instruction that describes the task: ### Input: function to extend builtin str/unicode class ### Response: def _extend_str(class_node, rvalue): """function to extend builtin str/unicode class""" code = dedent( """ class whatever(object): def join(self, iterable): ...
def status(self): """ Get the container's current status from Docker. If the container does not exist (before creation and after removal), the status is ``None``. """ if not self.created: return None self.inner().reload() return self.inner().s...
Get the container's current status from Docker. If the container does not exist (before creation and after removal), the status is ``None``.
Below is the the instruction that describes the task: ### Input: Get the container's current status from Docker. If the container does not exist (before creation and after removal), the status is ``None``. ### Response: def status(self): """ Get the container's current status from ...
def get_raw_output(self, tile, _baselevel_readonly=False): """ Get output raw data. This function won't work with multiprocessing, as it uses the ``threading.Lock()`` class. Parameters ---------- tile : tuple, Tile or BufferedTile If a tile index is ...
Get output raw data. This function won't work with multiprocessing, as it uses the ``threading.Lock()`` class. Parameters ---------- tile : tuple, Tile or BufferedTile If a tile index is given, a tile from the output pyramid will be assumed. Tile cannot ...
Below is the the instruction that describes the task: ### Input: Get output raw data. This function won't work with multiprocessing, as it uses the ``threading.Lock()`` class. Parameters ---------- tile : tuple, Tile or BufferedTile If a tile index is given, a t...
def encode(self, lname, fname='.', omit_fname=False): """Return Davidson's Consonant Code. Parameters ---------- lname : str Last name (or word) to be encoded fname : str First name (optional), of which the first character is included in the c...
Return Davidson's Consonant Code. Parameters ---------- lname : str Last name (or word) to be encoded fname : str First name (optional), of which the first character is included in the code. omit_fname : bool Set to True to complet...
Below is the the instruction that describes the task: ### Input: Return Davidson's Consonant Code. Parameters ---------- lname : str Last name (or word) to be encoded fname : str First name (optional), of which the first character is included in t...
def screenshot( width=None, height=None, format="png", fig=None, timeout_seconds=10, output_widget=None, headless=False, devmode=False, ): """Save the figure to a PIL.Image object. :param int width: the width of the image in pixels :param int height: the height of the image ...
Save the figure to a PIL.Image object. :param int width: the width of the image in pixels :param int height: the height of the image in pixels :param format: format of output data (png, jpeg or svg) :type fig: ipyvolume.widgets.Figure or None :param fig: if None use the current figure :type tim...
Below is the the instruction that describes the task: ### Input: Save the figure to a PIL.Image object. :param int width: the width of the image in pixels :param int height: the height of the image in pixels :param format: format of output data (png, jpeg or svg) :type fig: ipyvolume.widgets.Figure...
def equilateral(cls, origin=None, side=1): ''' :origin: optional Point :side: optional float describing triangle side length :return: Triangle initialized with points comprising a equilateral triangle. XXX equilateral triangle definition ''' o =...
:origin: optional Point :side: optional float describing triangle side length :return: Triangle initialized with points comprising a equilateral triangle. XXX equilateral triangle definition
Below is the the instruction that describes the task: ### Input: :origin: optional Point :side: optional float describing triangle side length :return: Triangle initialized with points comprising a equilateral triangle. XXX equilateral triangle definition ### Response: def...
def _get_hit_nearest_ref_start(self, hits): '''Returns the hit nearest to the start of the ref sequence from the input list of hits''' nearest_to_start = hits[0] for hit in hits[1:]: if hit.ref_coords().start < nearest_to_start.ref_coords().start: nearest_to_start = h...
Returns the hit nearest to the start of the ref sequence from the input list of hits
Below is the the instruction that describes the task: ### Input: Returns the hit nearest to the start of the ref sequence from the input list of hits ### Response: def _get_hit_nearest_ref_start(self, hits): '''Returns the hit nearest to the start of the ref sequence from the input list of hits''' ...
def get_payload(self): """Return Payload.""" ret = self._software_version ret += bytes([self.hardware_version, self.product_group, self.product_type]) return ret
Return Payload.
Below is the the instruction that describes the task: ### Input: Return Payload. ### Response: def get_payload(self): """Return Payload.""" ret = self._software_version ret += bytes([self.hardware_version, self.product_group, self.product_type]) return ret
def _check_html_response(self, response): """ Checks if the API Key is valid and if the request returned a 200 status (ok) """ error1 = "Access to this form requires a valid API key. For more info see: http://www.clublog.org/need_api.php" error2 = "Invalid or missing API Key...
Checks if the API Key is valid and if the request returned a 200 status (ok)
Below is the the instruction that describes the task: ### Input: Checks if the API Key is valid and if the request returned a 200 status (ok) ### Response: def _check_html_response(self, response): """ Checks if the API Key is valid and if the request returned a 200 status (ok) """ ...
def copy_everything_except_instructions(self): """ Copy all the members that live on a Program object. :return: a new Program """ new_prog = Program() new_prog._defined_gates = self._defined_gates.copy() if self.native_quil_metadata is not None: new_p...
Copy all the members that live on a Program object. :return: a new Program
Below is the the instruction that describes the task: ### Input: Copy all the members that live on a Program object. :return: a new Program ### Response: def copy_everything_except_instructions(self): """ Copy all the members that live on a Program object. :return: a new Program ...
def feed_key(self, key_press): """ Feed a key press to the CommandLineInterface. """ assert isinstance(key_press, KeyPress) cli = self._active_cli # Feed the key and redraw. # (When the CLI is in 'done' state, it should return to the event loop # as soon ...
Feed a key press to the CommandLineInterface.
Below is the the instruction that describes the task: ### Input: Feed a key press to the CommandLineInterface. ### Response: def feed_key(self, key_press): """ Feed a key press to the CommandLineInterface. """ assert isinstance(key_press, KeyPress) cli = self._active_cli ...
def _parse_args(args, cls): """ Parse a docopt dictionary of arguments """ d = _create_djset(args, cls) key_value_pair = args.get('<key>=<value>') key = args.get('<key>') func = None if args.get('add') and key_value_pair: fargs = tuple(args.get('<key>=<value>').split('=')) ...
Parse a docopt dictionary of arguments
Below is the the instruction that describes the task: ### Input: Parse a docopt dictionary of arguments ### Response: def _parse_args(args, cls): """ Parse a docopt dictionary of arguments """ d = _create_djset(args, cls) key_value_pair = args.get('<key>=<value>') key = args.get('<key>') ...
def login(): """Does the login via OpenID. Has to call into `oid.try_login` to start the OpenID machinery. """ # if we are already logged in, go back to were we came from if g.user is not None: return redirect(oid.get_next_url()) if request.method == 'POST': openid = request.for...
Does the login via OpenID. Has to call into `oid.try_login` to start the OpenID machinery.
Below is the the instruction that describes the task: ### Input: Does the login via OpenID. Has to call into `oid.try_login` to start the OpenID machinery. ### Response: def login(): """Does the login via OpenID. Has to call into `oid.try_login` to start the OpenID machinery. """ # if we are ...
def on_add(self, item): """Convert to pseuso acces""" super(Tels, self).on_add(list_views.PseudoAccesCategorie(item))
Convert to pseuso acces
Below is the the instruction that describes the task: ### Input: Convert to pseuso acces ### Response: def on_add(self, item): """Convert to pseuso acces""" super(Tels, self).on_add(list_views.PseudoAccesCategorie(item))
def _from_dict(cls, _dict): """Initialize a SpeechModels object from a json dictionary.""" args = {} if 'models' in _dict: args['models'] = [ SpeechModel._from_dict(x) for x in (_dict.get('models')) ] else: raise ValueError( ...
Initialize a SpeechModels object from a json dictionary.
Below is the the instruction that describes the task: ### Input: Initialize a SpeechModels object from a json dictionary. ### Response: def _from_dict(cls, _dict): """Initialize a SpeechModels object from a json dictionary.""" args = {} if 'models' in _dict: args['models'] = [ ...
def change_password_view(self): """ Prompt for old password and new password and change the user's password.""" # Initialize form form = self.ChangePasswordFormClass(request.form) # Process valid POST if request.method == 'POST' and form.validate(): # Hash password ...
Prompt for old password and new password and change the user's password.
Below is the the instruction that describes the task: ### Input: Prompt for old password and new password and change the user's password. ### Response: def change_password_view(self): """ Prompt for old password and new password and change the user's password.""" # Initialize form form = s...
def l3_tenant_id(cls): """Returns id of tenant owning hosting device resources.""" if cls._l3_tenant_uuid is None: if hasattr(cfg.CONF.keystone_authtoken, 'project_domain_id'): # TODO(sridar): hack for now to determing if keystone v3 # API is to be used. ...
Returns id of tenant owning hosting device resources.
Below is the the instruction that describes the task: ### Input: Returns id of tenant owning hosting device resources. ### Response: def l3_tenant_id(cls): """Returns id of tenant owning hosting device resources.""" if cls._l3_tenant_uuid is None: if hasattr(cfg.CONF.keystone_authtoken,...
def full_neg_loglik(self, beta): """ Creates the negative log marginal likelihood of the model Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- The negative log margi...
Creates the negative log marginal likelihood of the model Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- The negative log marginal logliklihood of the model
Below is the the instruction that describes the task: ### Input: Creates the negative log marginal likelihood of the model Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- ...
def ports_as_list(port_str): """ Parses a ports string into two list of individual tcp and udp ports. @input string containing a port list e.g. T:1,2,3,5-8 U:22,80,600-1024 @return two list of sorted integers, for tcp and udp ports respectively. """ if not port_str: LOGGER.info("In...
Parses a ports string into two list of individual tcp and udp ports. @input string containing a port list e.g. T:1,2,3,5-8 U:22,80,600-1024 @return two list of sorted integers, for tcp and udp ports respectively.
Below is the the instruction that describes the task: ### Input: Parses a ports string into two list of individual tcp and udp ports. @input string containing a port list e.g. T:1,2,3,5-8 U:22,80,600-1024 @return two list of sorted integers, for tcp and udp ports respectively. ### Response: def ports...
def get(self, queue_get): """ to get states from multiprocessing.queue """ if isinstance(queue_get, (tuple, list)): self.result.extend(queue_get)
to get states from multiprocessing.queue
Below is the the instruction that describes the task: ### Input: to get states from multiprocessing.queue ### Response: def get(self, queue_get): """ to get states from multiprocessing.queue """ if isinstance(queue_get, (tuple, list)): self.result.extend(queue_get)