code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def post_customer_preferences(self, **kwargs): # noqa: E501 """Update selected fields of customer preferences # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api....
Update selected fields of customer preferences # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.post_customer_preferences(async_req=True) >>> result = thread.ge...
Below is the the instruction that describes the task: ### Input: Update selected fields of customer preferences # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.pos...
def most_populated(adf): """ Looks at each column, using the one with the most values Honours the Trump override/failsafe logic. """ # just look at the feeds, ignore overrides and failsafes: feeds_only = adf[adf.columns[1:-1]] # find the most populated feed cnt_...
Looks at each column, using the one with the most values Honours the Trump override/failsafe logic.
Below is the the instruction that describes the task: ### Input: Looks at each column, using the one with the most values Honours the Trump override/failsafe logic. ### Response: def most_populated(adf): """ Looks at each column, using the one with the most values Honours the Trump ...
async def download(resource_url): ''' Download given resource_url ''' scheme = resource_url.parsed.scheme if scheme in ('http', 'https'): await download_http(resource_url) elif scheme in ('git', 'git+https', 'git+http'): await download_git(resource_url) else: raise Va...
Download given resource_url
Below is the the instruction that describes the task: ### Input: Download given resource_url ### Response: async def download(resource_url): ''' Download given resource_url ''' scheme = resource_url.parsed.scheme if scheme in ('http', 'https'): await download_http(resource_url) elif...
def map(self, mapper): """ Map categories using input correspondence (dict, Series, or function). Maps the categories to new categories. If the mapping correspondence is one-to-one the result is a :class:`~pandas.Categorical` which has the same order property as the original, ot...
Map categories using input correspondence (dict, Series, or function). Maps the categories to new categories. If the mapping correspondence is one-to-one the result is a :class:`~pandas.Categorical` which has the same order property as the original, otherwise a :class:`~pandas.Index` is...
Below is the the instruction that describes the task: ### Input: Map categories using input correspondence (dict, Series, or function). Maps the categories to new categories. If the mapping correspondence is one-to-one the result is a :class:`~pandas.Categorical` which has the same order pr...
def getImageForBulkExpressions(self, retina_name, body, get_fingerprint=None, image_scalar=2, plot_shape="circle", sparsity=1.0): """Bulk get images for expressions Args: retina_name, str: The retina name (required) body, ExpressionOperation: The JSON encoded expression to be eva...
Bulk get images for expressions Args: retina_name, str: The retina name (required) body, ExpressionOperation: The JSON encoded expression to be evaluated (required) get_fingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) ...
Below is the the instruction that describes the task: ### Input: Bulk get images for expressions Args: retina_name, str: The retina name (required) body, ExpressionOperation: The JSON encoded expression to be evaluated (required) get_fingerprint, bool: Configure if the fi...
def add_spark_slave(self, master, slave, configure): """ add spark slave :return: """ # go to master server, add config self.reset_server_env(master, configure) with cd(bigdata_conf.spark_home): if not exists('conf/spark-env.sh'): sudo(...
add spark slave :return:
Below is the the instruction that describes the task: ### Input: add spark slave :return: ### Response: def add_spark_slave(self, master, slave, configure): """ add spark slave :return: """ # go to master server, add config self.reset_server_env(master, confi...
def from_path(cls, spec_path): """ Load a specification from a path. :param FilePath spec_path: The location of the specification to read. """ with spec_path.open() as spec_file: return cls.from_document(load(spec_file))
Load a specification from a path. :param FilePath spec_path: The location of the specification to read.
Below is the the instruction that describes the task: ### Input: Load a specification from a path. :param FilePath spec_path: The location of the specification to read. ### Response: def from_path(cls, spec_path): """ Load a specification from a path. :param FilePath spec_path: Th...
def remove_distribution(self, dist): """ Remove a distribution from the finder. This will update internal information about who provides what. :param dist: The distribution to remove. """ logger.debug('removing distribution %s', dist) name = dist.key del s...
Remove a distribution from the finder. This will update internal information about who provides what. :param dist: The distribution to remove.
Below is the the instruction that describes the task: ### Input: Remove a distribution from the finder. This will update internal information about who provides what. :param dist: The distribution to remove. ### Response: def remove_distribution(self, dist): """ Remove a distributio...
def _year_month_delta_from_elements(elements): """ Return a tuple of (years, months) from a dict of date elements. Accepts a dict containing any of the following: - years - months Example: >>> _year_month_delta_from_elements({'years': 2, 'months': 14}) (3, 2) """ return di...
Return a tuple of (years, months) from a dict of date elements. Accepts a dict containing any of the following: - years - months Example: >>> _year_month_delta_from_elements({'years': 2, 'months': 14}) (3, 2)
Below is the the instruction that describes the task: ### Input: Return a tuple of (years, months) from a dict of date elements. Accepts a dict containing any of the following: - years - months Example: >>> _year_month_delta_from_elements({'years': 2, 'months': 14}) (3, 2) ### Respons...
def _nuclear_factor(self, Tp): """ Compute nuclear enhancement factor """ sigmaRpp = 10 * np.pi * 1e-27 sigmainel = self._sigma_inel(Tp) sigmainel0 = self._sigma_inel(1e3) # at 1e3 GeV f = sigmainel / sigmainel0 f2 = np.where(f > 1, f, 1.0) G = 1....
Compute nuclear enhancement factor
Below is the the instruction that describes the task: ### Input: Compute nuclear enhancement factor ### Response: def _nuclear_factor(self, Tp): """ Compute nuclear enhancement factor """ sigmaRpp = 10 * np.pi * 1e-27 sigmainel = self._sigma_inel(Tp) sigmainel0 = sel...
def metric_crud(client, to_delete): """Metric CRUD.""" METRIC_NAME = "robots-%d" % (_millis(),) DESCRIPTION = "Robots all up in your server" FILTER = "logName:apache-access AND textPayload:robot" UPDATED_FILTER = "textPayload:robot" UPDATED_DESCRIPTION = "Danger, Will Robinson!" # [START cl...
Metric CRUD.
Below is the the instruction that describes the task: ### Input: Metric CRUD. ### Response: def metric_crud(client, to_delete): """Metric CRUD.""" METRIC_NAME = "robots-%d" % (_millis(),) DESCRIPTION = "Robots all up in your server" FILTER = "logName:apache-access AND textPayload:robot" UPDATED...
def _on_ws_message(self, ws, message): """ on_message callback of websocket class, load the message into a dict and then update an Ack Object with the results :param ws: web socket connection that the message was received on :param message: web socket message in text form ...
on_message callback of websocket class, load the message into a dict and then update an Ack Object with the results :param ws: web socket connection that the message was received on :param message: web socket message in text form :return: None
Below is the the instruction that describes the task: ### Input: on_message callback of websocket class, load the message into a dict and then update an Ack Object with the results :param ws: web socket connection that the message was received on :param message: web socket message in text fo...
def _parse_complement(self, tokens): """ Parses a complement Complement ::= 'complement' '(' SuperRange ')' """ tokens.pop(0) # Pop 'complement' tokens.pop(0) # Pop '(' res = self._parse_nested_interval(tokens) tokens.pop(0) # Pop ')' res.switch_strand...
Parses a complement Complement ::= 'complement' '(' SuperRange ')'
Below is the the instruction that describes the task: ### Input: Parses a complement Complement ::= 'complement' '(' SuperRange ')' ### Response: def _parse_complement(self, tokens): """ Parses a complement Complement ::= 'complement' '(' SuperRange ')' """ tokens.pop(0) ...
def parse_value(self, value): """ Convert value string to float for reporting """ value = value.strip() # Skip missing sensors if value == 'na': return None # Try just getting the float value try: return float(value) excep...
Convert value string to float for reporting
Below is the the instruction that describes the task: ### Input: Convert value string to float for reporting ### Response: def parse_value(self, value): """ Convert value string to float for reporting """ value = value.strip() # Skip missing sensors if value == 'na'...
def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaul...
Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019....
Below is the the instruction that describes the task: ### Input: Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username ...
def _place_ticks_vertical(self): """Display the ticks for a vertical slider.""" for tick, label in zip(self.ticks, self.ticklabels): y = self.convert_to_pixels(tick) label.place_configure(y=y)
Display the ticks for a vertical slider.
Below is the the instruction that describes the task: ### Input: Display the ticks for a vertical slider. ### Response: def _place_ticks_vertical(self): """Display the ticks for a vertical slider.""" for tick, label in zip(self.ticks, self.ticklabels): y = self.convert_to_pixels(tick) ...
def isUrl(urlString): """ Attempts to return whether a given URL string is valid by checking for the presence of the URL scheme and netloc using the urlparse module, and then using a regex. From http://stackoverflow.com/questions/7160737/ """ parsed = urlparse.urlparse(urlString) urlpar...
Attempts to return whether a given URL string is valid by checking for the presence of the URL scheme and netloc using the urlparse module, and then using a regex. From http://stackoverflow.com/questions/7160737/
Below is the the instruction that describes the task: ### Input: Attempts to return whether a given URL string is valid by checking for the presence of the URL scheme and netloc using the urlparse module, and then using a regex. From http://stackoverflow.com/questions/7160737/ ### Response: def isUrl(...
def reindex(self, force=False, background=True): """Start jira re-indexing. Returns True if reindexing is in progress or not needed, or False. If you call reindex() without any parameters it will perform a background reindex only if JIRA thinks it should do it. :param force: reindex even if JI...
Start jira re-indexing. Returns True if reindexing is in progress or not needed, or False. If you call reindex() without any parameters it will perform a background reindex only if JIRA thinks it should do it. :param force: reindex even if JIRA doesn't say this is needed, False by default. :pa...
Below is the the instruction that describes the task: ### Input: Start jira re-indexing. Returns True if reindexing is in progress or not needed, or False. If you call reindex() without any parameters it will perform a background reindex only if JIRA thinks it should do it. :param force: reindex e...
def plot_kurtosis(self, f_start=None, f_stop=None, if_id=0, **kwargs): """ Plot kurtosis Args: f_start (float): start frequency, in MHz f_stop (float): stop frequency, in MHz kwargs: keyword args to be passed to matplotlib imshow() """ ax = plt.gca()...
Plot kurtosis Args: f_start (float): start frequency, in MHz f_stop (float): stop frequency, in MHz kwargs: keyword args to be passed to matplotlib imshow()
Below is the the instruction that describes the task: ### Input: Plot kurtosis Args: f_start (float): start frequency, in MHz f_stop (float): stop frequency, in MHz kwargs: keyword args to be passed to matplotlib imshow() ### Response: def plot_kurtosis(self, f_start=N...
def create_spot_requests(self, price, instance_type='default', root_device_type='ebs', size='default', vol_type='gp2', delete_on_termination=False...
Request creation of one or more EC2 spot instances. :param size: :param vol_type: :param delete_on_termination: :param root_device_type: The type of the root device. :type root_device_type: str :param price: Max price to pay for spot instance per hour. :type pric...
Below is the the instruction that describes the task: ### Input: Request creation of one or more EC2 spot instances. :param size: :param vol_type: :param delete_on_termination: :param root_device_type: The type of the root device. :type root_device_type: str :param p...
def update(self, other=None, **kwargs): '''Takes the same arguments as the update method in the builtin dict class. However, this version returns a new ImmutableDict instead of modifying in-place.''' copydict = ImmutableDict() if other: vallist = [(hash(key), (key, ot...
Takes the same arguments as the update method in the builtin dict class. However, this version returns a new ImmutableDict instead of modifying in-place.
Below is the the instruction that describes the task: ### Input: Takes the same arguments as the update method in the builtin dict class. However, this version returns a new ImmutableDict instead of modifying in-place. ### Response: def update(self, other=None, **kwargs): '''Takes the same ...
def netflowv9_defragment(plist, verb=1): """Process all NetflowV9/10 Packets to match IDs of the DataFlowsets with the Headers params: - plist: the list of mixed NetflowV9/10 packets. - verb: verbose print (0/1) """ if not isinstance(plist, (PacketList, list)): plist = [plist] ...
Process all NetflowV9/10 Packets to match IDs of the DataFlowsets with the Headers params: - plist: the list of mixed NetflowV9/10 packets. - verb: verbose print (0/1)
Below is the the instruction that describes the task: ### Input: Process all NetflowV9/10 Packets to match IDs of the DataFlowsets with the Headers params: - plist: the list of mixed NetflowV9/10 packets. - verb: verbose print (0/1) ### Response: def netflowv9_defragment(plist, verb=1): """P...
def getch(): """ get character. waiting for key """ try: termios.tcsetattr(_fd, termios.TCSANOW, _new_settings) ch = sys.stdin.read(1) finally: termios.tcsetattr(_fd, termios.TCSADRAIN, _old_settings) return ch
get character. waiting for key
Below is the the instruction that describes the task: ### Input: get character. waiting for key ### Response: def getch(): """ get character. waiting for key """ try: termios.tcsetattr(_fd, termios.TCSANOW, _new_settings) ch = sys.stdin.read(1) finally: termios.tcsetattr...
def score_samples(self, X, lengths=None): """Compute the log probability under the model and compute posteriors. Parameters ---------- X : array-like, shape (n_samples, n_features) Feature matrix of individual samples. lengths : array-like of integers, shape (n_sequ...
Compute the log probability under the model and compute posteriors. Parameters ---------- X : array-like, shape (n_samples, n_features) Feature matrix of individual samples. lengths : array-like of integers, shape (n_sequences, ), optional Lengths of the individ...
Below is the the instruction that describes the task: ### Input: Compute the log probability under the model and compute posteriors. Parameters ---------- X : array-like, shape (n_samples, n_features) Feature matrix of individual samples. lengths : array-like of integer...
def wrap_rethink_errors(func_, *args, **kwargs): """ Wraps rethinkdb specific errors as builtin/Brain errors :param func_: <function> to call :param args: <tuple> positional arguments :param kwargs: <dict> keyword arguments :return: inherits from the called function """ try: re...
Wraps rethinkdb specific errors as builtin/Brain errors :param func_: <function> to call :param args: <tuple> positional arguments :param kwargs: <dict> keyword arguments :return: inherits from the called function
Below is the the instruction that describes the task: ### Input: Wraps rethinkdb specific errors as builtin/Brain errors :param func_: <function> to call :param args: <tuple> positional arguments :param kwargs: <dict> keyword arguments :return: inherits from the called function ### Response: def ...
def get_languages_from_model(app_label, model_label): """ Get the languages configured for the current model :param model_label: :param app_label: :return: """ try: mod_lan = TransModelLanguage.objects.filter(model='{} - {}'.format(app_label, model_la...
Get the languages configured for the current model :param model_label: :param app_label: :return:
Below is the the instruction that describes the task: ### Input: Get the languages configured for the current model :param model_label: :param app_label: :return: ### Response: def get_languages_from_model(app_label, model_label): """ Get the languages configured for the cu...
def getresponse(self): """Wait for and return a HTTP response. The return value will be a :class:`HttpMessage`. When this method returns only the response header has been read. The response body can be read using :meth:`~gruvi.Stream.read` and similar methods on the message :att...
Wait for and return a HTTP response. The return value will be a :class:`HttpMessage`. When this method returns only the response header has been read. The response body can be read using :meth:`~gruvi.Stream.read` and similar methods on the message :attr:`~HttpMessage.body`. No...
Below is the the instruction that describes the task: ### Input: Wait for and return a HTTP response. The return value will be a :class:`HttpMessage`. When this method returns only the response header has been read. The response body can be read using :meth:`~gruvi.Stream.read` and similar ...
def InternalExchange(self, cmd, payload_in): """Sends and receives a message from the device.""" # make a copy because we destroy it below self.logger.debug('payload: ' + str(list(payload_in))) payload = bytearray() payload[:] = payload_in for _ in range(2): self.InternalSend(cmd, payload)...
Sends and receives a message from the device.
Below is the the instruction that describes the task: ### Input: Sends and receives a message from the device. ### Response: def InternalExchange(self, cmd, payload_in): """Sends and receives a message from the device.""" # make a copy because we destroy it below self.logger.debug('payload: ' + str(lis...
def widgetValue( widget ): """ Returns the value for the inputed widget based on its type. :param widget | <QWidget> :return (<variant> value, <bool> success) """ for wtype in reversed(_widgetValueTypes): if isinstance(widget, wtype[0]): try: ...
Returns the value for the inputed widget based on its type. :param widget | <QWidget> :return (<variant> value, <bool> success)
Below is the the instruction that describes the task: ### Input: Returns the value for the inputed widget based on its type. :param widget | <QWidget> :return (<variant> value, <bool> success) ### Response: def widgetValue( widget ): """ Returns the value for the inputed wi...
def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ if len(self.actual_arguments) < 1: return self.print_help() if self.has_option([u"-e", u"--examples"]): return self.print_examples(False) ...
Perform command and return the appropriate exit code. :rtype: int
Below is the the instruction that describes the task: ### Input: Perform command and return the appropriate exit code. :rtype: int ### Response: def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ if len(self.actual_...
def as_cnpj(numero): """Formata um número de CNPJ. Se o número não for um CNPJ válido apenas retorna o argumento sem qualquer modificação. """ _num = digitos(numero) if is_cnpj(_num): return '{}.{}.{}/{}-{}'.format( _num[:2], _num[2:5], _num[5:8], _num[8:12], _num[12:]) r...
Formata um número de CNPJ. Se o número não for um CNPJ válido apenas retorna o argumento sem qualquer modificação.
Below is the the instruction that describes the task: ### Input: Formata um número de CNPJ. Se o número não for um CNPJ válido apenas retorna o argumento sem qualquer modificação. ### Response: def as_cnpj(numero): """Formata um número de CNPJ. Se o número não for um CNPJ válido apenas retorna o argume...
def direction(self, direction): """ set the direction """ if not isinstance(direction, str): raise TypeError("direction must be of type str") accepted_values = ['i', 'x', 'y', 'z', 's', 'c'] if direction not in accepted_values: raise ValueError("m...
set the direction
Below is the the instruction that describes the task: ### Input: set the direction ### Response: def direction(self, direction): """ set the direction """ if not isinstance(direction, str): raise TypeError("direction must be of type str") accepted_values = ['i',...
def recvSecurityList(self, data): """ Read security list packet send from server to client @param data: Stream that contains well formed packet """ securityList = [] while data.dataLen() > 0: securityElement = UInt8() data.readType(securityElement)...
Read security list packet send from server to client @param data: Stream that contains well formed packet
Below is the the instruction that describes the task: ### Input: Read security list packet send from server to client @param data: Stream that contains well formed packet ### Response: def recvSecurityList(self, data): """ Read security list packet send from server to client @param ...
def coerce_date_dict(date_dict): """ given a dictionary (presumed to be from request.GET) it returns a tuple that represents a date. It will return from year down to seconds until one is not found. ie if year, month, and seconds are in the dictionary, only year and month will be returned, the rest ...
given a dictionary (presumed to be from request.GET) it returns a tuple that represents a date. It will return from year down to seconds until one is not found. ie if year, month, and seconds are in the dictionary, only year and month will be returned, the rest will be returned as min. If none of the p...
Below is the the instruction that describes the task: ### Input: given a dictionary (presumed to be from request.GET) it returns a tuple that represents a date. It will return from year down to seconds until one is not found. ie if year, month, and seconds are in the dictionary, only year and month wil...
def _onDecorator(self, name, line, pos, absPosition): """Memorizes a function or a class decorator""" # A class or a function must be on the top of the stack d = Decorator(name, line, pos, absPosition) if self.__lastDecorators is None: self.__lastDecorators = [d] else...
Memorizes a function or a class decorator
Below is the the instruction that describes the task: ### Input: Memorizes a function or a class decorator ### Response: def _onDecorator(self, name, line, pos, absPosition): """Memorizes a function or a class decorator""" # A class or a function must be on the top of the stack d = Decorato...
def lsf_stable(filt): """ Tests whether the given filter is stable or not by using the Line Spectral Frequencies (LSF) of the given filter. Needs NumPy. Parameters ---------- filt : A LTI filter as a LinearFilter object. Returns ------- A boolean that is true only when the LSF values from forwar...
Tests whether the given filter is stable or not by using the Line Spectral Frequencies (LSF) of the given filter. Needs NumPy. Parameters ---------- filt : A LTI filter as a LinearFilter object. Returns ------- A boolean that is true only when the LSF values from forward and backward prediction fi...
Below is the the instruction that describes the task: ### Input: Tests whether the given filter is stable or not by using the Line Spectral Frequencies (LSF) of the given filter. Needs NumPy. Parameters ---------- filt : A LTI filter as a LinearFilter object. Returns ------- A boolean that is tr...
def get_admins(self, account_id, params={}): """ Return a list of the admins in the account. https://canvas.instructure.com/doc/api/admins.html#method.admins.index """ url = ADMINS_API.format(account_id) admins = [] for data in self._get_paged_resource(url, para...
Return a list of the admins in the account. https://canvas.instructure.com/doc/api/admins.html#method.admins.index
Below is the the instruction that describes the task: ### Input: Return a list of the admins in the account. https://canvas.instructure.com/doc/api/admins.html#method.admins.index ### Response: def get_admins(self, account_id, params={}): """ Return a list of the admins in the account. ...
def mi(mi, iq=None, pl=None): # pylint: disable=redefined-outer-name """ This function is a wrapper for :meth:`~pywbem.WBEMConnection.ModifyInstance`. Modify the property values of an instance. Parameters: mi (:class:`~pywbem.CIMInstance`): Modified instance, also indicating i...
This function is a wrapper for :meth:`~pywbem.WBEMConnection.ModifyInstance`. Modify the property values of an instance. Parameters: mi (:class:`~pywbem.CIMInstance`): Modified instance, also indicating its instance path. The properties defined in this object specify the new pr...
Below is the the instruction that describes the task: ### Input: This function is a wrapper for :meth:`~pywbem.WBEMConnection.ModifyInstance`. Modify the property values of an instance. Parameters: mi (:class:`~pywbem.CIMInstance`): Modified instance, also indicating its instance path...
def user_organization_membership_create(self, user_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/organization_memberships#create-membership" api_path = "/api/v2/users/{user_id}/organization_memberships.json" api_path = api_path.format(user_id=user_id) return self...
https://developer.zendesk.com/rest_api/docs/core/organization_memberships#create-membership
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/core/organization_memberships#create-membership ### Response: def user_organization_membership_create(self, user_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/organization_m...
def parse_instancepath(parser, event, node): #pylint: disable=unused-argument """Parse the CIM/XML INSTANCEPATH element and return an instancname <!ELEMENT INSTANCEPATH (NAMESPACEPATH, INSTANCENAME)> """ (next_event, next_node) = six.next(parser) if not _is_start(next_event, next_no...
Parse the CIM/XML INSTANCEPATH element and return an instancname <!ELEMENT INSTANCEPATH (NAMESPACEPATH, INSTANCENAME)>
Below is the the instruction that describes the task: ### Input: Parse the CIM/XML INSTANCEPATH element and return an instancname <!ELEMENT INSTANCEPATH (NAMESPACEPATH, INSTANCENAME)> ### Response: def parse_instancepath(parser, event, node): #pylint: disable=unused-argument """Parse the CIM...
def geo_distance(a, b): """Distance between two geo points in km. (p.x = long, p.y = lat)""" a_y = radians(a.y) b_y = radians(b.y) delta_x = radians(a.x - b.x) cos_x = (sin(a_y) * sin(b_y) + cos(a_y) * cos(b_y) * cos(delta_x)) return acos(cos_x) * earth_radius_km
Distance between two geo points in km. (p.x = long, p.y = lat)
Below is the the instruction that describes the task: ### Input: Distance between two geo points in km. (p.x = long, p.y = lat) ### Response: def geo_distance(a, b): """Distance between two geo points in km. (p.x = long, p.y = lat)""" a_y = radians(a.y) b_y = radians(b.y) delta_x = radians(a.x - b....
def _poll(self) -> None: """Check the status of the wrapped running subprocess. Note: This should only be called on currently-running tasks. """ if self._subprocess is None: raise SublemonLifetimeError( 'Attempted to poll a non-active subprocess'...
Check the status of the wrapped running subprocess. Note: This should only be called on currently-running tasks.
Below is the the instruction that describes the task: ### Input: Check the status of the wrapped running subprocess. Note: This should only be called on currently-running tasks. ### Response: def _poll(self) -> None: """Check the status of the wrapped running subprocess. Note:...
def get_templates(self): '''list templates in the builder bundle library. If a name is provided, look it up ''' base = 'https://singularityhub.github.io/builders' base = self._get_and_update_setting('SREGISTRY_BUILDER_REPO', base) base = "%s/configs.json" %base return self._get(base)
list templates in the builder bundle library. If a name is provided, look it up
Below is the the instruction that describes the task: ### Input: list templates in the builder bundle library. If a name is provided, look it up ### Response: def get_templates(self): '''list templates in the builder bundle library. If a name is provided, look it up ''' base = 'https://...
def multiplicity(self): """ Returns the multiplicity of a defect site within the structure (needed for concentration analysis) """ sga = SpacegroupAnalyzer(self.bulk_structure) periodic_struc = sga.get_symmetrized_structure() poss_deflist = sorted( periodic_st...
Returns the multiplicity of a defect site within the structure (needed for concentration analysis)
Below is the the instruction that describes the task: ### Input: Returns the multiplicity of a defect site within the structure (needed for concentration analysis) ### Response: def multiplicity(self): """ Returns the multiplicity of a defect site within the structure (needed for concentration anal...
def next_offsets(self): # type: (Descriptor) -> Offsets """Retrieve the next offsets :param Descriptor self: this :rtype: Offsets :return: upload offsets """ resume_bytes = self._resume() with self._meta_lock: if self._chunk_num >= self._total_...
Retrieve the next offsets :param Descriptor self: this :rtype: Offsets :return: upload offsets
Below is the the instruction that describes the task: ### Input: Retrieve the next offsets :param Descriptor self: this :rtype: Offsets :return: upload offsets ### Response: def next_offsets(self): # type: (Descriptor) -> Offsets """Retrieve the next offsets :param D...
def fetchmany(self, *args, **kwargs): """ Analogous to :any:`sqlite3.Cursor.fetchmany`. Works only in single cursor mode. """ if not self.single_cursor_mode: raise S3MError("Calling Connection.fetchmany() while not in single cursor mode") return sel...
Analogous to :any:`sqlite3.Cursor.fetchmany`. Works only in single cursor mode.
Below is the the instruction that describes the task: ### Input: Analogous to :any:`sqlite3.Cursor.fetchmany`. Works only in single cursor mode. ### Response: def fetchmany(self, *args, **kwargs): """ Analogous to :any:`sqlite3.Cursor.fetchmany`. Works only in single c...
def compare_adjs(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as adjectives return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 ...
compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as adjectives return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural for...
Below is the the instruction that describes the task: ### Input: compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as adjectives return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plura...
def coerce(self, value): """Convert text values into integer values. Args: value (str or int): The value to coerce. Raises: TypeError: If the value is not an int or string. ValueError: If the value is not int or an acceptable value. Return...
Convert text values into integer values. Args: value (str or int): The value to coerce. Raises: TypeError: If the value is not an int or string. ValueError: If the value is not int or an acceptable value. Returns: int: The integer valu...
Below is the the instruction that describes the task: ### Input: Convert text values into integer values. Args: value (str or int): The value to coerce. Raises: TypeError: If the value is not an int or string. ValueError: If the value is not int or an acc...
def save(self, path): """ Writes file to a particular location This won't work for cloud environments like Google's App Engine, use with caution ensure to catch exceptions so you can provide informed feedback. prestans does not mask File IO exceptions so your handler can respon...
Writes file to a particular location This won't work for cloud environments like Google's App Engine, use with caution ensure to catch exceptions so you can provide informed feedback. prestans does not mask File IO exceptions so your handler can respond better.
Below is the the instruction that describes the task: ### Input: Writes file to a particular location This won't work for cloud environments like Google's App Engine, use with caution ensure to catch exceptions so you can provide informed feedback. prestans does not mask File IO exceptions...
def wait_for(self, predicate, timeout=None): """Like :meth:`wait` but additionally for *predicate* to be true. The *predicate* argument must be a callable that takes no arguments. Its result is interpreted as a boolean value. """ if not is_locked(self._lock): raise R...
Like :meth:`wait` but additionally for *predicate* to be true. The *predicate* argument must be a callable that takes no arguments. Its result is interpreted as a boolean value.
Below is the the instruction that describes the task: ### Input: Like :meth:`wait` but additionally for *predicate* to be true. The *predicate* argument must be a callable that takes no arguments. Its result is interpreted as a boolean value. ### Response: def wait_for(self, predicate, timeout=Non...
def _parse_extra(self, fp): """ Parse and store the config comments and create maps for dot notion lookup """ comment = '' section = '' fp.seek(0) for line in fp: line = line.rstrip() if not line: if comment: comment ...
Parse and store the config comments and create maps for dot notion lookup
Below is the the instruction that describes the task: ### Input: Parse and store the config comments and create maps for dot notion lookup ### Response: def _parse_extra(self, fp): """ Parse and store the config comments and create maps for dot notion lookup """ comment = '' section = '' ...
def session(self): """ This is what you should use to make requests. It sill authenticate for you. :return: requests.sessions.Session """ if not self._session: self._session = requests.Session() self._session.headers.update(dict(Authorization='Bearer {0}'...
This is what you should use to make requests. It sill authenticate for you. :return: requests.sessions.Session
Below is the the instruction that describes the task: ### Input: This is what you should use to make requests. It sill authenticate for you. :return: requests.sessions.Session ### Response: def session(self): """ This is what you should use to make requests. It sill authenticate for you. ...
def notify_listeners(self, msg_type, params): """Send a message to all the observers.""" for c in self.listeners: c.notify(msg_type, params)
Send a message to all the observers.
Below is the the instruction that describes the task: ### Input: Send a message to all the observers. ### Response: def notify_listeners(self, msg_type, params): """Send a message to all the observers.""" for c in self.listeners: c.notify(msg_type, params)
def net_fluxes(sources, sinks, msm, for_committors=None): """ Computes the transition path theory net flux matrix. Parameters ---------- sources : array_like, int The set of unfolded/reactant states. sinks : array_like, int The set of folded/product states. msm : msmbuilder....
Computes the transition path theory net flux matrix. Parameters ---------- sources : array_like, int The set of unfolded/reactant states. sinks : array_like, int The set of folded/product states. msm : msmbuilder.MarkovStateModel MSM fit to data. for_committors : np.ndar...
Below is the the instruction that describes the task: ### Input: Computes the transition path theory net flux matrix. Parameters ---------- sources : array_like, int The set of unfolded/reactant states. sinks : array_like, int The set of folded/product states. msm : msmbuilder.M...
def vocab_account_type(instance): """Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'user-account': try: acct_type = obj['account_type'...
Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary.
Below is the the instruction that describes the task: ### Input: Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary. ### Response: def vocab_account_type(instance): """Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabular...
def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0:...
Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node
Below is the the instruction that describes the task: ### Input: Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node ### Response: def _build_b...
def _make_tuple(x): """TF has an obnoxious habit of being lenient with single vs tuple.""" if isinstance(x, prettytensor.PrettyTensor): if x.is_sequence(): return tuple(x.sequence) else: return (x.tensor,) elif isinstance(x, tuple): return x elif (isinstance(x, collections.Sequence) and ...
TF has an obnoxious habit of being lenient with single vs tuple.
Below is the the instruction that describes the task: ### Input: TF has an obnoxious habit of being lenient with single vs tuple. ### Response: def _make_tuple(x): """TF has an obnoxious habit of being lenient with single vs tuple.""" if isinstance(x, prettytensor.PrettyTensor): if x.is_sequence(): r...
def two_phase_dP_acceleration(m, D, xi, xo, alpha_i, alpha_o, rho_li, rho_gi, rho_lo=None, rho_go=None): r'''This function handles calculation of two-phase liquid-gas pressure drop due to acceleration for flow inside channels. This is a discrete calculation for a segment wit...
r'''This function handles calculation of two-phase liquid-gas pressure drop due to acceleration for flow inside channels. This is a discrete calculation for a segment with a known difference in quality (and ideally known inlet and outlet pressures so density dependence can be included). .. math::...
Below is the the instruction that describes the task: ### Input: r'''This function handles calculation of two-phase liquid-gas pressure drop due to acceleration for flow inside channels. This is a discrete calculation for a segment with a known difference in quality (and ideally known inlet and outlet ...
def disconnectMsToNet(Facility_presence=0, UserUser_presence=0, SsVersionIndicator_presence=0): """Disconnect Section 9.3.7.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x25) # 00100101 c = Cause() packet = a / b / c if Facility_presence is 1: d = FacilityHdr(ieiF...
Disconnect Section 9.3.7.2
Below is the the instruction that describes the task: ### Input: Disconnect Section 9.3.7.2 ### Response: def disconnectMsToNet(Facility_presence=0, UserUser_presence=0, SsVersionIndicator_presence=0): """Disconnect Section 9.3.7.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x25)...
def write_bel_namespace(self, file: TextIO, use_names: bool = False) -> None: """Write as a BEL namespace file.""" if not self.is_populated(): self.populate() if use_names and not self.has_names: raise ValueError values = ( self._get_namespace_name_t...
Write as a BEL namespace file.
Below is the the instruction that describes the task: ### Input: Write as a BEL namespace file. ### Response: def write_bel_namespace(self, file: TextIO, use_names: bool = False) -> None: """Write as a BEL namespace file.""" if not self.is_populated(): self.populate() if use_na...
def _get_packages(): # type: () -> List[Package] """Convert `pkg_resources.working_set` into a list of `Package` objects. :return: list """ return [Package(pkg_obj=pkg) for pkg in sorted(pkg_resources.working_set, key=lambda x: str(x).lower())]
Convert `pkg_resources.working_set` into a list of `Package` objects. :return: list
Below is the the instruction that describes the task: ### Input: Convert `pkg_resources.working_set` into a list of `Package` objects. :return: list ### Response: def _get_packages(): # type: () -> List[Package] """Convert `pkg_resources.working_set` into a list of `Package` objects. :return: lis...
def Down(self, n = 1, dl = 0): """下方向键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.down_key, n)
下方向键n次
Below is the the instruction that describes the task: ### Input: 下方向键n次 ### Response: def Down(self, n = 1, dl = 0): """下方向键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.down_key, n)
def get_indicators_metadata(self, indicators): """ Provide metadata associated with an list of indicators, including value, indicatorType, noteCount, sightings, lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the request has READ access to...
Provide metadata associated with an list of indicators, including value, indicatorType, noteCount, sightings, lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the request has READ access to. :param indicators: a list of |Indicator| objects to quer...
Below is the the instruction that describes the task: ### Input: Provide metadata associated with an list of indicators, including value, indicatorType, noteCount, sightings, lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the request has READ access ...
def get_allowed_reset_keys_values(self): """Get the allowed values for resetting the system. :returns: A set with the allowed values. """ reset_keys_action = self._get_reset_keys_action_element() if not reset_keys_action.allowed_values: LOG.warning('Could not figure...
Get the allowed values for resetting the system. :returns: A set with the allowed values.
Below is the the instruction that describes the task: ### Input: Get the allowed values for resetting the system. :returns: A set with the allowed values. ### Response: def get_allowed_reset_keys_values(self): """Get the allowed values for resetting the system. :returns: A set with the al...
def viewzen_corr(data, view_zen): """Apply atmospheric correction on the given *data* using the specified satellite zenith angles (*view_zen*). Both input data are given as 2-dimensional Numpy (masked) arrays, and they should have equal shapes. The *data* array will be changed in place and has to be...
Apply atmospheric correction on the given *data* using the specified satellite zenith angles (*view_zen*). Both input data are given as 2-dimensional Numpy (masked) arrays, and they should have equal shapes. The *data* array will be changed in place and has to be copied before.
Below is the the instruction that describes the task: ### Input: Apply atmospheric correction on the given *data* using the specified satellite zenith angles (*view_zen*). Both input data are given as 2-dimensional Numpy (masked) arrays, and they should have equal shapes. The *data* array will be ch...
def cli_login(self, username='', password=''): """Generates CLI prompts to complete the login process :param username: optionally provide username :type username: :class:`str` :param password: optionally provide password :type password: :class:`str` :return: logon resu...
Generates CLI prompts to complete the login process :param username: optionally provide username :type username: :class:`str` :param password: optionally provide password :type password: :class:`str` :return: logon result, see `CMsgClientLogonResponse.eresult <https://github.c...
Below is the the instruction that describes the task: ### Input: Generates CLI prompts to complete the login process :param username: optionally provide username :type username: :class:`str` :param password: optionally provide password :type password: :class:`str` :return:...
def from_dataframe(cls, name, df, indices, primary_key=None): """Infer table metadata from a DataFrame""" # ordered list (column_name, column_type) pairs column_types = [] # which columns have nullable values nullable = set() # tag cached database by dataframe's number ...
Infer table metadata from a DataFrame
Below is the the instruction that describes the task: ### Input: Infer table metadata from a DataFrame ### Response: def from_dataframe(cls, name, df, indices, primary_key=None): """Infer table metadata from a DataFrame""" # ordered list (column_name, column_type) pairs column_types = [] ...
def Rz_to_coshucosv(R,z,delta=1.,oblate=False): """ NAME: Rz_to_coshucosv PURPOSE: calculate prolate confocal cosh(u) and cos(v) coordinates from R,z, and delta INPUT: R - radius z - height delta= focus oblate= (False) if True, compute oblate confocal co...
NAME: Rz_to_coshucosv PURPOSE: calculate prolate confocal cosh(u) and cos(v) coordinates from R,z, and delta INPUT: R - radius z - height delta= focus oblate= (False) if True, compute oblate confocal coordinates instead of prolate OUTPUT: (cosh(u),co...
Below is the the instruction that describes the task: ### Input: NAME: Rz_to_coshucosv PURPOSE: calculate prolate confocal cosh(u) and cos(v) coordinates from R,z, and delta INPUT: R - radius z - height delta= focus oblate= (False) if True, compute oblate co...
def execute(self, table_name=None, table_mode='create', use_cache=True, priority='interactive', allow_large_results=False, dialect=None, billing_tier=None): """ Initiate the query, blocking until complete and then return the results. Args: table_name: the result table name as a string or Ta...
Initiate the query, blocking until complete and then return the results. Args: table_name: the result table name as a string or TableName; if None (the default), then a temporary table will be used. table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request ...
Below is the the instruction that describes the task: ### Input: Initiate the query, blocking until complete and then return the results. Args: table_name: the result table name as a string or TableName; if None (the default), then a temporary table will be used. table_mode: one of 'creat...
def xml_entities_to_utf8(text, skip=('lt', 'gt', 'amp')): """Translate HTML or XML character references to UTF-8. Removes HTML or XML character references and entities from a text string and replaces them with their UTF-8 representation, if possible. :param text: The HTML (or XML) source text. :ty...
Translate HTML or XML character references to UTF-8. Removes HTML or XML character references and entities from a text string and replaces them with their UTF-8 representation, if possible. :param text: The HTML (or XML) source text. :type text: string :param skip: list of entity names to skip wh...
Below is the the instruction that describes the task: ### Input: Translate HTML or XML character references to UTF-8. Removes HTML or XML character references and entities from a text string and replaces them with their UTF-8 representation, if possible. :param text: The HTML (or XML) source text. ...
def getwinsize(self): """This returns the terminal window size of the child tty. The return value is a tuple of (rows, cols). """ TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L) s = struct.pack('HHHH', 0, 0, 0, 0) x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s) r...
This returns the terminal window size of the child tty. The return value is a tuple of (rows, cols).
Below is the the instruction that describes the task: ### Input: This returns the terminal window size of the child tty. The return value is a tuple of (rows, cols). ### Response: def getwinsize(self): """This returns the terminal window size of the child tty. The return value is a tuple o...
def create( cls, path, template_engine=None, output_filename=None, output_ext=None, view_name=None ): """Create the relevant subclass of StatikView based on the given path variable and parameters.""" # if it's a comp...
Create the relevant subclass of StatikView based on the given path variable and parameters.
Below is the the instruction that describes the task: ### Input: Create the relevant subclass of StatikView based on the given path variable and parameters. ### Response: def create( cls, path, template_engine=None, output_filename=None, output_ex...
def Hughmark(m, x, alpha, D, L, Cpl, kl, mu_b=None, mu_w=None): r'''Calculates the two-phase non-boiling laminar heat transfer coefficient of a liquid and gas flowing inside a tube of any inclination, as in [1]_ and reviewed in [2]_. .. math:: \frac{h_{TP} D}{k_l} = 1.75(1-\alpha)^{-0.5}\le...
r'''Calculates the two-phase non-boiling laminar heat transfer coefficient of a liquid and gas flowing inside a tube of any inclination, as in [1]_ and reviewed in [2]_. .. math:: \frac{h_{TP} D}{k_l} = 1.75(1-\alpha)^{-0.5}\left(\frac{m_l C_{p,l}} {(1-\alpha)k_l L}\right)^{1/3}\left(\f...
Below is the the instruction that describes the task: ### Input: r'''Calculates the two-phase non-boiling laminar heat transfer coefficient of a liquid and gas flowing inside a tube of any inclination, as in [1]_ and reviewed in [2]_. .. math:: \frac{h_{TP} D}{k_l} = 1.75(1-\alpha)^{-0.5}\l...
def initialize_path(self, path_num=None): """ inits producer for next path, i.e. sets current state to initial state""" for p in self.producers: p.initialize_path(path_num) # self.state = copy(self.initial_state) # self.state.path = path_num self.random.seed(hash(self...
inits producer for next path, i.e. sets current state to initial state
Below is the the instruction that describes the task: ### Input: inits producer for next path, i.e. sets current state to initial state ### Response: def initialize_path(self, path_num=None): """ inits producer for next path, i.e. sets current state to initial state""" for p in self.producers: ...
def cross_validate(data=None, folds=5, repeat=1, metrics=None, reporters=None, model_def=None, **kwargs): """Shortcut to cross-validate a single configuration. ModelDefinition variables are passed in as keyword args, along with the cross-validation parameters. """ md_kwargs = {} ...
Shortcut to cross-validate a single configuration. ModelDefinition variables are passed in as keyword args, along with the cross-validation parameters.
Below is the the instruction that describes the task: ### Input: Shortcut to cross-validate a single configuration. ModelDefinition variables are passed in as keyword args, along with the cross-validation parameters. ### Response: def cross_validate(data=None, folds=5, repeat=1, metrics=None, ...
def do_page_has_content(parser, token): """ Conditional tag that only renders its nodes if the page has content for a particular content type. By default the current page is used. Syntax:: {% page_has_content <content_type> [<page var name>] %} ... {%_end page_has_conte...
Conditional tag that only renders its nodes if the page has content for a particular content type. By default the current page is used. Syntax:: {% page_has_content <content_type> [<page var name>] %} ... {%_end page_has_content %} Example use:: {% page_has_conten...
Below is the the instruction that describes the task: ### Input: Conditional tag that only renders its nodes if the page has content for a particular content type. By default the current page is used. Syntax:: {% page_has_content <content_type> [<page var name>] %} ... {%_e...
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet imple...
List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs
Below is the the instruction that describes the task: ### Input: List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs ### Response: def list_pkgs(versions_as_list=False, **kwargs): ''' List the...
def check_bounds_variables(self, dataset): ''' Checks the grid boundary variables. :param netCDF4.Dataset dataset: An open netCDF dataset ''' recommended_ctx = TestCtx(BaseCheck.MEDIUM, 'Recommended variables to describe grid boundaries') bounds_map = { 'lat...
Checks the grid boundary variables. :param netCDF4.Dataset dataset: An open netCDF dataset
Below is the the instruction that describes the task: ### Input: Checks the grid boundary variables. :param netCDF4.Dataset dataset: An open netCDF dataset ### Response: def check_bounds_variables(self, dataset): ''' Checks the grid boundary variables. :param netCDF4.Dataset datas...
def CopyToStatTimeTuple(self): """Copies the date time value to a stat timestamp tuple. Returns: tuple[int, int]: a POSIX timestamp in seconds and the remainder in 100 nano seconds or (None, None) on error. """ normalized_timestamp = self._GetNormalizedTimestamp() if normalized_time...
Copies the date time value to a stat timestamp tuple. Returns: tuple[int, int]: a POSIX timestamp in seconds and the remainder in 100 nano seconds or (None, None) on error.
Below is the the instruction that describes the task: ### Input: Copies the date time value to a stat timestamp tuple. Returns: tuple[int, int]: a POSIX timestamp in seconds and the remainder in 100 nano seconds or (None, None) on error. ### Response: def CopyToStatTimeTuple(self): """Copi...
def flat_git_tree_to_nested(flat_tree, prefix=''): ''' Given an array in format: [ ["100644", "blob", "ab3ce...", "748", ".gitignore" ], ["100644", "blob", "ab3ce...", "748", "path/to/thing" ], ... ] Outputs in a nested format: { "path...
Given an array in format: [ ["100644", "blob", "ab3ce...", "748", ".gitignore" ], ["100644", "blob", "ab3ce...", "748", "path/to/thing" ], ... ] Outputs in a nested format: { "path": "/", "type": "directory", "children"...
Below is the the instruction that describes the task: ### Input: Given an array in format: [ ["100644", "blob", "ab3ce...", "748", ".gitignore" ], ["100644", "blob", "ab3ce...", "748", "path/to/thing" ], ... ] Outputs in a nested format: { ...
def resize(self, width, height): """ Pyqt specific resize callback. """ if not self.fbo: return # pyqt reports sizes in actual buffer size self.width = width // self.widget.devicePixelRatio() self.height = height // self.widget.devicePixelRatio() ...
Pyqt specific resize callback.
Below is the the instruction that describes the task: ### Input: Pyqt specific resize callback. ### Response: def resize(self, width, height): """ Pyqt specific resize callback. """ if not self.fbo: return # pyqt reports sizes in actual buffer size self....
def get_grouped_issues(self, keyfunc=None, sortby=None): """ Retrieves the issues in the collection grouped into buckets according to the key generated by the keyfunc. :param keyfunc: a function that will be used to generate the key that identifies the group that...
Retrieves the issues in the collection grouped into buckets according to the key generated by the keyfunc. :param keyfunc: a function that will be used to generate the key that identifies the group that an issue will be assigned to. This function receives a single ti...
Below is the the instruction that describes the task: ### Input: Retrieves the issues in the collection grouped into buckets according to the key generated by the keyfunc. :param keyfunc: a function that will be used to generate the key that identifies the group that an issu...
def load_json(path: str, encoding: str = "utf-8") -> HistogramBase: """Load histogram from a JSON file.""" with open(path, "r", encoding=encoding) as f: text = f.read() return parse_json(text)
Load histogram from a JSON file.
Below is the the instruction that describes the task: ### Input: Load histogram from a JSON file. ### Response: def load_json(path: str, encoding: str = "utf-8") -> HistogramBase: """Load histogram from a JSON file.""" with open(path, "r", encoding=encoding) as f: text = f.read() return par...
def add(self, indent, line): """Appends the given text line with prefixed spaces in accordance with the given number of indentation levels. """ if isinstance(line, str): list.append(self, indent*4*' ' + line) else: for subline in line: list...
Appends the given text line with prefixed spaces in accordance with the given number of indentation levels.
Below is the the instruction that describes the task: ### Input: Appends the given text line with prefixed spaces in accordance with the given number of indentation levels. ### Response: def add(self, indent, line): """Appends the given text line with prefixed spaces in accordance with the ...
def memoize(func): """ Cache decorator for functions inside model classes """ def model(cls, energy, *args, **kwargs): try: memoize = cls._memoize cache = cls._cache queue = cls._queue except AttributeError: memoize = False if memoize: ...
Cache decorator for functions inside model classes
Below is the the instruction that describes the task: ### Input: Cache decorator for functions inside model classes ### Response: def memoize(func): """ Cache decorator for functions inside model classes """ def model(cls, energy, *args, **kwargs): try: memoize = cls._memoize ...
def get_metadata(self, handle): """ Returns the associated metadata info for the given handle, the metadata file must exist (``handle + '.metadata'``). Args: handle (str): Path to the template to get the metadata from Returns: dict: Metadata for the give...
Returns the associated metadata info for the given handle, the metadata file must exist (``handle + '.metadata'``). Args: handle (str): Path to the template to get the metadata from Returns: dict: Metadata for the given handle
Below is the the instruction that describes the task: ### Input: Returns the associated metadata info for the given handle, the metadata file must exist (``handle + '.metadata'``). Args: handle (str): Path to the template to get the metadata from Returns: dict: Meta...
def simplify_soc_marker(self, text, prev_text): """Simplify start of cell marker when previous line is blank""" if self.cell_marker_start: return text if self.is_code() and text and text[0] == self.comment + ' + {}': if not prev_text or not prev_text[-1].strip(): ...
Simplify start of cell marker when previous line is blank
Below is the the instruction that describes the task: ### Input: Simplify start of cell marker when previous line is blank ### Response: def simplify_soc_marker(self, text, prev_text): """Simplify start of cell marker when previous line is blank""" if self.cell_marker_start: return text...
def set(self, indexes, values=None): """ Given indexes will set a sub-set of the Series to the values provided. This method will direct to the below methods based on what types are passed in for the indexes. If the indexes contains values not in the Series then new rows or columns will...
Given indexes will set a sub-set of the Series to the values provided. This method will direct to the below methods based on what types are passed in for the indexes. If the indexes contains values not in the Series then new rows or columns will be added. :param indexes: indexes value, list o...
Below is the the instruction that describes the task: ### Input: Given indexes will set a sub-set of the Series to the values provided. This method will direct to the below methods based on what types are passed in for the indexes. If the indexes contains values not in the Series then new rows or ...
def create_check(self, label=None, name=None, check_type=None, disabled=False, metadata=None, details=None, monitoring_zones_poll=None, timeout=None, period=None, target_alias=None, target_hostname=None, target_receiver=None, test_only=False, include_debug=False): ...
Creates a check on this entity with the specified attributes. The 'details' parameter should be a dict with the keys as the option name, and the value as the desired setting.
Below is the the instruction that describes the task: ### Input: Creates a check on this entity with the specified attributes. The 'details' parameter should be a dict with the keys as the option name, and the value as the desired setting. ### Response: def create_check(self, label=None, name=None,...
def execute(self, string, max_tacts=None): """Execute algorithm (if max_times = None, there can be forever loop).""" self.init_tape(string) counter = 0 while True: self.execute_once() if self.state == self.TERM_STATE: break counter += ...
Execute algorithm (if max_times = None, there can be forever loop).
Below is the the instruction that describes the task: ### Input: Execute algorithm (if max_times = None, there can be forever loop). ### Response: def execute(self, string, max_tacts=None): """Execute algorithm (if max_times = None, there can be forever loop).""" self.init_tape(string) coun...
def filesfile_string(self): """String with the list of files and prefixes needed to execute ABINIT.""" lines = [] app = lines.append pj = os.path.join app(self.input_file.path) # Path to the input file app(self.output_file.path) # Path to t...
String with the list of files and prefixes needed to execute ABINIT.
Below is the the instruction that describes the task: ### Input: String with the list of files and prefixes needed to execute ABINIT. ### Response: def filesfile_string(self): """String with the list of files and prefixes needed to execute ABINIT.""" lines = [] app = lines.append pj...
def list(self, group=None, host_filter=None, **kwargs): """Return a list of hosts. =====API DOCS===== Retrieve a list of hosts. :param group: Primary key or name of the group whose hosts will be listed. :type group: str :param all_pages: Flag that if set, collect all pa...
Return a list of hosts. =====API DOCS===== Retrieve a list of hosts. :param group: Primary key or name of the group whose hosts will be listed. :type group: str :param all_pages: Flag that if set, collect all pages of content from the API when returning results. :type a...
Below is the the instruction that describes the task: ### Input: Return a list of hosts. =====API DOCS===== Retrieve a list of hosts. :param group: Primary key or name of the group whose hosts will be listed. :type group: str :param all_pages: Flag that if set, collect all ...
def ldap_server_host_retries(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ldap_server = ET.SubElement(config, "ldap-server", xmlns="urn:brocade.com:mgmt:brocade-aaa") host = ET.SubElement(ldap_server, "host") hostname_key = ET.SubElement(host,...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def ldap_server_host_retries(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ldap_server = ET.SubElement(config, "ldap-server", xmlns="urn:brocade.com:mgmt:br...
def unset_variable(section, value): """ Unset a variable in an environment file for the given section. The value is given is the variable name, e.g.: s3conf unset test ENV_VAR_NAME """ if not value: value = section section = None try: logger.debug('Running env comman...
Unset a variable in an environment file for the given section. The value is given is the variable name, e.g.: s3conf unset test ENV_VAR_NAME
Below is the the instruction that describes the task: ### Input: Unset a variable in an environment file for the given section. The value is given is the variable name, e.g.: s3conf unset test ENV_VAR_NAME ### Response: def unset_variable(section, value): """ Unset a variable in an environment fil...
def is_import_exception(mod): """Check module name to see if import has been whitelisted. Import based rules should not run on any whitelisted module """ return (mod in IMPORT_EXCEPTIONS or any(mod.startswith(m + '.') for m in IMPORT_EXCEPTIONS))
Check module name to see if import has been whitelisted. Import based rules should not run on any whitelisted module
Below is the the instruction that describes the task: ### Input: Check module name to see if import has been whitelisted. Import based rules should not run on any whitelisted module ### Response: def is_import_exception(mod): """Check module name to see if import has been whitelisted. Import ba...
def _parse(self): """ Loop through all child elements and execute any available parse methods for them """ # Is this a shorthand template? if self._element.tag == 'template': return self._parse_template(self._element) # Is this a shorthand redirect? i...
Loop through all child elements and execute any available parse methods for them
Below is the the instruction that describes the task: ### Input: Loop through all child elements and execute any available parse methods for them ### Response: def _parse(self): """ Loop through all child elements and execute any available parse methods for them """ # Is this a shor...
def items(self): """Get an iter of VenvDirs and VenvFiles within the directory.""" contents = self.paths contents = ( BinFile(path.path) if path.is_file else BinDir(path.path) for path in contents ) return contents
Get an iter of VenvDirs and VenvFiles within the directory.
Below is the the instruction that describes the task: ### Input: Get an iter of VenvDirs and VenvFiles within the directory. ### Response: def items(self): """Get an iter of VenvDirs and VenvFiles within the directory.""" contents = self.paths contents = ( BinFile(path.path) if ...
def essays(self): """Copy essays from the source profile to the destination profile.""" for essay_name in self.dest_user.profile.essays.essay_names: setattr(self.dest_user.profile.essays, essay_name, getattr(self.source_profile.essays, essay_name))
Copy essays from the source profile to the destination profile.
Below is the the instruction that describes the task: ### Input: Copy essays from the source profile to the destination profile. ### Response: def essays(self): """Copy essays from the source profile to the destination profile.""" for essay_name in self.dest_user.profile.essays.essay_names: ...
def _num_integral(self, r, c): """ numerical integral (1-e^{-c*x^2})/x dx [0..r] :param r: radius :param c: 1/2sigma^2 :return: """ out = integrate.quad(lambda x: (1-np.exp(-c*x**2))/x, 0, r) return out[0]
numerical integral (1-e^{-c*x^2})/x dx [0..r] :param r: radius :param c: 1/2sigma^2 :return:
Below is the the instruction that describes the task: ### Input: numerical integral (1-e^{-c*x^2})/x dx [0..r] :param r: radius :param c: 1/2sigma^2 :return: ### Response: def _num_integral(self, r, c): """ numerical integral (1-e^{-c*x^2})/x dx [0..r] :param r: radi...
def export(self, exporter=None, force_stroke=False): """ Export this SWF using the specified exporter. When no exporter is passed in the default exporter used is swf.export.SVGExporter. Exporters should extend the swf.export.BaseExporter class. @param ...
Export this SWF using the specified exporter. When no exporter is passed in the default exporter used is swf.export.SVGExporter. Exporters should extend the swf.export.BaseExporter class. @param exporter : the exporter to use @param force_stroke : set to true ...
Below is the the instruction that describes the task: ### Input: Export this SWF using the specified exporter. When no exporter is passed in the default exporter used is swf.export.SVGExporter. Exporters should extend the swf.export.BaseExporter class. @param expo...