code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def select_edges_by_attribute(docgraph, attribute=None, value=None, data=False): """ get all edges with the given edge type and layer. Parameters ---------- docgraph : DiscourseDocumentGraph document graph from which the nodes will be extracted attribute : str or None Name of th...
get all edges with the given edge type and layer. Parameters ---------- docgraph : DiscourseDocumentGraph document graph from which the nodes will be extracted attribute : str or None Name of the node attribute that all nodes must posess. If None, returns all nodes. value : ...
Below is the the instruction that describes the task: ### Input: get all edges with the given edge type and layer. Parameters ---------- docgraph : DiscourseDocumentGraph document graph from which the nodes will be extracted attribute : str or None Name of the node attribute that al...
def freeze(self, dest_dir): """Freezes every resource within a context""" for resource in self.resources(): if resource.present: resource.freeze(dest_dir)
Freezes every resource within a context
Below is the the instruction that describes the task: ### Input: Freezes every resource within a context ### Response: def freeze(self, dest_dir): """Freezes every resource within a context""" for resource in self.resources(): if resource.present: resource.freeze(dest_di...
def run(self, dag): """ If `dag` is mapped to `coupling_map`, the property `is_swap_mapped` is set to True (or to False otherwise). Args: dag (DAGCircuit): DAG to map. """ if self.layout is None: if self.property_set["layout"]: sel...
If `dag` is mapped to `coupling_map`, the property `is_swap_mapped` is set to True (or to False otherwise). Args: dag (DAGCircuit): DAG to map.
Below is the the instruction that describes the task: ### Input: If `dag` is mapped to `coupling_map`, the property `is_swap_mapped` is set to True (or to False otherwise). Args: dag (DAGCircuit): DAG to map. ### Response: def run(self, dag): """ If `dag` is mapped to `...
def text(self, x, y, text, attr=None): u'''Write text at the given position.''' if attr is None: attr = self.attr pos = self.fixcoord(x, y) n = DWORD(0) self.WriteConsoleOutputCharacterW(self.hout, text, len(text), p...
u'''Write text at the given position.
Below is the the instruction that describes the task: ### Input: u'''Write text at the given position. ### Response: def text(self, x, y, text, attr=None): u'''Write text at the given position.''' if attr is None: attr = self.attr pos = self.fixcoord(x, y) n = DWO...
def read(self, path, encoding=None): """ Read the template at the given path, and return it as a unicode string. """ b = common.read(path) if encoding is None: encoding = self.file_encoding return self.unicode(b, encoding)
Read the template at the given path, and return it as a unicode string.
Below is the the instruction that describes the task: ### Input: Read the template at the given path, and return it as a unicode string. ### Response: def read(self, path, encoding=None): """ Read the template at the given path, and return it as a unicode string. """ b = common.rea...
def configure_modsecurity(self): """ Installs the mod-security Apache module. https://www.modsecurity.org """ r = self.local_renderer if r.env.modsecurity_enabled and not self.last_manifest.modsecurity_enabled: self.install_packages() # Write mo...
Installs the mod-security Apache module. https://www.modsecurity.org
Below is the the instruction that describes the task: ### Input: Installs the mod-security Apache module. https://www.modsecurity.org ### Response: def configure_modsecurity(self): """ Installs the mod-security Apache module. https://www.modsecurity.org """ r = sel...
def render(self, text, auth=None): """ Renders the specified markdown content and embedded styles. """ if markdown is None: import markdown if UrlizeExtension is None: from .mdx_urlize import UrlizeExtension return markdown.markdown(text, extension...
Renders the specified markdown content and embedded styles.
Below is the the instruction that describes the task: ### Input: Renders the specified markdown content and embedded styles. ### Response: def render(self, text, auth=None): """ Renders the specified markdown content and embedded styles. """ if markdown is None: import m...
def OnMouseWheel(self, event): """Event handler for mouse wheel actions Invokes zoom when mouse when Ctrl is also pressed """ if event.ControlDown(): if event.WheelRotation > 0: post_command_event(self.grid, self.grid.ZoomInMsg) else: ...
Event handler for mouse wheel actions Invokes zoom when mouse when Ctrl is also pressed
Below is the the instruction that describes the task: ### Input: Event handler for mouse wheel actions Invokes zoom when mouse when Ctrl is also pressed ### Response: def OnMouseWheel(self, event): """Event handler for mouse wheel actions Invokes zoom when mouse when Ctrl is also pressed ...
def pool_memcached_connections(func): """Function decorator to pool memcached connections. Use this to wrap functions that might make multiple calls to memcached. This will cause a single memcached client to be shared for all connections. """ if isgeneratorfunction(func): def wrapper(*nargs...
Function decorator to pool memcached connections. Use this to wrap functions that might make multiple calls to memcached. This will cause a single memcached client to be shared for all connections.
Below is the the instruction that describes the task: ### Input: Function decorator to pool memcached connections. Use this to wrap functions that might make multiple calls to memcached. This will cause a single memcached client to be shared for all connections. ### Response: def pool_memcached_connection...
def lime_tabular_regression_1000(model, data): """ LIME Tabular 1000 """ return lambda X: other.LimeTabularExplainer(model.predict, data, mode="regression").attributions(X, nsamples=1000)
LIME Tabular 1000
Below is the the instruction that describes the task: ### Input: LIME Tabular 1000 ### Response: def lime_tabular_regression_1000(model, data): """ LIME Tabular 1000 """ return lambda X: other.LimeTabularExplainer(model.predict, data, mode="regression").attributions(X, nsamples=1000)
def contiguous(self, other: "Interval") -> bool: """ Does this interval overlap or touch the other? """ return not(self.end < other.start or self.start > other.end)
Does this interval overlap or touch the other?
Below is the the instruction that describes the task: ### Input: Does this interval overlap or touch the other? ### Response: def contiguous(self, other: "Interval") -> bool: """ Does this interval overlap or touch the other? """ return not(self.end < other.start or self.start > oth...
def f_load_items(self, iterator, *args, **kwargs): """Loads parameters and results specified in `iterator`. You can directly list the Parameter objects or just their names. If names are given the `~pypet.naturalnaming.NNGroupNode.f_get` method is applied to find the parameters or resul...
Loads parameters and results specified in `iterator`. You can directly list the Parameter objects or just their names. If names are given the `~pypet.naturalnaming.NNGroupNode.f_get` method is applied to find the parameters or results in the trajectory. Accordingly, the parameters and results ...
Below is the the instruction that describes the task: ### Input: Loads parameters and results specified in `iterator`. You can directly list the Parameter objects or just their names. If names are given the `~pypet.naturalnaming.NNGroupNode.f_get` method is applied to find the parameters o...
def structure_attrs_fromdict(self, obj, cl): # type: (Mapping[str, Any], Type[T]) -> T """Instantiate an attrs class from a mapping (dict).""" # For public use. conv_obj = {} # Start with a fresh dict, to ignore extra keys. dispatch = self._structure_func.dispatch for a ...
Instantiate an attrs class from a mapping (dict).
Below is the the instruction that describes the task: ### Input: Instantiate an attrs class from a mapping (dict). ### Response: def structure_attrs_fromdict(self, obj, cl): # type: (Mapping[str, Any], Type[T]) -> T """Instantiate an attrs class from a mapping (dict).""" # For public use. ...
def client(addr): """Return a SocketTalk client.""" success = False while not success: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.connect(addr) ...
Return a SocketTalk client.
Below is the the instruction that describes the task: ### Input: Return a SocketTalk client. ### Response: def client(addr): """Return a SocketTalk client.""" success = False while not success: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
def build_genome_alignment_from_directory(d_name, ref_spec, extensions=None, index_exts=None, fail_no_index=False): """ build a genome aligment by loading all files in a directory. Fiel without indexes are loaded immediately; tho...
build a genome aligment by loading all files in a directory. Fiel without indexes are loaded immediately; those with indexes are loaded on-demand. Not recursive (i.e. subdirectories are not parsed). :param d_name: directory to load from. :param ref_spec: which species in the alignemnt files is the...
Below is the the instruction that describes the task: ### Input: build a genome aligment by loading all files in a directory. Fiel without indexes are loaded immediately; those with indexes are loaded on-demand. Not recursive (i.e. subdirectories are not parsed). :param d_name: directory to load from...
def session(self, bundle_id=None, arguments=None, environment=None): """ Args: - bundle_id (str): the app bundle id - arguments (list): ['-u', 'https://www.google.com/ncr'] - enviroment (dict): {"KEY": "VAL"} WDA Return json like { "value...
Args: - bundle_id (str): the app bundle id - arguments (list): ['-u', 'https://www.google.com/ncr'] - enviroment (dict): {"KEY": "VAL"} WDA Return json like { "value": { "sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814", ...
Below is the the instruction that describes the task: ### Input: Args: - bundle_id (str): the app bundle id - arguments (list): ['-u', 'https://www.google.com/ncr'] - enviroment (dict): {"KEY": "VAL"} WDA Return json like { "value": { ...
def is_simplified(s): """Check if a string's Chinese characters are Simplified. This is equivalent to: >>> identify('foo') in (SIMPLIFIED, BOTH) """ chinese = _get_hanzi(s) if not chinese: return False elif chinese.issubset(_SHARED_CHARACTERS): return True elif chin...
Check if a string's Chinese characters are Simplified. This is equivalent to: >>> identify('foo') in (SIMPLIFIED, BOTH)
Below is the the instruction that describes the task: ### Input: Check if a string's Chinese characters are Simplified. This is equivalent to: >>> identify('foo') in (SIMPLIFIED, BOTH) ### Response: def is_simplified(s): """Check if a string's Chinese characters are Simplified. This is equiva...
def create_connection_context(self): '''Creates and seriazlies a IpcConnectionContextProto (not delimited)''' context = IpcConnectionContextProto() context.userInfo.effectiveUser = self.effective_user context.protocol = "org.apache.hadoop.hdfs.protocol.ClientProtocol" s_context ...
Creates and seriazlies a IpcConnectionContextProto (not delimited)
Below is the the instruction that describes the task: ### Input: Creates and seriazlies a IpcConnectionContextProto (not delimited) ### Response: def create_connection_context(self): '''Creates and seriazlies a IpcConnectionContextProto (not delimited)''' context = IpcConnectionContextProto() ...
def _api_query(self, protection=None, path_dict=None, options=None): """ Queries Bittrex :param request_url: fully-formed URL to request :type options: dict :return: JSON response from Bittrex :rtype : dict """ if not options: options = {} ...
Queries Bittrex :param request_url: fully-formed URL to request :type options: dict :return: JSON response from Bittrex :rtype : dict
Below is the the instruction that describes the task: ### Input: Queries Bittrex :param request_url: fully-formed URL to request :type options: dict :return: JSON response from Bittrex :rtype : dict ### Response: def _api_query(self, protection=None, path_dict=None, options=None): ...
def _get_penalty_function(nmr_parameters, constraints_func=None): """Get a function to compute the penalty term for the boundary conditions. This is meant to be used in the evaluation function of the optimization routines. Args: nmr_parameters (int): the number of parameters in the model c...
Get a function to compute the penalty term for the boundary conditions. This is meant to be used in the evaluation function of the optimization routines. Args: nmr_parameters (int): the number of parameters in the model constraints_func (mot.optimize.base.ConstraintFunction): function to compu...
Below is the the instruction that describes the task: ### Input: Get a function to compute the penalty term for the boundary conditions. This is meant to be used in the evaluation function of the optimization routines. Args: nmr_parameters (int): the number of parameters in the model const...
def manifestation_model_factory(*, validator=validators.is_manifestation_model, ld_type='CreativeWork', **kwargs): """Generate a Manifestation model. Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and ``ld_context`` as keyword arguments. """ return _mod...
Generate a Manifestation model. Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and ``ld_context`` as keyword arguments.
Below is the the instruction that describes the task: ### Input: Generate a Manifestation model. Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and ``ld_context`` as keyword arguments. ### Response: def manifestation_model_factory(*, validator=validators.is_manifestation_model, ...
def _get_sql_server_ver(self): """ Returns the version of the SQL Server in use: """ if self._ss_ver is not None: return self._ss_ver cur = self.connection.cursor() ver_code = None if not self.is_db2 and not self.is_openedge: cur.execute("S...
Returns the version of the SQL Server in use:
Below is the the instruction that describes the task: ### Input: Returns the version of the SQL Server in use: ### Response: def _get_sql_server_ver(self): """ Returns the version of the SQL Server in use: """ if self._ss_ver is not None: return self._ss_ver cur ...
def noninteractive_changeset_update(self, fqn, template, old_parameters, parameters, stack_policy, tags, **kwargs): """Update a Cloudformation stack using a change set. This is required for stacks with a defined Transform (...
Update a Cloudformation stack using a change set. This is required for stacks with a defined Transform (i.e. SAM), as the default update_stack API cannot be used with them. Args: fqn (str): The fully qualified name of the Cloudformation stack. template (:class:`stacker....
Below is the the instruction that describes the task: ### Input: Update a Cloudformation stack using a change set. This is required for stacks with a defined Transform (i.e. SAM), as the default update_stack API cannot be used with them. Args: fqn (str): The fully qualified nam...
def parse_image_json(text): """ parses response output of AWS describe commands and returns the first (and only) item in array :param text: describe output :return: image json """ image_details = json.loads(text) if image_details.get('Images') is not None: try: image_deta...
parses response output of AWS describe commands and returns the first (and only) item in array :param text: describe output :return: image json
Below is the the instruction that describes the task: ### Input: parses response output of AWS describe commands and returns the first (and only) item in array :param text: describe output :return: image json ### Response: def parse_image_json(text): """ parses response output of AWS describe comma...
def orientation(p1, p2, p3): """ Finds orientation of three points p1, p2, p3. The function returns following values 0 --> p1, p2 and p3 are collinear 1 --> Clockwise 2 --> Counterclockwise :param p1: tuple representing two dimensional point :param p2: tuple representing two dimensional ...
Finds orientation of three points p1, p2, p3. The function returns following values 0 --> p1, p2 and p3 are collinear 1 --> Clockwise 2 --> Counterclockwise :param p1: tuple representing two dimensional point :param p2: tuple representing two dimensional point :param p3: tuple representing t...
Below is the the instruction that describes the task: ### Input: Finds orientation of three points p1, p2, p3. The function returns following values 0 --> p1, p2 and p3 are collinear 1 --> Clockwise 2 --> Counterclockwise :param p1: tuple representing two dimensional point :param p2: tuple r...
def assign_shifts_view(request, semester): """ View all members' preferences. This view also includes forms to create an entire semester's worth of weekly workshifts. """ page_name = "Assign Shifts" auto_assign_shifts_form = None random_assign_instances_form = None clear_assign_form = N...
View all members' preferences. This view also includes forms to create an entire semester's worth of weekly workshifts.
Below is the the instruction that describes the task: ### Input: View all members' preferences. This view also includes forms to create an entire semester's worth of weekly workshifts. ### Response: def assign_shifts_view(request, semester): """ View all members' preferences. This view also includes fo...
def from_veto_definer_file(cls, fp, start=None, end=None, ifo=None, format='ligolw'): """Read a `DataQualityDict` from a LIGO_LW XML VetoDefinerTable. Parameters ---------- fp : `str` path of veto definer file to read start : `~gwpy.tim...
Read a `DataQualityDict` from a LIGO_LW XML VetoDefinerTable. Parameters ---------- fp : `str` path of veto definer file to read start : `~gwpy.time.LIGOTimeGPS`, `int`, optional GPS start time at which to restrict returned flags end : `~gwpy.time.LIGOTim...
Below is the the instruction that describes the task: ### Input: Read a `DataQualityDict` from a LIGO_LW XML VetoDefinerTable. Parameters ---------- fp : `str` path of veto definer file to read start : `~gwpy.time.LIGOTimeGPS`, `int`, optional GPS start time ...
def handle(self): "The actual service to which the user has connected." if not self.authentication_ok(): return if self.DOECHO: self.writeline(self.WELCOME) self.session_start() while self.RUNSHELL: read_line = self.readline(prompt=self.PROMPT)...
The actual service to which the user has connected.
Below is the the instruction that describes the task: ### Input: The actual service to which the user has connected. ### Response: def handle(self): "The actual service to which the user has connected." if not self.authentication_ok(): return if self.DOECHO: self.wri...
def solveConsRepAgentMarkov(solution_next,MrkvArray,DiscFac,CRRA,IncomeDstn,CapShare,DeprFac,PermGroFac,aXtraGrid): ''' Solve one period of the simple representative agent consumption-saving model. This version supports a discrete Markov process. Parameters ---------- solution_next : ConsumerSo...
Solve one period of the simple representative agent consumption-saving model. This version supports a discrete Markov process. Parameters ---------- solution_next : ConsumerSolution Solution to the next period's problem (i.e. previous iteration). MrkvArray : np.array Markov transiti...
Below is the the instruction that describes the task: ### Input: Solve one period of the simple representative agent consumption-saving model. This version supports a discrete Markov process. Parameters ---------- solution_next : ConsumerSolution Solution to the next period's problem (i.e. ...
def insert_ngram(self, ngram, count): """ Inserts a given n-gram with count into the database. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. count : int The count for the given n-gram. """ query = ...
Inserts a given n-gram with count into the database. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. count : int The count for the given n-gram.
Below is the the instruction that describes the task: ### Input: Inserts a given n-gram with count into the database. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. count : int The count for the given n-gram. ### Response: def...
def _parse_names_set(feature_names): """Helping function of `_parse_feature_names` that parses a set of feature names.""" feature_collection = OrderedDict() for feature_name in feature_names: if isinstance(feature_name, str): feature_collection[feature_name] = .....
Helping function of `_parse_feature_names` that parses a set of feature names.
Below is the the instruction that describes the task: ### Input: Helping function of `_parse_feature_names` that parses a set of feature names. ### Response: def _parse_names_set(feature_names): """Helping function of `_parse_feature_names` that parses a set of feature names.""" feature_collectio...
def load_from_dict(self, data: dict, overwrite: bool=True): """ Loads key/values from dicts or list into the ConfigKey. :param data: The data object to load. This can be a dict, or a list of key/value tuples. :param overwrite: Should the ConfigKey overwrite data a...
Loads key/values from dicts or list into the ConfigKey. :param data: The data object to load. This can be a dict, or a list of key/value tuples. :param overwrite: Should the ConfigKey overwrite data already in it?
Below is the the instruction that describes the task: ### Input: Loads key/values from dicts or list into the ConfigKey. :param data: The data object to load. This can be a dict, or a list of key/value tuples. :param overwrite: Should the ConfigKey overwrite data already in i...
def split_in_tiles(self, hint): """ Split a SiteCollection into a set of tiles (SiteCollection instances). :param hint: hint for how many tiles to generate """ tiles = [] for seq in split_in_blocks(range(len(self)), hint or 1): sc = SiteCollection.__new__(Sit...
Split a SiteCollection into a set of tiles (SiteCollection instances). :param hint: hint for how many tiles to generate
Below is the the instruction that describes the task: ### Input: Split a SiteCollection into a set of tiles (SiteCollection instances). :param hint: hint for how many tiles to generate ### Response: def split_in_tiles(self, hint): """ Split a SiteCollection into a set of tiles (SiteCollect...
def ban_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/bans#create-ban" api_path = "/api/v2/bans" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/chat/bans#create-ban
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/chat/bans#create-ban ### Response: def ban_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/bans#create-ban" api_path = "/api/v2/bans" return self.call...
def find_non_contiguous(all_items): """Find any items that have slots that aren't contiguous""" non_contiguous = [] for item in all_items: if item.slots.count() < 2: # No point in checking continue last_slot = None for slot in item.slots.all().order_by('end_ti...
Find any items that have slots that aren't contiguous
Below is the the instruction that describes the task: ### Input: Find any items that have slots that aren't contiguous ### Response: def find_non_contiguous(all_items): """Find any items that have slots that aren't contiguous""" non_contiguous = [] for item in all_items: if item.slots.count() <...
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_location( # receiver, self.media, disable_notificat...
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
Below is the the instruction that describes the task: ### Input: Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage ### Response: def send(self, sender: PytgbotApiBot): """ Send the message v...
def create_rules(aes, value): """Create a Rules instance for a single aesthetic value. Parameter --------- aes: str The name of the aesthetic value: str or list The value associated with any aesthetic """ if isinstance(value, six.string_types): return Rules(aes) ...
Create a Rules instance for a single aesthetic value. Parameter --------- aes: str The name of the aesthetic value: str or list The value associated with any aesthetic
Below is the the instruction that describes the task: ### Input: Create a Rules instance for a single aesthetic value. Parameter --------- aes: str The name of the aesthetic value: str or list The value associated with any aesthetic ### Response: def create_rules(aes, value): "...
def angsep(lon1, lat1, lon2, lat2): """ Angular separation (deg) between two sky coordinates. Borrowed from astropy (www.astropy.org) Notes ----- The angular separation is calculated using the Vincenty formula [1], which is slighly more complex and computationally expensive than some alt...
Angular separation (deg) between two sky coordinates. Borrowed from astropy (www.astropy.org) Notes ----- The angular separation is calculated using the Vincenty formula [1], which is slighly more complex and computationally expensive than some alternatives, but is stable at at all distances, in...
Below is the the instruction that describes the task: ### Input: Angular separation (deg) between two sky coordinates. Borrowed from astropy (www.astropy.org) Notes ----- The angular separation is calculated using the Vincenty formula [1], which is slighly more complex and computationally expens...
def remove(self, oid): """ Remove a faked Virtual Function resource. This method also updates the 'virtual-function-uris' property in the parent Partition resource, by removing the URI for the faked Virtual Function resource. Parameters: oid (string): ...
Remove a faked Virtual Function resource. This method also updates the 'virtual-function-uris' property in the parent Partition resource, by removing the URI for the faked Virtual Function resource. Parameters: oid (string): The object ID of the faked Virtual Fun...
Below is the the instruction that describes the task: ### Input: Remove a faked Virtual Function resource. This method also updates the 'virtual-function-uris' property in the parent Partition resource, by removing the URI for the faked Virtual Function resource. Parameters: ...
def draw(self, img, pixmapper, bounds): '''draw a polygon on the image''' if self.hidden: return self._pix_points = [] for i in range(len(self.points)-1): if len(self.points[i]) > 2: colour = self.points[i][2] else: colo...
draw a polygon on the image
Below is the the instruction that describes the task: ### Input: draw a polygon on the image ### Response: def draw(self, img, pixmapper, bounds): '''draw a polygon on the image''' if self.hidden: return self._pix_points = [] for i in range(len(self.points)-1): ...
def from_string(cls, string): """ Create a public blob from a ``-cert.pub``-style string. """ fields = string.split(None, 2) if len(fields) < 2: msg = "Not enough fields for public blob: {}" raise ValueError(msg.format(fields)) key_type = fields[0]...
Create a public blob from a ``-cert.pub``-style string.
Below is the the instruction that describes the task: ### Input: Create a public blob from a ``-cert.pub``-style string. ### Response: def from_string(cls, string): """ Create a public blob from a ``-cert.pub``-style string. """ fields = string.split(None, 2) if len(fields) ...
def close_active_window(self): """ Close active window. """ active_split = self._get_active_split() # First remove the active window from its split. index = active_split.index(self.active_window) del active_split[index] # Move focus. if len(activ...
Close active window.
Below is the the instruction that describes the task: ### Input: Close active window. ### Response: def close_active_window(self): """ Close active window. """ active_split = self._get_active_split() # First remove the active window from its split. index = active_sp...
def engine_list(self): """ :returns: Return list of engines supported by GNS3 for the GNS3VM """ download_url = "https://github.com/GNS3/gns3-gui/releases/download/v{version}/GNS3.VM.VMware.Workstation.{version}.zip".format(version=__version__) vmware_informations = { ...
:returns: Return list of engines supported by GNS3 for the GNS3VM
Below is the the instruction that describes the task: ### Input: :returns: Return list of engines supported by GNS3 for the GNS3VM ### Response: def engine_list(self): """ :returns: Return list of engines supported by GNS3 for the GNS3VM """ download_url = "https://github.com/GNS3/...
def iterencode(self, o): """ Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: ...
Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk)
Below is the the instruction that describes the task: ### Input: Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) ### Response: def itere...
def add_entry(self, path_object): """Adds a child FakeFile to this directory. Args: path_object: FakeFile instance to add as a child of this directory. Raises: OSError: if the directory has no write permission (Posix only) OSError: if the file or directory t...
Adds a child FakeFile to this directory. Args: path_object: FakeFile instance to add as a child of this directory. Raises: OSError: if the directory has no write permission (Posix only) OSError: if the file or directory to be added already exists
Below is the the instruction that describes the task: ### Input: Adds a child FakeFile to this directory. Args: path_object: FakeFile instance to add as a child of this directory. Raises: OSError: if the directory has no write permission (Posix only) OSError: if...
def by_youtube_id(cls, youtube_id): """ Look up video by youtube id """ qset = cls.objects.filter( encoded_videos__profile__profile_name='youtube', encoded_videos__url=youtube_id ).prefetch_related('encoded_videos', 'courses') return qset
Look up video by youtube id
Below is the the instruction that describes the task: ### Input: Look up video by youtube id ### Response: def by_youtube_id(cls, youtube_id): """ Look up video by youtube id """ qset = cls.objects.filter( encoded_videos__profile__profile_name='youtube', enco...
def get_rotation_program(pauli_term: PauliTerm) -> Program: """ Generate a rotation program so that the pauli term is diagonal. :param pauli_term: The Pauli term used to generate diagonalizing one-qubit rotations. :return: The rotation program. """ meas_basis_change = Program() for index, g...
Generate a rotation program so that the pauli term is diagonal. :param pauli_term: The Pauli term used to generate diagonalizing one-qubit rotations. :return: The rotation program.
Below is the the instruction that describes the task: ### Input: Generate a rotation program so that the pauli term is diagonal. :param pauli_term: The Pauli term used to generate diagonalizing one-qubit rotations. :return: The rotation program. ### Response: def get_rotation_program(pauli_term: PauliTerm...
def dual_csiszar_function(logu, csiszar_function, name=None): """Calculates the dual Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Csiszar-dual is defined as: ```none f^*(u) = u f(1 / u) ``` where `f` is some other Csiszar-funct...
Calculates the dual Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Csiszar-dual is defined as: ```none f^*(u) = u f(1 / u) ``` where `f` is some other Csiszar-function. For example, the dual of `kl_reverse` is `kl_forward`, i.e....
Below is the the instruction that describes the task: ### Input: Calculates the dual Csiszar-function in log-space. A Csiszar-function is a member of, ```none F = { f:R_+ to R : f convex }. ``` The Csiszar-dual is defined as: ```none f^*(u) = u f(1 / u) ``` where `f` is some other Csiszar-fun...
def safe_concurrent_creation(target_path): """A contextmanager that yields a temporary path and renames it to a final target path when the contextmanager exits. Useful when concurrent processes may attempt to create a file, and it doesn't matter who wins. :param target_path: The final target path to rename th...
A contextmanager that yields a temporary path and renames it to a final target path when the contextmanager exits. Useful when concurrent processes may attempt to create a file, and it doesn't matter who wins. :param target_path: The final target path to rename the temporary path to. :yields: A temporary path...
Below is the the instruction that describes the task: ### Input: A contextmanager that yields a temporary path and renames it to a final target path when the contextmanager exits. Useful when concurrent processes may attempt to create a file, and it doesn't matter who wins. :param target_path: The final tar...
def export(fn): """ Export decorator Please refer to the following SO article for details: https://stackoverflow.com/a/35710527 """ mod = sys.modules[fn.__module__] if hasattr(mod, '__all__'): mod.__all__.append(fn.__name__) else: mod.__all__ = [fn.__name__] return fn
Export decorator Please refer to the following SO article for details: https://stackoverflow.com/a/35710527
Below is the the instruction that describes the task: ### Input: Export decorator Please refer to the following SO article for details: https://stackoverflow.com/a/35710527 ### Response: def export(fn): """ Export decorator Please refer to the following SO article for details: https://stackoverflow.c...
def derivatives(self, x, y, Rs, theta_Rs, r_core, center_x=0, center_y=0): """ deflection angles :param x: x coordinate :param y: y coordinate :param Rs: scale radius :param rho0: central core density :param r_core: core radius :param center_x: :pa...
deflection angles :param x: x coordinate :param y: y coordinate :param Rs: scale radius :param rho0: central core density :param r_core: core radius :param center_x: :param center_y: :return:
Below is the the instruction that describes the task: ### Input: deflection angles :param x: x coordinate :param y: y coordinate :param Rs: scale radius :param rho0: central core density :param r_core: core radius :param center_x: :param center_y: :ret...
def sense(self, *targets, **options): """Discover a contactless card or listening device. .. note:: The :meth:`sense` method is intended for experts with a good understanding of the commands and responses exchanged during target activation (the noti...
Discover a contactless card or listening device. .. note:: The :meth:`sense` method is intended for experts with a good understanding of the commands and responses exchanged during target activation (the notion used for commands and responses follows the ...
Below is the the instruction that describes the task: ### Input: Discover a contactless card or listening device. .. note:: The :meth:`sense` method is intended for experts with a good understanding of the commands and responses exchanged during target activation (the ...
def linesubst(line, variables): """ In a string, substitute '{{varname}}' occurrences with the value of variables['varname'], '\\' being an escaping char... If at first you don't understand this function, draw its finite state machine and everything will become crystal clear :) """ # trivial...
In a string, substitute '{{varname}}' occurrences with the value of variables['varname'], '\\' being an escaping char... If at first you don't understand this function, draw its finite state machine and everything will become crystal clear :)
Below is the the instruction that describes the task: ### Input: In a string, substitute '{{varname}}' occurrences with the value of variables['varname'], '\\' being an escaping char... If at first you don't understand this function, draw its finite state machine and everything will become crystal clear...
def blink1(switch_off=True, gamma=None, white_point=None): """Context manager which automatically shuts down the Blink(1) after use. :param switch_off: turn blink(1) off when existing context :param gamma: set gamma curve (as tuple) :param white_point: set white point (as tuple) """ b1 = Bli...
Context manager which automatically shuts down the Blink(1) after use. :param switch_off: turn blink(1) off when existing context :param gamma: set gamma curve (as tuple) :param white_point: set white point (as tuple)
Below is the the instruction that describes the task: ### Input: Context manager which automatically shuts down the Blink(1) after use. :param switch_off: turn blink(1) off when existing context :param gamma: set gamma curve (as tuple) :param white_point: set white point (as tuple) ### Response: de...
def _set_session_role(self, v, load=False): """ Setter method for session_role, mapped from YANG variable /mpls_state/rsvp/sessions/session_role (session-role) If this variable is read-only (config: false) in the source YANG file, then _set_session_role is considered as a private method. Backends lo...
Setter method for session_role, mapped from YANG variable /mpls_state/rsvp/sessions/session_role (session-role) If this variable is read-only (config: false) in the source YANG file, then _set_session_role is considered as a private method. Backends looking to populate this variable should do so via cal...
Below is the the instruction that describes the task: ### Input: Setter method for session_role, mapped from YANG variable /mpls_state/rsvp/sessions/session_role (session-role) If this variable is read-only (config: false) in the source YANG file, then _set_session_role is considered as a private method...
async def status(self, *args, **kwargs): """ Get task status Get task status structure from `taskId` This method gives output: ``v1/task-status-response.json#`` This method is ``stable`` """ return await self._makeApiCall(self.funcinfo["status"], *args, **kwar...
Get task status Get task status structure from `taskId` This method gives output: ``v1/task-status-response.json#`` This method is ``stable``
Below is the the instruction that describes the task: ### Input: Get task status Get task status structure from `taskId` This method gives output: ``v1/task-status-response.json#`` This method is ``stable`` ### Response: async def status(self, *args, **kwargs): """ Get ta...
def make_caches(driver, specs, catdir=None, cache_dir=None, storage_options={}): """ Creates Cache objects from the cache_specs provided in the catalog yaml file Parameters ---------- driver: str Name of the plugin that can load catalog entry specs: list Specification for cachi...
Creates Cache objects from the cache_specs provided in the catalog yaml file Parameters ---------- driver: str Name of the plugin that can load catalog entry specs: list Specification for caching the data source.
Below is the the instruction that describes the task: ### Input: Creates Cache objects from the cache_specs provided in the catalog yaml file Parameters ---------- driver: str Name of the plugin that can load catalog entry specs: list Specification for caching the data source. ### ...
def range(*args, prefix: str): """Returns a range of NamedQubits. The range returned starts with the prefix, and followed by a qubit for each number in the range, e.g.: NamedQubit.range(3, prefix="a") -> ["a1", "a2", "a3] NamedQubit.range(2, 4, prefix="a") -> ["a2", "a3] ...
Returns a range of NamedQubits. The range returned starts with the prefix, and followed by a qubit for each number in the range, e.g.: NamedQubit.range(3, prefix="a") -> ["a1", "a2", "a3] NamedQubit.range(2, 4, prefix="a") -> ["a2", "a3] Args: *args: Args to be pas...
Below is the the instruction that describes the task: ### Input: Returns a range of NamedQubits. The range returned starts with the prefix, and followed by a qubit for each number in the range, e.g.: NamedQubit.range(3, prefix="a") -> ["a1", "a2", "a3] NamedQubit.range(2, 4, prefix...
def pipe_wait(popens): """ Given an array of Popen objects returned by the pipe method, wait for all processes to terminate and return the array with their return values. Taken from http://www.enricozini.org/2009/debian/python-pipes/ """ # Avoid mutating the passed copy popens = copy.c...
Given an array of Popen objects returned by the pipe method, wait for all processes to terminate and return the array with their return values. Taken from http://www.enricozini.org/2009/debian/python-pipes/
Below is the the instruction that describes the task: ### Input: Given an array of Popen objects returned by the pipe method, wait for all processes to terminate and return the array with their return values. Taken from http://www.enricozini.org/2009/debian/python-pipes/ ### Response: def pipe_wait(po...
def _ReadDataTypeDefinitionWithMembers( self, definitions_registry, definition_values, data_type_definition_class, definition_name, supports_conditions=False): """Reads a data type definition with members. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions ...
Reads a data type definition with members. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. data_type_definition_class (str): data type definition class. definition_name (str): name ...
Below is the the instruction that describes the task: ### Input: Reads a data type definition with members. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. data_type_definition_class ...
def create_user(username, password, permissions, users=None): ''' Create user accounts CLI Example: .. code-block:: bash salt dell drac.create_user [USERNAME] [PASSWORD] [PRIVILEGES] salt dell drac.create_user diana secret login,test_alerts,clear_logs DRAC Privileges * logi...
Create user accounts CLI Example: .. code-block:: bash salt dell drac.create_user [USERNAME] [PASSWORD] [PRIVILEGES] salt dell drac.create_user diana secret login,test_alerts,clear_logs DRAC Privileges * login : Login to iDRAC * drac : Con...
Below is the the instruction that describes the task: ### Input: Create user accounts CLI Example: .. code-block:: bash salt dell drac.create_user [USERNAME] [PASSWORD] [PRIVILEGES] salt dell drac.create_user diana secret login,test_alerts,clear_logs DRAC Privileges * login ...
def list(self, filter_title=None, filter_ids=None, page=None): """ :type filter_title: str :param filter_title: Filter by dashboard title :type filter_ids: list of ints :param filter_ids: Filter by dashboard ids :type page: int :param page: Pagination index ...
:type filter_title: str :param filter_title: Filter by dashboard title :type filter_ids: list of ints :param filter_ids: Filter by dashboard ids :type page: int :param page: Pagination index :rtype: dict :return: The JSON response of the API, with an additional...
Below is the the instruction that describes the task: ### Input: :type filter_title: str :param filter_title: Filter by dashboard title :type filter_ids: list of ints :param filter_ids: Filter by dashboard ids :type page: int :param page: Pagination index :rtype: d...
def _characteristics_discovered(self, service): """Called when GATT characteristics have been discovered.""" # Characteristics for the specified service were discovered. Update # set of discovered services and signal when all have been discovered. self._discovered_services.add(service) ...
Called when GATT characteristics have been discovered.
Below is the the instruction that describes the task: ### Input: Called when GATT characteristics have been discovered. ### Response: def _characteristics_discovered(self, service): """Called when GATT characteristics have been discovered.""" # Characteristics for the specified service were discove...
def update(self, db): """update(db) Update this database with all resources entries in the resource database DB. """ self.lock.acquire() update_db(self.db, db.db) self.lock.release()
update(db) Update this database with all resources entries in the resource database DB.
Below is the the instruction that describes the task: ### Input: update(db) Update this database with all resources entries in the resource database DB. ### Response: def update(self, db): """update(db) Update this database with all resources entries in the resource databa...
def serialize(exc): """ Serialize `self.exc` into a data dictionary representing it. """ return { 'exc_type': type(exc).__name__, 'exc_path': get_module_path(type(exc)), 'exc_args': list(map(safe_for_serialization, exc.args)), 'value': safe_for_serialization(exc), }
Serialize `self.exc` into a data dictionary representing it.
Below is the the instruction that describes the task: ### Input: Serialize `self.exc` into a data dictionary representing it. ### Response: def serialize(exc): """ Serialize `self.exc` into a data dictionary representing it. """ return { 'exc_type': type(exc).__name__, 'exc_path': get_...
def tf_loss_per_instance(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None): """ Creates the TensorFlow operations for calculating the loss per batch instance. Args: states: Dict of state tensors. ...
Creates the TensorFlow operations for calculating the loss per batch instance. Args: states: Dict of state tensors. internals: Dict of prior internal state tensors. actions: Dict of action tensors. terminal: Terminal boolean tensor. reward: Reward ten...
Below is the the instruction that describes the task: ### Input: Creates the TensorFlow operations for calculating the loss per batch instance. Args: states: Dict of state tensors. internals: Dict of prior internal state tensors. actions: Dict of action tensors. ...
def assign_component_value(cli, transform_path, component_type, name, value): """ Requests status on whether a scene is loaded or not. :param cli: :param transform_path: The path of the transform where the component resides :param component_type: The C# type name of the component GetComponent(type) ...
Requests status on whether a scene is loaded or not. :param cli: :param transform_path: The path of the transform where the component resides :param component_type: The C# type name of the component GetComponent(type) :param name: The field or property name. :param value: The value to assign (String...
Below is the the instruction that describes the task: ### Input: Requests status on whether a scene is loaded or not. :param cli: :param transform_path: The path of the transform where the component resides :param component_type: The C# type name of the component GetComponent(type) :param name: The ...
def unregister_file(path, pkg=None, conn=None): # pylint: disable=W0612 ''' Unregister a file from the package database ''' close = False if conn is None: close = True conn = init() conn.execute('DELETE FROM files WHERE path=?', (path, )) if close: conn.close()
Unregister a file from the package database
Below is the the instruction that describes the task: ### Input: Unregister a file from the package database ### Response: def unregister_file(path, pkg=None, conn=None): # pylint: disable=W0612 ''' Unregister a file from the package database ''' close = False if conn is None: close = ...
def initialize(self): """See :meth:`pymlab.sensors.Device.initialize` for more information. Calls `initialize()` on all devices connected to the bus. """ Device.initialize(self) for child in iter(self.children.values()): child.initialize()
See :meth:`pymlab.sensors.Device.initialize` for more information. Calls `initialize()` on all devices connected to the bus.
Below is the the instruction that describes the task: ### Input: See :meth:`pymlab.sensors.Device.initialize` for more information. Calls `initialize()` on all devices connected to the bus. ### Response: def initialize(self): """See :meth:`pymlab.sensors.Device.initialize` for more information. ...
def team_profiles(self, team): """ Get team's social media profiles linked on their TBA page. :param team: Team to get data on. :return: List of Profile objects. """ return [Profile(raw) for raw in self._get('team/%s/social_media' % self.team_key(team))]
Get team's social media profiles linked on their TBA page. :param team: Team to get data on. :return: List of Profile objects.
Below is the the instruction that describes the task: ### Input: Get team's social media profiles linked on their TBA page. :param team: Team to get data on. :return: List of Profile objects. ### Response: def team_profiles(self, team): """ Get team's social media profiles linked o...
def stylize(text, styles, reset=True): """conveniently styles your text as and resets ANSI codes at its end.""" terminator = attr("reset") if reset else "" return "{}{}{}".format("".join(styles), text, terminator)
conveniently styles your text as and resets ANSI codes at its end.
Below is the the instruction that describes the task: ### Input: conveniently styles your text as and resets ANSI codes at its end. ### Response: def stylize(text, styles, reset=True): """conveniently styles your text as and resets ANSI codes at its end.""" terminator = attr("reset") if reset else "" r...
def _status_query(query, hostname, enumerate=None, service=None): ''' Send query along to Nagios. ''' config = _config() data = None params = { 'hostname': hostname, 'query': query, } ret = { 'result': False } if enumerate: params['formatoptions...
Send query along to Nagios.
Below is the the instruction that describes the task: ### Input: Send query along to Nagios. ### Response: def _status_query(query, hostname, enumerate=None, service=None): ''' Send query along to Nagios. ''' config = _config() data = None params = { 'hostname': hostname, '...
def _get_relationships(model): """ Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships o...
Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships on the Model. :rtype: tuple
Below is the the instruction that describes the task: ### Input: Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances correspond...
async def revoke(self): """Removes all access rights for this user from the controller. """ await self.controller.revoke(self.username) self._user_info.access = ''
Removes all access rights for this user from the controller.
Below is the the instruction that describes the task: ### Input: Removes all access rights for this user from the controller. ### Response: async def revoke(self): """Removes all access rights for this user from the controller. """ await self.controller.revoke(self.username) self._u...
def x10_housecode(self): """Emit the X10 house code.""" housecode = None if self.is_x10: housecode = insteonplm.utils.byte_to_housecode(self.addr[1]) return housecode
Emit the X10 house code.
Below is the the instruction that describes the task: ### Input: Emit the X10 house code. ### Response: def x10_housecode(self): """Emit the X10 house code.""" housecode = None if self.is_x10: housecode = insteonplm.utils.byte_to_housecode(self.addr[1]) return housecode
def add_resource(self, transaction, parent_resource, lp): """ Render a POST on a new resource. :param transaction: the transaction :param parent_resource: the parent of the resource :param lp: the location_path attribute of the resource :return: the response """ ...
Render a POST on a new resource. :param transaction: the transaction :param parent_resource: the parent of the resource :param lp: the location_path attribute of the resource :return: the response
Below is the the instruction that describes the task: ### Input: Render a POST on a new resource. :param transaction: the transaction :param parent_resource: the parent of the resource :param lp: the location_path attribute of the resource :return: the response ### Response: def ad...
def _parse(self, stream, context, path): """Parse stream to find a given byte string.""" start = stream.tell() read_bytes = "" if self.max_length: read_bytes = stream.read(self.max_length) else: read_bytes = stream.read() skip = read_bytes.find(sel...
Parse stream to find a given byte string.
Below is the the instruction that describes the task: ### Input: Parse stream to find a given byte string. ### Response: def _parse(self, stream, context, path): """Parse stream to find a given byte string.""" start = stream.tell() read_bytes = "" if self.max_length: rea...
def escape( x, lb=False ): """ Ensure a string does not contain HTML-reserved characters (including double quotes) Optionally also insert a linebreak if the string is too long """ # Insert a linebreak? Roughly around the middle of the string, if lb: l = len(x) if l >= 10: ...
Ensure a string does not contain HTML-reserved characters (including double quotes) Optionally also insert a linebreak if the string is too long
Below is the the instruction that describes the task: ### Input: Ensure a string does not contain HTML-reserved characters (including double quotes) Optionally also insert a linebreak if the string is too long ### Response: def escape( x, lb=False ): """ Ensure a string does not contain HTML-reserv...
def competition_list_files(self, competition): """ list files for competition Parameters ========== competition: the name of the competition """ competition_list_files_result = self.process_response( self.competitions_data_list_files_with_http_inf...
list files for competition Parameters ========== competition: the name of the competition
Below is the the instruction that describes the task: ### Input: list files for competition Parameters ========== competition: the name of the competition ### Response: def competition_list_files(self, competition): """ list files for competition Parameters...
def EMAIL_REQUIRED(self): """ The user is required to hand over an e-mail address when signing up """ from allauth.account import app_settings as account_settings return self._setting("EMAIL_REQUIRED", account_settings.EMAIL_REQUIRED)
The user is required to hand over an e-mail address when signing up
Below is the the instruction that describes the task: ### Input: The user is required to hand over an e-mail address when signing up ### Response: def EMAIL_REQUIRED(self): """ The user is required to hand over an e-mail address when signing up """ from allauth.account import app_se...
def is_metaseries(self): """Page contains MDS MetaSeries metadata in ImageDescription tag.""" if self.index > 1 or self.software != 'MetaSeries': return False d = self.description return d.startswith('<MetaData>') and d.endswith('</MetaData>')
Page contains MDS MetaSeries metadata in ImageDescription tag.
Below is the the instruction that describes the task: ### Input: Page contains MDS MetaSeries metadata in ImageDescription tag. ### Response: def is_metaseries(self): """Page contains MDS MetaSeries metadata in ImageDescription tag.""" if self.index > 1 or self.software != 'MetaSeries': ...
def encode_scopes(scopes, use_quote=False): """ Creates a string out of a list of scopes. :param scopes: A list of scopes :param use_quote: Boolean flag indicating whether the string should be quoted :return: Scopes as a string """ scopes_as_string = Scope.separator.join(scopes) if use...
Creates a string out of a list of scopes. :param scopes: A list of scopes :param use_quote: Boolean flag indicating whether the string should be quoted :return: Scopes as a string
Below is the the instruction that describes the task: ### Input: Creates a string out of a list of scopes. :param scopes: A list of scopes :param use_quote: Boolean flag indicating whether the string should be quoted :return: Scopes as a string ### Response: def encode_scopes(scopes, use_quote=False):...
def load(): ''' Return all of the data in the minion datastore CLI Example: .. code-block:: bash salt '*' data.load ''' serial = salt.payload.Serial(__opts__) try: datastore_path = os.path.join(__opts__['cachedir'], 'datastore') with salt.utils.files.fopen(datasto...
Return all of the data in the minion datastore CLI Example: .. code-block:: bash salt '*' data.load
Below is the the instruction that describes the task: ### Input: Return all of the data in the minion datastore CLI Example: .. code-block:: bash salt '*' data.load ### Response: def load(): ''' Return all of the data in the minion datastore CLI Example: .. code-block:: bash ...
def _from_dict(cls, _dict): """Initialize a ValueCollection object from a json dictionary.""" args = {} if 'values' in _dict: args['values'] = [ Value._from_dict(x) for x in (_dict.get('values')) ] else: raise ValueError( ...
Initialize a ValueCollection object from a json dictionary.
Below is the the instruction that describes the task: ### Input: Initialize a ValueCollection object from a json dictionary. ### Response: def _from_dict(cls, _dict): """Initialize a ValueCollection object from a json dictionary.""" args = {} if 'values' in _dict: args['values']...
def load_mnist(): '''Load the MNIST digits dataset.''' mnist = skdata.mnist.dataset.MNIST() mnist.meta # trigger download if needed. def arr(n, dtype): arr = mnist.arrays[n] return arr.reshape((len(arr), -1)).astype(dtype) train_images = arr('train_images', np.float32) / 128 - 1 ...
Load the MNIST digits dataset.
Below is the the instruction that describes the task: ### Input: Load the MNIST digits dataset. ### Response: def load_mnist(): '''Load the MNIST digits dataset.''' mnist = skdata.mnist.dataset.MNIST() mnist.meta # trigger download if needed. def arr(n, dtype): arr = mnist.arrays[n] ...
def about_axis(cls, center, angle, axis, invert=False): """Create transformation that represents a rotation about an axis Arguments: | ``center`` -- Point on the axis | ``angle`` -- Rotation angle | ``axis`` -- Rotation axis | ``invert`` -- Whe...
Create transformation that represents a rotation about an axis Arguments: | ``center`` -- Point on the axis | ``angle`` -- Rotation angle | ``axis`` -- Rotation axis | ``invert`` -- When True, an inversion rotation is constructed ...
Below is the the instruction that describes the task: ### Input: Create transformation that represents a rotation about an axis Arguments: | ``center`` -- Point on the axis | ``angle`` -- Rotation angle | ``axis`` -- Rotation axis | ``invert`` -- W...
def array(self, name): """ Returns the array of tables with the given name. """ if name in self._navigable: if isinstance(self._navigable[name], (list, tuple)): return self[name] else: raise NoArrayFoundError else: ...
Returns the array of tables with the given name.
Below is the the instruction that describes the task: ### Input: Returns the array of tables with the given name. ### Response: def array(self, name): """ Returns the array of tables with the given name. """ if name in self._navigable: if isinstance(self._navigable[name]...
def try_eval_metadata(metadata, name): """Evaluate given metadata to a python object, if possible""" value = metadata[name] if not isinstance(value, (str, unicode)): return if (value.startswith('"') and value.endswith('"')) or (value.startswith("'") and value.endswith("'")): if name in [...
Evaluate given metadata to a python object, if possible
Below is the the instruction that describes the task: ### Input: Evaluate given metadata to a python object, if possible ### Response: def try_eval_metadata(metadata, name): """Evaluate given metadata to a python object, if possible""" value = metadata[name] if not isinstance(value, (str, unicode)): ...
def min_percent(self, value: float) -> 'Size': """Set the minimum percentage of free space to use.""" raise_not_number(value) self.minimum = '{}%'.format(value) return self
Set the minimum percentage of free space to use.
Below is the the instruction that describes the task: ### Input: Set the minimum percentage of free space to use. ### Response: def min_percent(self, value: float) -> 'Size': """Set the minimum percentage of free space to use.""" raise_not_number(value) self.minimum = '{}%'.format(value) ...
def sets(self): """Get list of sets.""" if self.cache: return self.cache.get( self.app.config['OAISERVER_CACHE_KEY'])
Get list of sets.
Below is the the instruction that describes the task: ### Input: Get list of sets. ### Response: def sets(self): """Get list of sets.""" if self.cache: return self.cache.get( self.app.config['OAISERVER_CACHE_KEY'])
def can_create_replica_without_replication_connection(self): """ go through the replication methods to see if there are ones that does not require a working replication connection. """ replica_methods = self._create_replica_methods return any(self.replica_method_can_work_with...
go through the replication methods to see if there are ones that does not require a working replication connection.
Below is the the instruction that describes the task: ### Input: go through the replication methods to see if there are ones that does not require a working replication connection. ### Response: def can_create_replica_without_replication_connection(self): """ go through the replication methods ...
def validate_cmd_response_int(name, got, expected): """ Check that some value returned in the response to a command matches what we put in the request (the command). """ if got != expected: raise(pyhsm.exception.YHSM_Error("Bad %s in response (got %i, expected %i)" \ ...
Check that some value returned in the response to a command matches what we put in the request (the command).
Below is the the instruction that describes the task: ### Input: Check that some value returned in the response to a command matches what we put in the request (the command). ### Response: def validate_cmd_response_int(name, got, expected): """ Check that some value returned in the response to a comman...
def quote_datetime(self, value): """ Force the quote_datetime to always be a datetime :param value: :return: """ if value: if isinstance(value, type_check): self._quote_datetime = parse(value) elif isinstance(value, datetime.datetim...
Force the quote_datetime to always be a datetime :param value: :return:
Below is the the instruction that describes the task: ### Input: Force the quote_datetime to always be a datetime :param value: :return: ### Response: def quote_datetime(self, value): """ Force the quote_datetime to always be a datetime :param value: :return: ...
def sendrpc(self, argv=[]): self._aArgv += argv _operation = '' try: self._cParams.parser(self._aArgv, self._dOptions) # set rpc operation handler while self._cParams.get('operation') not in rpc.operations.keys(): self._cParams.set('op...
end of function exchgmsg
Below is the the instruction that describes the task: ### Input: end of function exchgmsg ### Response: def sendrpc(self, argv=[]): self._aArgv += argv _operation = '' try: self._cParams.parser(self._aArgv, self._dOptions) # set rpc operation handler ...
def create_page(self, content, class_, record_keeper=None, logger=None): ''' Robust as possible Attempts to create the page If any of the functions used to attach content to the page fail, keep going, keep a record of those errors in a context dict return the page and th...
Robust as possible Attempts to create the page If any of the functions used to attach content to the page fail, keep going, keep a record of those errors in a context dict return the page and the context dict in a tuple
Below is the the instruction that describes the task: ### Input: Robust as possible Attempts to create the page If any of the functions used to attach content to the page fail, keep going, keep a record of those errors in a context dict return the page and the context dict in a tupl...
def get_common_register(start, end): """Get the register most commonly used in accessing structs. Access to is considered for every opcode that accesses memory in an offset from a register:: mov eax, [ebx + 5] For every access, the struct-referencing registers, in this case `ebx`, are cou...
Get the register most commonly used in accessing structs. Access to is considered for every opcode that accesses memory in an offset from a register:: mov eax, [ebx + 5] For every access, the struct-referencing registers, in this case `ebx`, are counted. The most used one is returned. Ar...
Below is the the instruction that describes the task: ### Input: Get the register most commonly used in accessing structs. Access to is considered for every opcode that accesses memory in an offset from a register:: mov eax, [ebx + 5] For every access, the struct-referencing registers, in thi...
def _find_first_bigger(self, timestamps, target, lower_bound, upper_bound): """ Find the first element in timestamps whose value is bigger than target. param list values: list of timestamps(epoch number). param target: target value. param lower_bound: lower bound for binary search. param upper_b...
Find the first element in timestamps whose value is bigger than target. param list values: list of timestamps(epoch number). param target: target value. param lower_bound: lower bound for binary search. param upper_bound: upper bound for binary search.
Below is the the instruction that describes the task: ### Input: Find the first element in timestamps whose value is bigger than target. param list values: list of timestamps(epoch number). param target: target value. param lower_bound: lower bound for binary search. param upper_bound: upper bound f...
def format(obj, options): """Return a string representation of the Python object Args: obj: The Python object options: Format options """ formatters = { float_types: lambda x: '{:.{}g}'.format(x, options.digits), } for _types, fmtr in formatters.items(): if isins...
Return a string representation of the Python object Args: obj: The Python object options: Format options
Below is the the instruction that describes the task: ### Input: Return a string representation of the Python object Args: obj: The Python object options: Format options ### Response: def format(obj, options): """Return a string representation of the Python object Args: obj: T...
def compose_github(projects, data): """ Compose projects.json for github :param projects: projects.json :param data: eclipse JSON :return: projects.json with github """ for p in [project for project in data if len(data[project]['github_repos']) > 0]: if 'github' not in projects[p]: ...
Compose projects.json for github :param projects: projects.json :param data: eclipse JSON :return: projects.json with github
Below is the the instruction that describes the task: ### Input: Compose projects.json for github :param projects: projects.json :param data: eclipse JSON :return: projects.json with github ### Response: def compose_github(projects, data): """ Compose projects.json for github :param projects:...
def next_token(self): """Lexical analyser of the raw input.""" while self.char is not None: if self.char.isspace(): # The current character is a whitespace self.whitespace() continue elif self.char == '#': # The cu...
Lexical analyser of the raw input.
Below is the the instruction that describes the task: ### Input: Lexical analyser of the raw input. ### Response: def next_token(self): """Lexical analyser of the raw input.""" while self.char is not None: if self.char.isspace(): # The current character is a whitespace ...