code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def update(self, **kwargs): """ Add, remove or modify a share's title. Input: * ``title`` The share title, if any (optional) **NOTE**: Passing ``None`` or calling this method with an empty argument list will remove the share's title. Output: * None ...
Add, remove or modify a share's title. Input: * ``title`` The share title, if any (optional) **NOTE**: Passing ``None`` or calling this method with an empty argument list will remove the share's title. Output: * None Example:: share = client.get_s...
Below is the the instruction that describes the task: ### Input: Add, remove or modify a share's title. Input: * ``title`` The share title, if any (optional) **NOTE**: Passing ``None`` or calling this method with an empty argument list will remove the share's title. Output: ...
def plural_fmt(name, cnt): """ pluralize name if necessary and combine with cnt :param name: str name of the item type :param cnt: int number items of this type :return: str name and cnt joined """ if cnt == 1: return '{} {}'.format(cnt, name) ...
pluralize name if necessary and combine with cnt :param name: str name of the item type :param cnt: int number items of this type :return: str name and cnt joined
Below is the the instruction that describes the task: ### Input: pluralize name if necessary and combine with cnt :param name: str name of the item type :param cnt: int number items of this type :return: str name and cnt joined ### Response: def plural_fmt(name, cnt): """ pl...
def begin(self): """Start a new transaction.""" if self.in_transaction: # we're already in a transaction... if self._auto_transaction: self._auto_transaction = False return self.commit() self.in_transaction = True for collection, s...
Start a new transaction.
Below is the the instruction that describes the task: ### Input: Start a new transaction. ### Response: def begin(self): """Start a new transaction.""" if self.in_transaction: # we're already in a transaction... if self._auto_transaction: self._auto_transaction = False ...
def set_image(self): """This code must be in its own method since the fetch functions need credits to be set. m2m fields are not yet set at the end of either the save method or post_save signal.""" if not self.image: scrape_image(self) # If still no image then use f...
This code must be in its own method since the fetch functions need credits to be set. m2m fields are not yet set at the end of either the save method or post_save signal.
Below is the the instruction that describes the task: ### Input: This code must be in its own method since the fetch functions need credits to be set. m2m fields are not yet set at the end of either the save method or post_save signal. ### Response: def set_image(self): """This code must be...
def insert_colorpoint(self, position=0.5, color1=[1.0,1.0,0.0], color2=[1.0,1.0,0.0]): """ Inserts the specified color into the list. """ L = self._colorpoint_list # if position = 0 or 1, push the end points inward if position <= 0.0: L.insert(0,[0.0,color1...
Inserts the specified color into the list.
Below is the the instruction that describes the task: ### Input: Inserts the specified color into the list. ### Response: def insert_colorpoint(self, position=0.5, color1=[1.0,1.0,0.0], color2=[1.0,1.0,0.0]): """ Inserts the specified color into the list. """ L = self._colorpoint_li...
def content(self, value): """ Defines the ``Content-Type`` outgoing header value to match. You can pass one of the following type aliases instead of the full MIME type representation: - ``json`` = ``application/json`` - ``xml`` = ``application/xml`` - ``html`` =...
Defines the ``Content-Type`` outgoing header value to match. You can pass one of the following type aliases instead of the full MIME type representation: - ``json`` = ``application/json`` - ``xml`` = ``application/xml`` - ``html`` = ``text/html`` - ``text`` = ``text/pla...
Below is the the instruction that describes the task: ### Input: Defines the ``Content-Type`` outgoing header value to match. You can pass one of the following type aliases instead of the full MIME type representation: - ``json`` = ``application/json`` - ``xml`` = ``application/xml...
def temporary_directory(): """ make a temporary directory, yeild its name, cleanup on exit """ dir_name = tempfile.mkdtemp() yield dir_name if os.path.exists(dir_name): shutil.rmtree(dir_name)
make a temporary directory, yeild its name, cleanup on exit
Below is the the instruction that describes the task: ### Input: make a temporary directory, yeild its name, cleanup on exit ### Response: def temporary_directory(): """ make a temporary directory, yeild its name, cleanup on exit """ dir_name = tempfile.mkdtemp() yield dir_name if os.path.exists(di...
def _from_dict(cls, _dict): """Initialize a AggregationResult object from a json dictionary.""" args = {} if 'key' in _dict: args['key'] = _dict.get('key') if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggrega...
Initialize a AggregationResult object from a json dictionary.
Below is the the instruction that describes the task: ### Input: Initialize a AggregationResult object from a json dictionary. ### Response: def _from_dict(cls, _dict): """Initialize a AggregationResult object from a json dictionary.""" args = {} if 'key' in _dict: args['key'] =...
def create(self, article, attachment, inline=False, file_name=None, content_type=None): """ This function creates attachment attached to article. :param article: Numeric article id or :class:`Article` object. :param attachment: File object or os path to file :param inline: If tr...
This function creates attachment attached to article. :param article: Numeric article id or :class:`Article` object. :param attachment: File object or os path to file :param inline: If true, the attached file is shown in the dedicated admin UI for inline attachments and its url can ...
Below is the the instruction that describes the task: ### Input: This function creates attachment attached to article. :param article: Numeric article id or :class:`Article` object. :param attachment: File object or os path to file :param inline: If true, the attached file is shown in the d...
def _onShortcutDuplicateLine(self): """Duplicate selected text or current line """ cursor = self.textCursor() if cursor.hasSelection(): # duplicate selection text = cursor.selectedText() selectionStart, selectionEnd = cursor.selectionStart(), cursor.selectionEnd(...
Duplicate selected text or current line
Below is the the instruction that describes the task: ### Input: Duplicate selected text or current line ### Response: def _onShortcutDuplicateLine(self): """Duplicate selected text or current line """ cursor = self.textCursor() if cursor.hasSelection(): # duplicate selection ...
def import_eit_fzj(self, filename, configfile, correction_file=None, timestep=None, **kwargs): """EIT data import for FZJ Medusa systems""" # we get not electrode positions (dummy1) and no topography data # (dummy2) df_emd, dummy1, dummy2 = eit_fzj.read_3p_data( ...
EIT data import for FZJ Medusa systems
Below is the the instruction that describes the task: ### Input: EIT data import for FZJ Medusa systems ### Response: def import_eit_fzj(self, filename, configfile, correction_file=None, timestep=None, **kwargs): """EIT data import for FZJ Medusa systems""" # we get not elect...
def bottom(self, objects: Set[Object]) -> Set[Object]: """ Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for each box. """ objects_per_box = self._separate_objects_by_boxes(objects) return_set: Set[Object] = set() for _, box...
Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for each box.
Below is the the instruction that describes the task: ### Input: Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for each box. ### Response: def bottom(self, objects: Set[Object]) -> Set[Object]: """ Return the bottom most objects(i.e. maximum y_loc). T...
def _controlSide(cls, side, grammar): # type: (_MetaRule, List[object], Grammar) -> None """ Validate one side of the rule. :param side: Iterable side of the rule. :param grammar: Grammar on which to validate. :raise RuleSyntaxException: If invalid syntax is use. ...
Validate one side of the rule. :param side: Iterable side of the rule. :param grammar: Grammar on which to validate. :raise RuleSyntaxException: If invalid syntax is use. :raise UselessEpsilonException: If useless epsilon is used. :raise TerminalDoesNotExistsException: If termina...
Below is the the instruction that describes the task: ### Input: Validate one side of the rule. :param side: Iterable side of the rule. :param grammar: Grammar on which to validate. :raise RuleSyntaxException: If invalid syntax is use. :raise UselessEpsilonException: If useless epsil...
def add_arguments(self): """ Definition and addition of all arguments. """ if self.parser is None: raise TypeError("Parser cannot be None, has create_parser been called?") for keys, kwargs in self.args.items(): if not isinstance(keys, tuple): ...
Definition and addition of all arguments.
Below is the the instruction that describes the task: ### Input: Definition and addition of all arguments. ### Response: def add_arguments(self): """ Definition and addition of all arguments. """ if self.parser is None: raise TypeError("Parser cannot be None, has create_...
def setup_figcanvas(self): """Setup the FigureCanvas.""" self.figcanvas = FigureCanvas(background_color=self.background_color) self.figcanvas.installEventFilter(self) self.setWidget(self.figcanvas)
Setup the FigureCanvas.
Below is the the instruction that describes the task: ### Input: Setup the FigureCanvas. ### Response: def setup_figcanvas(self): """Setup the FigureCanvas.""" self.figcanvas = FigureCanvas(background_color=self.background_color) self.figcanvas.installEventFilter(self) self.setWidge...
def filter_name(funcname, package, context="decorate", explicit=False): """Returns True if the specified function should be filtered (i.e., included or excluded for use in the specified context.) Args: funcname (str): name of the method/function being called. package (str): name of the pac...
Returns True if the specified function should be filtered (i.e., included or excluded for use in the specified context.) Args: funcname (str): name of the method/function being called. package (str): name of the package that the method belongs to. context (str): one of ['decorate', 'ti...
Below is the the instruction that describes the task: ### Input: Returns True if the specified function should be filtered (i.e., included or excluded for use in the specified context.) Args: funcname (str): name of the method/function being called. package (str): name of the package that ...
def get_properties(self, instance, fields): """ Get the feature metadata which will be used for the GeoJSON "properties" key. By default it returns all serializer fields excluding those used for the ID, the geometry and the bounding box. :param instance: The current Dja...
Get the feature metadata which will be used for the GeoJSON "properties" key. By default it returns all serializer fields excluding those used for the ID, the geometry and the bounding box. :param instance: The current Django model instance :param fields: The list of fields to ...
Below is the the instruction that describes the task: ### Input: Get the feature metadata which will be used for the GeoJSON "properties" key. By default it returns all serializer fields excluding those used for the ID, the geometry and the bounding box. :param instance: The curren...
def yzy_to_zyz(xi, theta1, theta2, eps=1e-9): # pylint: disable=invalid-name """Express a Y.Z.Y single qubit gate as a Z.Y.Z gate. Solve the equation .. math:: Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda) for theta, phi, and lambda. Return a solution ...
Express a Y.Z.Y single qubit gate as a Z.Y.Z gate. Solve the equation .. math:: Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda) for theta, phi, and lambda. Return a solution theta, phi, and lambda.
Below is the the instruction that describes the task: ### Input: Express a Y.Z.Y single qubit gate as a Z.Y.Z gate. Solve the equation .. math:: Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda) for theta, phi, and lambda. Return a solution theta, phi, and lamb...
def arithm_expr_target(x, target): """ Create arithmetic expression approaching target value :param x: allowed constants :param target: target value :returns: string in form 'expression=value' :complexity: huge """ n = len(x) expr = [{} for _ in range(1 << n)] # expr[S][val] # = ...
Create arithmetic expression approaching target value :param x: allowed constants :param target: target value :returns: string in form 'expression=value' :complexity: huge
Below is the the instruction that describes the task: ### Input: Create arithmetic expression approaching target value :param x: allowed constants :param target: target value :returns: string in form 'expression=value' :complexity: huge ### Response: def arithm_expr_target(x, target): """ Creat...
def startDtmf(): """START DTMF Section 9.3.24""" a = TpPd(pd=0x3) b = MessageType(mesType=0x35) # 00110101 c = KeypadFacilityHdr(ieiKF=0x2C, eightBitKF=0x0) packet = a / b / c return packet
START DTMF Section 9.3.24
Below is the the instruction that describes the task: ### Input: START DTMF Section 9.3.24 ### Response: def startDtmf(): """START DTMF Section 9.3.24""" a = TpPd(pd=0x3) b = MessageType(mesType=0x35) # 00110101 c = KeypadFacilityHdr(ieiKF=0x2C, eightBitKF=0x0) packet = a / b / c return pa...
def init(name, storage_backend='dir', trust_password=None, network_address=None, network_port=None, storage_create_device=None, storage_create_loop=None, storage_pool=None, done_file='%SALT_CONFIG_DIR%/lxd_initialized'): ''' Initalizes the LXD Daemon, as LXD doesn't tell if its initia...
Initalizes the LXD Daemon, as LXD doesn't tell if its initialized we touch the the done_file and check if it exist. This can only be called once per host unless you remove the done_file. name : Ignore this. This is just here for salt. storage_backend : Storage backend to use (zfs or d...
Below is the the instruction that describes the task: ### Input: Initalizes the LXD Daemon, as LXD doesn't tell if its initialized we touch the the done_file and check if it exist. This can only be called once per host unless you remove the done_file. name : Ignore this. This is just here for ...
def _graphify(self, *args, graph=None): # defined """ Lift phenotypeEdges to Restrictions """ if graph is None: graph = self.out_graph ################## LABELS ARE DEFINED HERE ################## gl = self.genLabel ll = self.localLabel ol = self.origLabel ...
Lift phenotypeEdges to Restrictions
Below is the the instruction that describes the task: ### Input: Lift phenotypeEdges to Restrictions ### Response: def _graphify(self, *args, graph=None): # defined """ Lift phenotypeEdges to Restrictions """ if graph is None: graph = self.out_graph ################## LABELS A...
def deep_force_unicode(value): """ Recursively call force_text on value. """ if isinstance(value, (list, tuple, set)): value = type(value)(map(deep_force_unicode, value)) elif isinstance(value, dict): value = type(value)(map(deep_force_unicode, value.items())) elif isinstance(val...
Recursively call force_text on value.
Below is the the instruction that describes the task: ### Input: Recursively call force_text on value. ### Response: def deep_force_unicode(value): """ Recursively call force_text on value. """ if isinstance(value, (list, tuple, set)): value = type(value)(map(deep_force_unicode, value)) ...
def requires_basic_auth(resource): ''' Flask decorator protecting ressources using username/password scheme ''' @functools.wraps(resource) def decorated(*args, **kwargs): ''' Check provided username/password ''' auth = flask.request.authorization user = check_credentials(auth...
Flask decorator protecting ressources using username/password scheme
Below is the the instruction that describes the task: ### Input: Flask decorator protecting ressources using username/password scheme ### Response: def requires_basic_auth(resource): ''' Flask decorator protecting ressources using username/password scheme ''' @functools.wraps(resource) def deco...
def end_tag(el): """ The text representation of an end tag for a tag. Includes trailing whitespace when appropriate. """ if el.tail and start_whitespace_re.search(el.tail): extra = ' ' else: extra = '' return '</%s>%s' % (el.tag, extra)
The text representation of an end tag for a tag. Includes trailing whitespace when appropriate.
Below is the the instruction that describes the task: ### Input: The text representation of an end tag for a tag. Includes trailing whitespace when appropriate. ### Response: def end_tag(el): """ The text representation of an end tag for a tag. Includes trailing whitespace when appropriate. """ ...
def _resolve_task_logging(job_metadata, job_resources, task_descriptors): """Resolve the logging path from job and task properties. Args: job_metadata: Job metadata, such as job-id, job-name, and user-id. job_resources: Resources specified such as ram, cpu, and logging path. task_descriptors: Task meta...
Resolve the logging path from job and task properties. Args: job_metadata: Job metadata, such as job-id, job-name, and user-id. job_resources: Resources specified such as ram, cpu, and logging path. task_descriptors: Task metadata, parameters, and resources. Resolve the logging path, which may have su...
Below is the the instruction that describes the task: ### Input: Resolve the logging path from job and task properties. Args: job_metadata: Job metadata, such as job-id, job-name, and user-id. job_resources: Resources specified such as ram, cpu, and logging path. task_descriptors: Task metadata, para...
def get_hash(file_path, checksum='sha1'): """ Generate a hash for the given file Args: file_path (str): Path to the file to generate the hash for checksum (str): hash to apply, one of the supported by hashlib, for example sha1 or sha512 Returns: str: hash for that f...
Generate a hash for the given file Args: file_path (str): Path to the file to generate the hash for checksum (str): hash to apply, one of the supported by hashlib, for example sha1 or sha512 Returns: str: hash for that file
Below is the the instruction that describes the task: ### Input: Generate a hash for the given file Args: file_path (str): Path to the file to generate the hash for checksum (str): hash to apply, one of the supported by hashlib, for example sha1 or sha512 Returns: str: ...
def show(ctx, short_name): """Show metadata for a specific subscription Example: \b $ wva subscriptions show speed {'buffer': 'queue', 'interval': 5, 'uri': 'vehicle/data/VehicleSpeed'} """ wva = get_wva(ctx) subscription = wva.get_subscription(short_name) cli_pprint(subscription.get_metadata(...
Show metadata for a specific subscription Example: \b $ wva subscriptions show speed {'buffer': 'queue', 'interval': 5, 'uri': 'vehicle/data/VehicleSpeed'}
Below is the the instruction that describes the task: ### Input: Show metadata for a specific subscription Example: \b $ wva subscriptions show speed {'buffer': 'queue', 'interval': 5, 'uri': 'vehicle/data/VehicleSpeed'} ### Response: def show(ctx, short_name): """Show metadata for a specific subscri...
def _get_data(self, func): """ This is the decorator for our DECORATED_METHODS. Each of the decorated methods must return: uri, params, method, body, headers, singleobject """ def wrapper(*args, **kwargs): timeout = kwargs.pop('timeout', None) uri, pa...
This is the decorator for our DECORATED_METHODS. Each of the decorated methods must return: uri, params, method, body, headers, singleobject
Below is the the instruction that describes the task: ### Input: This is the decorator for our DECORATED_METHODS. Each of the decorated methods must return: uri, params, method, body, headers, singleobject ### Response: def _get_data(self, func): """ This is the decorator for our DECORA...
def time_zone_by_name(self, hostname): """ Returns time zone in tzdata format (e.g. America/New_York or Europe/Paris) :arg hostname: Hostname (e.g. example.com) """ addr = self._gethostbyname(hostname) return self.time_zone_by_addr(addr)
Returns time zone in tzdata format (e.g. America/New_York or Europe/Paris) :arg hostname: Hostname (e.g. example.com)
Below is the the instruction that describes the task: ### Input: Returns time zone in tzdata format (e.g. America/New_York or Europe/Paris) :arg hostname: Hostname (e.g. example.com) ### Response: def time_zone_by_name(self, hostname): """ Returns time zone in tzdata format (e.g. America/N...
def credentials(self, credentials): """ Sets the credentials of this WebAuthorization. The confidential portion of the `Authorization` header that follows the `type` field. This field is write-only. It is omitted by read operations. If authorization is required, the `credentials` value must be...
Sets the credentials of this WebAuthorization. The confidential portion of the `Authorization` header that follows the `type` field. This field is write-only. It is omitted by read operations. If authorization is required, the `credentials` value must be provided whenever a File Source is created or modified....
Below is the the instruction that describes the task: ### Input: Sets the credentials of this WebAuthorization. The confidential portion of the `Authorization` header that follows the `type` field. This field is write-only. It is omitted by read operations. If authorization is required, the `credentials` ...
def require_user(self, *users, user=None): """A decorator to protect views with Negotiate authentication.""" # accept old-style single user keyword-argument as well if user: users = (*users, user) def _require_auth(view_func): @wraps(view_func) def w...
A decorator to protect views with Negotiate authentication.
Below is the the instruction that describes the task: ### Input: A decorator to protect views with Negotiate authentication. ### Response: def require_user(self, *users, user=None): """A decorator to protect views with Negotiate authentication.""" # accept old-style single user keyword-argument as...
def wait(self): """ Block until a matched message appears. """ if not self._patterns: raise RuntimeError('Listener has nothing to capture') while 1: msg = self._queue.get(block=True) if any(map(lambda p: filtering.match_all(msg, p), self._pat...
Block until a matched message appears.
Below is the the instruction that describes the task: ### Input: Block until a matched message appears. ### Response: def wait(self): """ Block until a matched message appears. """ if not self._patterns: raise RuntimeError('Listener has nothing to capture') whil...
def plot_kde(self, ax=None, amax=None, amin=None, label=None, return_fig=False): """ Plot a KDE for the curve. Very nice summary of KDEs: https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ ...
Plot a KDE for the curve. Very nice summary of KDEs: https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ Args: ax (axis): Optional matplotlib (MPL) axis to plot into. Returned. amax (float): Optional max value to permit. amin (float): Optional min va...
Below is the the instruction that describes the task: ### Input: Plot a KDE for the curve. Very nice summary of KDEs: https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/ Args: ax (axis): Optional matplotlib (MPL) axis to plot into. Returned. amax (float): Op...
def get_video_transcript(video_id, language_code): """ Get video transcript info Arguments: video_id(unicode): A video id, it can be an edx_video_id or an external video id extracted from external sources of a video component. language_code(unicode): it will be the language code of ...
Get video transcript info Arguments: video_id(unicode): A video id, it can be an edx_video_id or an external video id extracted from external sources of a video component. language_code(unicode): it will be the language code of the requested transcript.
Below is the the instruction that describes the task: ### Input: Get video transcript info Arguments: video_id(unicode): A video id, it can be an edx_video_id or an external video id extracted from external sources of a video component. language_code(unicode): it will be the language co...
def xor(left, right): """xor 2 strings. They can be shorter than each other, in which case the shortest will be padded with null bytes at its right. :param left: a string to be the left side of the xor :param right: a string to be the left side of the xor """ maxlength = max(map(len, (left, rig...
xor 2 strings. They can be shorter than each other, in which case the shortest will be padded with null bytes at its right. :param left: a string to be the left side of the xor :param right: a string to be the left side of the xor
Below is the the instruction that describes the task: ### Input: xor 2 strings. They can be shorter than each other, in which case the shortest will be padded with null bytes at its right. :param left: a string to be the left side of the xor :param right: a string to be the left side of the xor ### Res...
def getStretchTwistBendModulus(self, bp, frames=None, paxis='Z', masked=True, matrix=False): r"""Calculate Bending-Stretching-Twisting matrix It calculate elastic matrix and modulus matrix. .. math:: \text{modulus matrix} = 4.1419464 \times \begin{bmatrix} K_{Bx} ...
r"""Calculate Bending-Stretching-Twisting matrix It calculate elastic matrix and modulus matrix. .. math:: \text{modulus matrix} = 4.1419464 \times \begin{bmatrix} K_{Bx} & K_{Bx,By} & K_{Bx,S} & K_{Bx,T} \\ K_{Bx,By} & K_{By} & K_{By,S} & K_{By,T} \\ ...
Below is the the instruction that describes the task: ### Input: r"""Calculate Bending-Stretching-Twisting matrix It calculate elastic matrix and modulus matrix. .. math:: \text{modulus matrix} = 4.1419464 \times \begin{bmatrix} K_{Bx} & K_{Bx,By} & K_{Bx,S} & K_{Bx,...
def create_analytic_backend(settings): """ Creates a new Analytics backend from the settings :param settings: Dictionary of settings for the analytics backend :returns: A backend object implementing the analytics api >>> >>> analytics = create_analytic({ >>> 'backend': 'analytics.backe...
Creates a new Analytics backend from the settings :param settings: Dictionary of settings for the analytics backend :returns: A backend object implementing the analytics api >>> >>> analytics = create_analytic({ >>> 'backend': 'analytics.backends.redis.Redis', >>> 'settings': { >>>...
Below is the the instruction that describes the task: ### Input: Creates a new Analytics backend from the settings :param settings: Dictionary of settings for the analytics backend :returns: A backend object implementing the analytics api >>> >>> analytics = create_analytic({ >>> 'backend'...
def Read(self, length=None): """Read from the file.""" if self.progress_callback: self.progress_callback() available_to_read = max(0, (self.size or 0) - self.offset) if length is None: to_read = available_to_read else: to_read = min(length, available_to_read) with FileHandle...
Read from the file.
Below is the the instruction that describes the task: ### Input: Read from the file. ### Response: def Read(self, length=None): """Read from the file.""" if self.progress_callback: self.progress_callback() available_to_read = max(0, (self.size or 0) - self.offset) if length is None: t...
def register(self, *actions): """Register `actions` in the current application. All `actions` must be an instance of :class:`.Action` or one of its subclasses. If `overwrite` is `True`, then it is allowed to overwrite an existing action with same name and category; else `ValueError` ...
Register `actions` in the current application. All `actions` must be an instance of :class:`.Action` or one of its subclasses. If `overwrite` is `True`, then it is allowed to overwrite an existing action with same name and category; else `ValueError` is raised.
Below is the the instruction that describes the task: ### Input: Register `actions` in the current application. All `actions` must be an instance of :class:`.Action` or one of its subclasses. If `overwrite` is `True`, then it is allowed to overwrite an existing action with same name and cat...
def get_real_stored_key(self, session_key): """Return the real key name in redis storage @return string """ prefix = settings.SESSION_REDIS_PREFIX if not prefix: return session_key return ':'.join([prefix, session_key])
Return the real key name in redis storage @return string
Below is the the instruction that describes the task: ### Input: Return the real key name in redis storage @return string ### Response: def get_real_stored_key(self, session_key): """Return the real key name in redis storage @return string """ prefix = settings.SESSION_REDIS...
def read_key(self, key, bucket_name=None): """ Reads a key from S3 :param key: S3 key that will point to the file :type key: str :param bucket_name: Name of the bucket in which the file is stored :type bucket_name: str """ obj = self.get_key(key, bucket_...
Reads a key from S3 :param key: S3 key that will point to the file :type key: str :param bucket_name: Name of the bucket in which the file is stored :type bucket_name: str
Below is the the instruction that describes the task: ### Input: Reads a key from S3 :param key: S3 key that will point to the file :type key: str :param bucket_name: Name of the bucket in which the file is stored :type bucket_name: str ### Response: def read_key(self, key, bucket_...
def set_options(cls, obj, options=None, backend=None, **kwargs): """ Pure Python function for customize HoloViews objects in terms of their style, plot and normalization options. The options specification is a dictionary containing the target for customization as a {type}.{group...
Pure Python function for customize HoloViews objects in terms of their style, plot and normalization options. The options specification is a dictionary containing the target for customization as a {type}.{group}.{label} keys. An example of such a key is 'Image' which would customize all...
Below is the the instruction that describes the task: ### Input: Pure Python function for customize HoloViews objects in terms of their style, plot and normalization options. The options specification is a dictionary containing the target for customization as a {type}.{group}.{label} keys. ...
def workflow_overwrite(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /workflow-xxxx/overwrite API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fworkflow-xxxx%2Foverwrite """ return DXHTTPRequest('/%...
Invokes the /workflow-xxxx/overwrite API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fworkflow-xxxx%2Foverwrite
Below is the the instruction that describes the task: ### Input: Invokes the /workflow-xxxx/overwrite API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fworkflow-xxxx%2Foverwrite ### Response: def workflow_overwrite(object_id, input_param...
def grids(fig=None, value='solid'): """Sets the value of the grid_lines for the axis to the passed value. The default value is `solid`. Parameters ---------- fig: Figure or None(default: None) The figure for which the axes should be edited. If the value is None, the current figure i...
Sets the value of the grid_lines for the axis to the passed value. The default value is `solid`. Parameters ---------- fig: Figure or None(default: None) The figure for which the axes should be edited. If the value is None, the current figure is used. value: {'none', 'solid', 'dashe...
Below is the the instruction that describes the task: ### Input: Sets the value of the grid_lines for the axis to the passed value. The default value is `solid`. Parameters ---------- fig: Figure or None(default: None) The figure for which the axes should be edited. If the value is None, ...
def remove_field(self, field): """ Removes a field from this table :param field: This can be a string of a field name, a dict of {'alias': field}, or a ``Field`` instance :type field: str or dict or :class:`Field <querybuilder.fields.Field>` """ new_field = F...
Removes a field from this table :param field: This can be a string of a field name, a dict of {'alias': field}, or a ``Field`` instance :type field: str or dict or :class:`Field <querybuilder.fields.Field>`
Below is the the instruction that describes the task: ### Input: Removes a field from this table :param field: This can be a string of a field name, a dict of {'alias': field}, or a ``Field`` instance :type field: str or dict or :class:`Field <querybuilder.fields.Field>` ### Response: ...
def auth(self): """ tuple of (username, password). if use_keyring is set to true the password will be queried from the local keyring instead of taken from the configuration file. """ username = self._settings["username"] if not username: raise ValueError("Use...
tuple of (username, password). if use_keyring is set to true the password will be queried from the local keyring instead of taken from the configuration file.
Below is the the instruction that describes the task: ### Input: tuple of (username, password). if use_keyring is set to true the password will be queried from the local keyring instead of taken from the configuration file. ### Response: def auth(self): """ tuple of (username, password). if...
def load_objective(config): """ Loads the objective function from a .json file. """ assert 'prjpath' in config assert 'main-file' in config, "The problem file ('main-file') is missing!" os.chdir(config['prjpath']) if config['language'].lower()=='python': assert config['main-fil...
Loads the objective function from a .json file.
Below is the the instruction that describes the task: ### Input: Loads the objective function from a .json file. ### Response: def load_objective(config): """ Loads the objective function from a .json file. """ assert 'prjpath' in config assert 'main-file' in config, "The problem file ('main-f...
def delete(self): """Delete the file.""" self.close() if self.does_file_exist(): os.remove(self.path)
Delete the file.
Below is the the instruction that describes the task: ### Input: Delete the file. ### Response: def delete(self): """Delete the file.""" self.close() if self.does_file_exist(): os.remove(self.path)
def delete_value(self, key): """ Delete the key if the token is expired. Arg: key : cache key """ response = {} response['status'] = False response['msg'] = "key does not exist" file_cache = self.read_file() if key in file_cache: ...
Delete the key if the token is expired. Arg: key : cache key
Below is the the instruction that describes the task: ### Input: Delete the key if the token is expired. Arg: key : cache key ### Response: def delete_value(self, key): """ Delete the key if the token is expired. Arg: key : cache key """ response = ...
def G(self, v, t): """Aburn2012 equations right hand side, noise term Args: v: (8,) array state vector t: number scalar time Returns: (8,1) array Only one matrix column, meaning that in this example we are modelling th...
Aburn2012 equations right hand side, noise term Args: v: (8,) array state vector t: number scalar time Returns: (8,1) array Only one matrix column, meaning that in this example we are modelling the noise input to pyramidal and...
Below is the the instruction that describes the task: ### Input: Aburn2012 equations right hand side, noise term Args: v: (8,) array state vector t: number scalar time Returns: (8,1) array Only one matrix column, meaning that in thi...
def service_status(self, name): """Pull the current status of a service by name. Returns: dict: A dictionary of service status """ return self._loop.run_coroutine(self._client.service_status(name))
Pull the current status of a service by name. Returns: dict: A dictionary of service status
Below is the the instruction that describes the task: ### Input: Pull the current status of a service by name. Returns: dict: A dictionary of service status ### Response: def service_status(self, name): """Pull the current status of a service by name. Returns: dict...
def is_same_day(self, dt): """ Checks if the passed in date is the same day as the instance current day. :type dt: DateTime or datetime or str or int :rtype: bool """ dt = pendulum.instance(dt) return self.to_date_string() == dt.to_date_string()
Checks if the passed in date is the same day as the instance current day. :type dt: DateTime or datetime or str or int :rtype: bool
Below is the the instruction that describes the task: ### Input: Checks if the passed in date is the same day as the instance current day. :type dt: DateTime or datetime or str or int :rtype: bool ### Response: def is_same_day(self, dt): """ Checks if the passed in date is...
def handle_authorized_event(self, event): """Request roster upon login.""" self.server = event.authorized_jid.bare() if "versioning" in self.server_features: if self.roster is not None and self.roster.version is not None: version = self.roster.version else...
Request roster upon login.
Below is the the instruction that describes the task: ### Input: Request roster upon login. ### Response: def handle_authorized_event(self, event): """Request roster upon login.""" self.server = event.authorized_jid.bare() if "versioning" in self.server_features: if self.roster ...
def _parse_members(self, contents, module): """Extracts any module-level members from the code. They must appear before any type declalations.""" #We need to get hold of the text before the module's main CONTAINS keyword #so that we don't find variables from executables and claim them as...
Extracts any module-level members from the code. They must appear before any type declalations.
Below is the the instruction that describes the task: ### Input: Extracts any module-level members from the code. They must appear before any type declalations. ### Response: def _parse_members(self, contents, module): """Extracts any module-level members from the code. They must appear before ...
def open(self): """Opens a SSH connection with a Pluribus machine.""" self._connection = paramiko.SSHClient() self._connection.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self._connection.connect(hostname=self._hostname, use...
Opens a SSH connection with a Pluribus machine.
Below is the the instruction that describes the task: ### Input: Opens a SSH connection with a Pluribus machine. ### Response: def open(self): """Opens a SSH connection with a Pluribus machine.""" self._connection = paramiko.SSHClient() self._connection.set_missing_host_key_policy(paramiko....
def UsersChangePassword (self, current_password, new_password): """ Change the password for the current user @param current_password (string) - md5 hash of the current password of the user @param new_password (string) - md5 hash of the new password of the us...
Change the password for the current user @param current_password (string) - md5 hash of the current password of the user @param new_password (string) - md5 hash of the new password of the user (make sure to doublecheck!) @return (bool) - Boolean indicat...
Below is the the instruction that describes the task: ### Input: Change the password for the current user @param current_password (string) - md5 hash of the current password of the user @param new_password (string) - md5 hash of the new password of the user (make sure to doub...
def target_sequence(self): # type: () -> SeqRecord """Get the target sequence in the vector. The target sequence if the part of the plasmid that is not discarded during the assembly (everything except the placeholder sequence). """ if self.cutter.is_3overhang(): ...
Get the target sequence in the vector. The target sequence if the part of the plasmid that is not discarded during the assembly (everything except the placeholder sequence).
Below is the the instruction that describes the task: ### Input: Get the target sequence in the vector. The target sequence if the part of the plasmid that is not discarded during the assembly (everything except the placeholder sequence). ### Response: def target_sequence(self): # type: ()...
def remove_specification(self, name): """ Remove a specification that matches a query parameter. No checks for the specified or any parameter are made regarding specification removing :param name: parameter name to remove :return: None """ if name in self.__specs: self.__specs.pop(name)
Remove a specification that matches a query parameter. No checks for the specified or any parameter are made regarding specification removing :param name: parameter name to remove :return: None
Below is the the instruction that describes the task: ### Input: Remove a specification that matches a query parameter. No checks for the specified or any parameter are made regarding specification removing :param name: parameter name to remove :return: None ### Response: def remove_specification(self, name...
def image_to_rgb(self, path, n=10): """ Returns a list of colors based on pixel values in the image. The Core Image library must be present to determine pixel colors. F. Albers: http://nodebox.net/code/index.php/shared_2007-06-11-11-37-05 """ from PIL import Image ...
Returns a list of colors based on pixel values in the image. The Core Image library must be present to determine pixel colors. F. Albers: http://nodebox.net/code/index.php/shared_2007-06-11-11-37-05
Below is the the instruction that describes the task: ### Input: Returns a list of colors based on pixel values in the image. The Core Image library must be present to determine pixel colors. F. Albers: http://nodebox.net/code/index.php/shared_2007-06-11-11-37-05 ### Response: def image_to_rgb(sel...
def expand_internal_causal(universe: BELGraph, graph: BELGraph) -> None: """Add causal edges between entities in the sub-graph. Is an extremely thin wrapper around :func:`expand_internal`. :param universe: A BEL graph representing the universe of all knowledge :param graph: The target BEL graph to enr...
Add causal edges between entities in the sub-graph. Is an extremely thin wrapper around :func:`expand_internal`. :param universe: A BEL graph representing the universe of all knowledge :param graph: The target BEL graph to enrich with causal relations between contained nodes Equivalent to: >>> f...
Below is the the instruction that describes the task: ### Input: Add causal edges between entities in the sub-graph. Is an extremely thin wrapper around :func:`expand_internal`. :param universe: A BEL graph representing the universe of all knowledge :param graph: The target BEL graph to enrich with ca...
def get_action_by_id(self, action_id): """ Получение детального описания события """ parsed_json, raw_json = self._call('getactionbyid', element_id=action_id) action = Action.object_from_api(parsed_json, raw_json) return action
Получение детального описания события
Below is the the instruction that describes the task: ### Input: Получение детального описания события ### Response: def get_action_by_id(self, action_id): """ Получение детального описания события """ parsed_json, raw_json = self._call('getactionbyid', element_id=action_id) action ...
def find_state_op_colocation_error(graph, reported_tags=None): """Returns error message for colocation of state ops, or None if ok.""" state_op_types = list_registered_stateful_ops_without_inputs() state_op_map = {op.name: op for op in graph.get_operations() if op.type in state_op_types} for o...
Returns error message for colocation of state ops, or None if ok.
Below is the the instruction that describes the task: ### Input: Returns error message for colocation of state ops, or None if ok. ### Response: def find_state_op_colocation_error(graph, reported_tags=None): """Returns error message for colocation of state ops, or None if ok.""" state_op_types = list_registere...
def parse(msg): """ Helper method for parsing a Mongrel2 request string and returning a new `MongrelRequest` instance. """ sender, conn_id, path, rest = msg.split(' ', 3) headers, rest = tnetstring.pop(rest) body, _ = tnetstring.pop(rest) if type(headers)...
Helper method for parsing a Mongrel2 request string and returning a new `MongrelRequest` instance.
Below is the the instruction that describes the task: ### Input: Helper method for parsing a Mongrel2 request string and returning a new `MongrelRequest` instance. ### Response: def parse(msg): """ Helper method for parsing a Mongrel2 request string and returning a new `MongrelReque...
def load_secrets(self, secret_path): """render secrets into config object""" self._config = p_config.render_secrets(self.config_path, secret_path)
render secrets into config object
Below is the the instruction that describes the task: ### Input: render secrets into config object ### Response: def load_secrets(self, secret_path): """render secrets into config object""" self._config = p_config.render_secrets(self.config_path, secret_path)
def fix_timezone(df, freq, tz=None): """ set timezone for pandas """ index_name = df.index.name # fix timezone if isinstance(df.index[0], str): # timezone df exists if ("-" in df.index[0][-6:]) | ("+" in df.index[0][-6:]): df.index = pd.to_datetime(df.index, utc=False) ...
set timezone for pandas
Below is the the instruction that describes the task: ### Input: set timezone for pandas ### Response: def fix_timezone(df, freq, tz=None): """ set timezone for pandas """ index_name = df.index.name # fix timezone if isinstance(df.index[0], str): # timezone df exists if ("-" in df....
def set_annotation(self): """Appends the context's ``pending_symbol`` to its ``annotations`` sequence.""" assert self.pending_symbol is not None assert not self.value annotations = (_as_symbol(self.pending_symbol, is_symbol_value=False),) # pending_symbol becomes an annotation s...
Appends the context's ``pending_symbol`` to its ``annotations`` sequence.
Below is the the instruction that describes the task: ### Input: Appends the context's ``pending_symbol`` to its ``annotations`` sequence. ### Response: def set_annotation(self): """Appends the context's ``pending_symbol`` to its ``annotations`` sequence.""" assert self.pending_symbol is not None ...
def best_fit_plane(self): """Fits a plane to the point cloud using least squares. Returns ------- :obj:`tuple` of :obj:`numpy.ndarray` of float A normal vector to and point in the fitted plane. """ X = np.c_[self.x_coords, self.y_coords, np.ones(self.num_poin...
Fits a plane to the point cloud using least squares. Returns ------- :obj:`tuple` of :obj:`numpy.ndarray` of float A normal vector to and point in the fitted plane.
Below is the the instruction that describes the task: ### Input: Fits a plane to the point cloud using least squares. Returns ------- :obj:`tuple` of :obj:`numpy.ndarray` of float A normal vector to and point in the fitted plane. ### Response: def best_fit_plane(self): ...
def sargasso_chart (self): """ Make the sargasso plot """ # Config for the plot config = { 'id': 'sargasso_assignment_plot', 'title': 'Sargasso: Assigned Reads', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number of Reads' } #We ...
Make the sargasso plot
Below is the the instruction that describes the task: ### Input: Make the sargasso plot ### Response: def sargasso_chart (self): """ Make the sargasso plot """ # Config for the plot config = { 'id': 'sargasso_assignment_plot', 'title': 'Sargasso: Assigned Reads', ...
def __makeShowColumnFunction(self, column_idx): """ Creates a function that shows or hides a column.""" show_column = lambda checked: self.setColumnHidden(column_idx, not checked) return show_column
Creates a function that shows or hides a column.
Below is the the instruction that describes the task: ### Input: Creates a function that shows or hides a column. ### Response: def __makeShowColumnFunction(self, column_idx): """ Creates a function that shows or hides a column.""" show_column = lambda checked: self.setColumnHidden(column_idx, not ...
def log(self, x, base=2): """Computes the logarithm of x with the given base (the default base is 2).""" return self._format_result(log(float(x), base))
Computes the logarithm of x with the given base (the default base is 2).
Below is the the instruction that describes the task: ### Input: Computes the logarithm of x with the given base (the default base is 2). ### Response: def log(self, x, base=2): """Computes the logarithm of x with the given base (the default base is 2).""" return self._format_resu...
def get_all_firmwares(self, filter='', start=0, count=-1, query='', sort=''): """ Gets a list of firmware inventory across all servers. To filter the returned data, specify a filter expression to select a particular server model, component name, and/or component firmware version. Note: ...
Gets a list of firmware inventory across all servers. To filter the returned data, specify a filter expression to select a particular server model, component name, and/or component firmware version. Note: This method is available for API version 300 or later. Args: star...
Below is the the instruction that describes the task: ### Input: Gets a list of firmware inventory across all servers. To filter the returned data, specify a filter expression to select a particular server model, component name, and/or component firmware version. Note: This method is av...
def returner(ret): ''' Return data to an odbc server ''' conn = _get_conn(ret) cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, retval, id, success, full_ret) VALUES (?, ?, ?, ?, ?, ?)''' cur.execute( sql, ( ret['fun'], ...
Return data to an odbc server
Below is the the instruction that describes the task: ### Input: Return data to an odbc server ### Response: def returner(ret): ''' Return data to an odbc server ''' conn = _get_conn(ret) cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, retval, id, success, full_...
def enter_maintenance_mode(self): """ Put the service in maintenance mode. @return: Reference to the completed command. @since: API v2 """ cmd = self._cmd('enterMaintenanceMode') if cmd.success: self._update(_get_service(self._get_resource_root(), self._path())) return cmd
Put the service in maintenance mode. @return: Reference to the completed command. @since: API v2
Below is the the instruction that describes the task: ### Input: Put the service in maintenance mode. @return: Reference to the completed command. @since: API v2 ### Response: def enter_maintenance_mode(self): """ Put the service in maintenance mode. @return: Reference to the completed comman...
def do_bucket(self, count=1): '''Set self.bucket and return results. :param count: Number of rolls to make :return: List of tuples (total of roll, times it was rolled) ''' self._bucket = dict() for roll in self.roll.roll(count): self._bucket[roll] = self._buck...
Set self.bucket and return results. :param count: Number of rolls to make :return: List of tuples (total of roll, times it was rolled)
Below is the the instruction that describes the task: ### Input: Set self.bucket and return results. :param count: Number of rolls to make :return: List of tuples (total of roll, times it was rolled) ### Response: def do_bucket(self, count=1): '''Set self.bucket and return results. ...
def get_root(self, drive): """ Returns the root directory for the specified drive, creating it if necessary. """ drive = _my_normcase(drive) try: return self.Root[drive] except KeyError: root = RootDir(drive, self) self.Root[dri...
Returns the root directory for the specified drive, creating it if necessary.
Below is the the instruction that describes the task: ### Input: Returns the root directory for the specified drive, creating it if necessary. ### Response: def get_root(self, drive): """ Returns the root directory for the specified drive, creating it if necessary. """ ...
def enqueue(self, destination): """Enqueues given destination for processing. Given instance should be a valid destination. """ if not destination: raise BgpProcessorError('Invalid destination %s.' % destination) dest_queue = self._dest_queue # RtDest are qu...
Enqueues given destination for processing. Given instance should be a valid destination.
Below is the the instruction that describes the task: ### Input: Enqueues given destination for processing. Given instance should be a valid destination. ### Response: def enqueue(self, destination): """Enqueues given destination for processing. Given instance should be a valid destinatio...
def get_build_params(metadata): '''get_build_params uses get_build_metadata to retrieve corresponding meta data values for a build :param metadata: a list, each item a dictionary of metadata, in format: metadata = [{'key': 'repo_url', 'value': repo_url }, {'key': 'repo_id', 'value': repo_id ...
get_build_params uses get_build_metadata to retrieve corresponding meta data values for a build :param metadata: a list, each item a dictionary of metadata, in format: metadata = [{'key': 'repo_url', 'value': repo_url }, {'key': 'repo_id', 'value': repo_id }, {'key': 'credential'...
Below is the the instruction that describes the task: ### Input: get_build_params uses get_build_metadata to retrieve corresponding meta data values for a build :param metadata: a list, each item a dictionary of metadata, in format: metadata = [{'key': 'repo_url', 'value': repo_url }, {'key'...
def inverse_transform(self, sequences): """Transform a list of sequences from internal indexing into labels Parameters ---------- sequences : list List of sequences, each of which is one-dimensional array of integers in ``0, ..., n_states_ - 1``. ...
Transform a list of sequences from internal indexing into labels Parameters ---------- sequences : list List of sequences, each of which is one-dimensional array of integers in ``0, ..., n_states_ - 1``. Returns ------- sequences : list ...
Below is the the instruction that describes the task: ### Input: Transform a list of sequences from internal indexing into labels Parameters ---------- sequences : list List of sequences, each of which is one-dimensional array of integers in ``0, ..., n_state...
def col_iscat(df,col_name = None): """ Returns a list of columns that are of type 'category'. If col_name is specified, returns whether the column in the DataFrame is of type 'category' instead. Parameters: df - DataFrame DataFrame to check col_name - string, default None If specifi...
Returns a list of columns that are of type 'category'. If col_name is specified, returns whether the column in the DataFrame is of type 'category' instead. Parameters: df - DataFrame DataFrame to check col_name - string, default None If specified, this function will True if df[col_name]...
Below is the the instruction that describes the task: ### Input: Returns a list of columns that are of type 'category'. If col_name is specified, returns whether the column in the DataFrame is of type 'category' instead. Parameters: df - DataFrame DataFrame to check col_name - string, defau...
def nsorted( to_sort: Iterable[str], key: Optional[Callable[[str], Any]] = None ) -> List[str]: """Returns a naturally sorted list""" if key is None: key_callback = _natural_keys else: def key_callback(text: str) -> List[Any]: return _natural_keys(key(text)) # type: igno...
Returns a naturally sorted list
Below is the the instruction that describes the task: ### Input: Returns a naturally sorted list ### Response: def nsorted( to_sort: Iterable[str], key: Optional[Callable[[str], Any]] = None ) -> List[str]: """Returns a naturally sorted list""" if key is None: key_callback = _natural_keys ...
def content_to_html(content, article_id): """Returns artilce/page content as HTML""" def render_node(html, node, index): """Renders node as HTML""" if node['type'] == 'paragraph': return html + '<p>%s</p>' % node['data'] else: if node['type'] == 'ad': ...
Returns artilce/page content as HTML
Below is the the instruction that describes the task: ### Input: Returns artilce/page content as HTML ### Response: def content_to_html(content, article_id): """Returns artilce/page content as HTML""" def render_node(html, node, index): """Renders node as HTML""" if node['type'] == 'paragr...
def _set_tpvm(self, v, load=False): """ Setter method for tpvm, mapped from YANG variable /tpvm (container) If this variable is read-only (config: false) in the source YANG file, then _set_tpvm is considered as a private method. Backends looking to populate this variable should do so via calling...
Setter method for tpvm, mapped from YANG variable /tpvm (container) If this variable is read-only (config: false) in the source YANG file, then _set_tpvm is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_tpvm() directly.
Below is the the instruction that describes the task: ### Input: Setter method for tpvm, mapped from YANG variable /tpvm (container) If this variable is read-only (config: false) in the source YANG file, then _set_tpvm is considered as a private method. Backends looking to populate this variable should ...
def loaddata(self, path, site=None): """ Runs the Dango loaddata management command. By default, runs on only the current site. Pass site=all to run on all sites. """ site = site or self.genv.SITE r = self.local_renderer r.env._loaddata_path = path ...
Runs the Dango loaddata management command. By default, runs on only the current site. Pass site=all to run on all sites.
Below is the the instruction that describes the task: ### Input: Runs the Dango loaddata management command. By default, runs on only the current site. Pass site=all to run on all sites. ### Response: def loaddata(self, path, site=None): """ Runs the Dango loaddata management comm...
def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self.text = text if...
Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self
Below is the the instruction that describes the task: ### Input: Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self ### Response: def start(self, text=None): ...
def printo(msg, encoding=None, errors='replace', std_type='stdout'): """Write msg on stdout. If no encoding is specified the detected encoding of stdout is used. If the encoding can't encode some chars they are replaced by '?' :param msg: message :type msg: unicode on python2 | str on python3 "...
Write msg on stdout. If no encoding is specified the detected encoding of stdout is used. If the encoding can't encode some chars they are replaced by '?' :param msg: message :type msg: unicode on python2 | str on python3
Below is the the instruction that describes the task: ### Input: Write msg on stdout. If no encoding is specified the detected encoding of stdout is used. If the encoding can't encode some chars they are replaced by '?' :param msg: message :type msg: unicode on python2 | str on python3 ### Response...
def unshare(self, group_id, **kwargs): """Delete a shared project link within a group. Args: group_id (int): ID of the group. **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct ...
Delete a shared project link within a group. Args: group_id (int): ID of the group. **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabDeleteError: If the server failed to p...
Below is the the instruction that describes the task: ### Input: Delete a shared project link within a group. Args: group_id (int): ID of the group. **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is...
def getPeopleTags(self): """ Return a sequence of tags which have been applied to L{Person} items. @rtype: C{set} """ query = self.store.query( Tag, Tag.object == Person.storeID) return set(query.getColumn('name').distinct())
Return a sequence of tags which have been applied to L{Person} items. @rtype: C{set}
Below is the the instruction that describes the task: ### Input: Return a sequence of tags which have been applied to L{Person} items. @rtype: C{set} ### Response: def getPeopleTags(self): """ Return a sequence of tags which have been applied to L{Person} items. @rtype: C{set} ...
def get_keys(self, bucket, timeout=None): """ Fetch a list of keys for the bucket """ bucket_type = self._get_bucket_type(bucket.bucket_type) url = self.key_list_path(bucket.name, bucket_type=bucket_type, timeout=timeout) status, _, body =...
Fetch a list of keys for the bucket
Below is the the instruction that describes the task: ### Input: Fetch a list of keys for the bucket ### Response: def get_keys(self, bucket, timeout=None): """ Fetch a list of keys for the bucket """ bucket_type = self._get_bucket_type(bucket.bucket_type) url = self.key_lis...
def within_set(df, items=None): """ Assert that df is a subset of items Parameters ========== df : DataFrame items : dict mapping of columns (k) to array-like of values (v) that ``df[k]`` is expected to be a subset of Returns ======= df : DataFrame """ for k, v ...
Assert that df is a subset of items Parameters ========== df : DataFrame items : dict mapping of columns (k) to array-like of values (v) that ``df[k]`` is expected to be a subset of Returns ======= df : DataFrame
Below is the the instruction that describes the task: ### Input: Assert that df is a subset of items Parameters ========== df : DataFrame items : dict mapping of columns (k) to array-like of values (v) that ``df[k]`` is expected to be a subset of Returns ======= df : DataFr...
def optimized(code, silent=True, ignore_errors=True): """Performs optimizations on already parsed code.""" return constant_fold(code, silent=silent, ignore_errors=ignore_errors)
Performs optimizations on already parsed code.
Below is the the instruction that describes the task: ### Input: Performs optimizations on already parsed code. ### Response: def optimized(code, silent=True, ignore_errors=True): """Performs optimizations on already parsed code.""" return constant_fold(code, silent=silent, ignore_errors=ignore_errors)
def discrete_mean_curvature_measure(mesh, points, radius): """ Return the discrete mean curvature measure of a sphere centered at a point as detailed in 'Restricted Delaunay triangulations and normal cycle', Cohen-Steiner and Morvan. Parameters ---------- points : (n,3) float, list of point...
Return the discrete mean curvature measure of a sphere centered at a point as detailed in 'Restricted Delaunay triangulations and normal cycle', Cohen-Steiner and Morvan. Parameters ---------- points : (n,3) float, list of points in space radius : float, the sphere radius Returns -----...
Below is the the instruction that describes the task: ### Input: Return the discrete mean curvature measure of a sphere centered at a point as detailed in 'Restricted Delaunay triangulations and normal cycle', Cohen-Steiner and Morvan. Parameters ---------- points : (n,3) float, list of points ...
def per_chat_id_in(s, types='all'): """ :param s: a list or set of chat id :param types: ``all`` or a list of chat types (``private``, ``group``, ``channel``) :return: a seeder function that returns the chat id only if the chat id is in ``s`` and chat type is in ``types...
:param s: a list or set of chat id :param types: ``all`` or a list of chat types (``private``, ``group``, ``channel``) :return: a seeder function that returns the chat id only if the chat id is in ``s`` and chat type is in ``types``.
Below is the the instruction that describes the task: ### Input: :param s: a list or set of chat id :param types: ``all`` or a list of chat types (``private``, ``group``, ``channel``) :return: a seeder function that returns the chat id only if the chat id is in ``s`` and ch...
def open_mask(fn:PathOrStr, div=False, convert_mode='L', after_open:Callable=None)->ImageSegment: "Return `ImageSegment` object create from mask in file `fn`. If `div`, divides pixel values by 255." return open_image(fn, div=div, convert_mode=convert_mode, cls=ImageSegment, after_open=after_open)
Return `ImageSegment` object create from mask in file `fn`. If `div`, divides pixel values by 255.
Below is the the instruction that describes the task: ### Input: Return `ImageSegment` object create from mask in file `fn`. If `div`, divides pixel values by 255. ### Response: def open_mask(fn:PathOrStr, div=False, convert_mode='L', after_open:Callable=None)->ImageSegment: "Return `ImageSegment` object creat...
def maf(genotypes): """Computes the MAF and returns a boolean indicating if the minor allele is currently the coded allele. """ warnings.warn("deprecated: use 'Genotypes.maf'", DeprecationWarning) g = genotypes.genotypes maf = np.nansum(g) / (2 * np.sum(~np.isnan(g))) if maf > 0.5: ...
Computes the MAF and returns a boolean indicating if the minor allele is currently the coded allele.
Below is the the instruction that describes the task: ### Input: Computes the MAF and returns a boolean indicating if the minor allele is currently the coded allele. ### Response: def maf(genotypes): """Computes the MAF and returns a boolean indicating if the minor allele is currently the coded allele....
def make_pixel_mask_from_col_row(column, row, default=0, value=1): '''Generate mask from column and row lists Parameters ---------- column : iterable, int List of colums values. row : iterable, int List of row values. default : int Value of pixels that are not ...
Generate mask from column and row lists Parameters ---------- column : iterable, int List of colums values. row : iterable, int List of row values. default : int Value of pixels that are not selected by the mask. value : int Value of pixels that are se...
Below is the the instruction that describes the task: ### Input: Generate mask from column and row lists Parameters ---------- column : iterable, int List of colums values. row : iterable, int List of row values. default : int Value of pixels that are not select...
def all_units_idle(self): """Return True if all units are idle. """ for unit in self.units.values(): unit_status = unit.data['agent-status']['current'] if unit_status != 'idle': return False return True
Return True if all units are idle.
Below is the the instruction that describes the task: ### Input: Return True if all units are idle. ### Response: def all_units_idle(self): """Return True if all units are idle. """ for unit in self.units.values(): unit_status = unit.data['agent-status']['current'] ...
def command(self, dbname, spec, slave_ok=False, read_preference=ReadPreference.PRIMARY, codec_options=DEFAULT_CODEC_OPTIONS, check=True, allowable_errors=None, check_keys=False, read_concern=None, write_concern=None, parse_w...
Execute a command or raise an error. :Parameters: - `dbname`: name of the database on which to run the command - `spec`: a command document as a dict, SON, or mapping object - `slave_ok`: whether to set the SlaveOkay wire protocol bit - `read_preference`: a read preferen...
Below is the the instruction that describes the task: ### Input: Execute a command or raise an error. :Parameters: - `dbname`: name of the database on which to run the command - `spec`: a command document as a dict, SON, or mapping object - `slave_ok`: whether to set the Slave...
def _URange(s): """Converts string to Unicode range. '0001..0003' => [1, 2, 3]. '0001' => [1]. Args: s: string to convert Returns: Unicode range Raises: InputError: the string is not a valid Unicode range. """ a = s.split("..") if len(a) == 1: return [_UInt(a[0])] if len(a) =...
Converts string to Unicode range. '0001..0003' => [1, 2, 3]. '0001' => [1]. Args: s: string to convert Returns: Unicode range Raises: InputError: the string is not a valid Unicode range.
Below is the the instruction that describes the task: ### Input: Converts string to Unicode range. '0001..0003' => [1, 2, 3]. '0001' => [1]. Args: s: string to convert Returns: Unicode range Raises: InputError: the string is not a valid Unicode range. ### Response: def _URange(s): "...
def is_list_of_list(item): """ check whether the item is list (tuple) and consist of list (tuple) elements """ if ( type(item) in (list, tuple) and len(item) and isinstance(item[0], (list, tuple)) ): return True return False
check whether the item is list (tuple) and consist of list (tuple) elements
Below is the the instruction that describes the task: ### Input: check whether the item is list (tuple) and consist of list (tuple) elements ### Response: def is_list_of_list(item): """ check whether the item is list (tuple) and consist of list (tuple) elements """ if ( type(item) i...