code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def tags(self, ticket_id): """ Lists the most popular recent tags in decreasing popularity from a specific ticket. """ return self._query_zendesk(self.endpoint.tags, 'tag', id=ticket_id)
Lists the most popular recent tags in decreasing popularity from a specific ticket.
def p_property_list(self, p): """property_list : property_assignment | property_list COMMA property_assignment """ if len(p) == 2: p[0] = [p[1]] else: p[1].append(p[3]) p[0] = p[1]
property_list : property_assignment | property_list COMMA property_assignment
def exc_message(exc_info): """Return the exception's message.""" exc = exc_info[1] if exc is None: # str exception result = exc_info[0] else: try: result = str(exc) except UnicodeEncodeError: try: result = unicode(exc) # flake8: no...
Return the exception's message.
def update(self): """ This method should be called when you want to ensure all cached attributes are in sync with the actual object attributes at runtime. This happens because attributes could store mutable objects and be modified outside the scope of this class. The most...
This method should be called when you want to ensure all cached attributes are in sync with the actual object attributes at runtime. This happens because attributes could store mutable objects and be modified outside the scope of this class. The most common idiom that isn't automagically...
def load(theTask, canExecute=True, strict=True, defaults=False): """ Shortcut to load TEAL .cfg files for non-GUI access where loadOnly=True. """ return teal(theTask, parent=None, loadOnly=True, returnAs="dict", canExecute=canExecute, strict=strict, errorsToTerm=True, default...
Shortcut to load TEAL .cfg files for non-GUI access where loadOnly=True.
def setup_data_split(X, y, tokenizer, proc_data_dir, **kwargs): """Setup data while splitting into a training, validation, and test set. Args: X: text data, y: data labels, tokenizer: A Tokenizer instance proc_data_dir: Directory for the split and processed d...
Setup data while splitting into a training, validation, and test set. Args: X: text data, y: data labels, tokenizer: A Tokenizer instance proc_data_dir: Directory for the split and processed data
def negated(self): """ Negates this instance and returns it. :return self """ op = QueryCompound.Op.And if self.__op == QueryCompound.Op.Or else QueryCompound.Op.Or return QueryCompound(*self.__queries, op=op)
Negates this instance and returns it. :return self
def __getBarFCName(pressure): """Parse the pressure and return FC (String).""" if pressure is None: return None press = __to_float1(pressure) if press < 974: return "Thunderstorms" if press < 990: return "Stormy" if press < 1002: return "Rain" if press < 1010:...
Parse the pressure and return FC (String).
def flatten(*caches): """Flatten a nested list of cache entries Parameters ---------- *caches : `list` One or more lists of file paths (`str` or :class:`~lal.utils.CacheEntry`). Returns ------- flat : `list` A flat `list` containing the unique set of entries across ...
Flatten a nested list of cache entries Parameters ---------- *caches : `list` One or more lists of file paths (`str` or :class:`~lal.utils.CacheEntry`). Returns ------- flat : `list` A flat `list` containing the unique set of entries across each input.
def _check_args(self, source): '''Validate the argument section. Args may be either a dict or a list (to allow multiple positional args). ''' path = [source] args = self.parsed_yaml.get('args', {}) self._assert_struct_type(args, 'args', (dict, list), path) path.a...
Validate the argument section. Args may be either a dict or a list (to allow multiple positional args).
def max_await_time_ms(self, max_await_time_ms): """Specifies a time limit for a getMore operation on a :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` cursor. For all other types of cursor max_await_time_ms is ignored. Raises :exc:`TypeError` if `max_await_time_ms` is not an integer o...
Specifies a time limit for a getMore operation on a :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` cursor. For all other types of cursor max_await_time_ms is ignored. Raises :exc:`TypeError` if `max_await_time_ms` is not an integer or ``None``. Raises :exc:`~pymongo.errors.InvalidOpe...
def subsample(partitions,dataset,seed): ''' Function to generate randomly sampled datasets with replacement. This is in the context of cells in the native dataset which are the rows of the matrix :param partitions: int designating the number of evenly spaced sample sizes to randomly select from the nati...
Function to generate randomly sampled datasets with replacement. This is in the context of cells in the native dataset which are the rows of the matrix :param partitions: int designating the number of evenly spaced sample sizes to randomly select from the native dataset :param dataset: DataFrame of the nati...
def add_digital_object( self, parent_archival_object, identifier, title=None, uri=None, location_of_originals=None, object_type="text", xlink_show="embed", xlink_actuate="onLoad", restricted=False, use_statement="", use_cond...
Creates a new digital object. :param string parent_archival_object: The archival object to which the newly-created digital object will be parented. :param string identifier: A unique identifier for the digital object, in any format. :param string title: The title of the digital object. ...
def find_taskruns(project_id, **kwargs): """Return a list of matched task runs for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA Task Run members :rtype: list :returns: A List of task runs that match the query members """ try...
Return a list of matched task runs for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA Task Run members :rtype: list :returns: A List of task runs that match the query members
def filter_by_col(self, column_names): """filters sheet/table by columns (input is column header) The routine returns the serial numbers with values>1 in the selected columns. Args: column_names (list): the column headers. Returns: pandas.DataFrame ...
filters sheet/table by columns (input is column header) The routine returns the serial numbers with values>1 in the selected columns. Args: column_names (list): the column headers. Returns: pandas.DataFrame
def handle(self, request_headers={}, signature_header=None): """Handle request.""" if self.client.webhook_secret is None: raise ValueError('Error: no webhook secret.') encoded_header = self._get_signature_header(signature_header, request_headers) decoded_request = self._decod...
Handle request.
def hgmd(self): """Hi Index """ # calculate time thread took to finish # logging.info('Starting HI score') tstart = datetime.now() if os.path.isfile(settings.hgmd_file): hgmd_obj = hgmd.HGMD(self.vcf_file) hgmd_obj.run() tend = datetime.now()...
Hi Index
def loads( s, record_store=None, schema=None, loader=from_json_compatible, record_class=None # deprecated in favor of schema ): """ Create a Record instance from a json serialized dictionary :param s: String with a json-serialized dictionary :param record_s...
Create a Record instance from a json serialized dictionary :param s: String with a json-serialized dictionary :param record_store: Record store to use for schema lookups (when $schema field is present) :param loader: Function called to fetch attributes from json. Typically shouldn...
def copy_file_upload(self, targetdir): ''' Copies the currently valid file upload into the given directory. If possible, the content is un-archived in the target directory. ''' assert(self.file_upload) # unpack student data to temporary directory # os.chro...
Copies the currently valid file upload into the given directory. If possible, the content is un-archived in the target directory.
def get_tax_class_by_id(cls, tax_class_id, **kwargs): """Find TaxClass Return single instance of TaxClass by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_tax_class_by_id(tax_cla...
Find TaxClass Return single instance of TaxClass by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_tax_class_by_id(tax_class_id, async=True) >>> result = thread.get() :pa...
def get_callee_account( global_state: GlobalState, callee_address: str, dynamic_loader: DynLoader ): """Gets the callees account from the global_state. :param global_state: state to look in :param callee_address: address of the callee :param dynamic_loader: dynamic loader to use :return: Accoun...
Gets the callees account from the global_state. :param global_state: state to look in :param callee_address: address of the callee :param dynamic_loader: dynamic loader to use :return: Account belonging to callee
def parse_at_root( self, root, # type: ET.Element state # type: _ProcessorState ): # type: (...) -> Any """Parse the given element as the root of the document.""" xml_value = self._processor.parse_at_root(root, state) return _hooks_apply_after_pa...
Parse the given element as the root of the document.
def _add_section_to_report(self, data): """ Adds found data to the report via several HTML generators """ # Count samples that have errors and/or warnings pass_count = error_count = only_warning_count = 0 for sample_data in data.values(): if sample_data['file_validation_status'] == ...
Adds found data to the report via several HTML generators
def contains(self, data): """ Check if an item has been added to the bloomfilter. :param bytes data: a bytestring representing the item to check. :returns: a boolean indicating whether or not the item is present in the bloomfilter. False-positives are possible, but a negativ...
Check if an item has been added to the bloomfilter. :param bytes data: a bytestring representing the item to check. :returns: a boolean indicating whether or not the item is present in the bloomfilter. False-positives are possible, but a negative return value is definitive.
def cached(cls, minimum_version=None, maximum_version=None, jdk=False): """Finds a java distribution that meets the given constraints and returns it. :API: public First looks for a cached version that was previously located, otherwise calls locate(). :param minimum_version: minimum jvm version to look...
Finds a java distribution that meets the given constraints and returns it. :API: public First looks for a cached version that was previously located, otherwise calls locate(). :param minimum_version: minimum jvm version to look for (eg, 1.7). The stricter of this and `--jvm-dis...
def hist(data): """Plots histogram""" win = CurveDialog(edit=False, toolbar=True, wintitle="Histogram test") plot = win.get_plot() plot.add_item(make.histogram(data)) win.show() win.exec_()
Plots histogram
def walk_perimeter(self, startx, starty): """ Starting at a point on the perimeter of a region, 'walk' the perimeter to return to the starting point. Record the path taken. Parameters ---------- startx, starty : int The starting location. Assumed to be on the...
Starting at a point on the perimeter of a region, 'walk' the perimeter to return to the starting point. Record the path taken. Parameters ---------- startx, starty : int The starting location. Assumed to be on the perimeter of a region. Returns ------- ...
def has(self, id, domain): """ Checks if a message has a translation. @rtype: bool @return: true if the message has a translation, false otherwise """ assert isinstance(id, (str, unicode)) assert isinstance(domain, (str, unicode)) if self.defines(id, dom...
Checks if a message has a translation. @rtype: bool @return: true if the message has a translation, false otherwise
def swarm_denovo_cluster(seq_path, d=1, threads=1, HALT_EXEC=False): """ Function : launch the Swarm de novo OTU picker Parameters: seq_path, filepath to reads d, resolution threads, number o...
Function : launch the Swarm de novo OTU picker Parameters: seq_path, filepath to reads d, resolution threads, number of threads to use Return : clusters, list of lists
def is_native_ion_gate(gate: ops.Gate) -> bool: """Check if a gate is a native ion gate. Args: gate: Input gate. Returns: True if the gate is native to the ion, false otherwise. """ return isinstance(gate, (ops.XXPowGate, ops.MeasurementGate, ...
Check if a gate is a native ion gate. Args: gate: Input gate. Returns: True if the gate is native to the ion, false otherwise.
def mkstemp(self, suffix, prefix, directory=None): """ Generate temp file name in artifacts base dir and close temp file handle """ if not directory: directory = self.artifacts_dir fd, fname = tempfile.mkstemp(suffix, prefix, directory) os.close(fd) ...
Generate temp file name in artifacts base dir and close temp file handle
def act(self, world_state, agent_host, current_r ): """take 1 action in response to the current world state""" obs_text = world_state.observations[-1].text obs = json.loads(obs_text) # most recent observation self.logger.debug(obs) if not u'XPos' in obs or not u'ZPos' in...
take 1 action in response to the current world state
def status_subversion(path, ignore_set, options): """Run svn status. Returns a 2-element tuple: * Text lines describing the status of the repository. * Empty sequence of subrepos, since svn does not support them. """ subrepos = () if path in ignore_set: return None, subrepos kee...
Run svn status. Returns a 2-element tuple: * Text lines describing the status of the repository. * Empty sequence of subrepos, since svn does not support them.
def StartCli(args, adb_commands, extra=None, **device_kwargs): """Starts a common CLI interface for this usb path and protocol.""" try: dev = adb_commands() dev.ConnectDevice(port_path=args.port_path, serial=args.serial, default_timeout_ms=args.timeout_ms, **device_kwar...
Starts a common CLI interface for this usb path and protocol.
def geometries(self): """Return an iterator of (shapely) geometries for this feature.""" # Ensure that the associated files are in the cache fname = '{}_{}'.format(self.name, self.scale) for extension in ['.dbf', '.shx']: get_test_data(fname + extension) path = get_te...
Return an iterator of (shapely) geometries for this feature.
def paths_from_version(version): """Get the EnergyPlus install directory and executable path. Parameters ---------- version : str, optional EnergyPlus version in the format "X-X-X", e.g. "8-7-0". Returns ------- eplus_exe : str Full path to the EnergyPlus executable. ep...
Get the EnergyPlus install directory and executable path. Parameters ---------- version : str, optional EnergyPlus version in the format "X-X-X", e.g. "8-7-0". Returns ------- eplus_exe : str Full path to the EnergyPlus executable. eplus_home : str Full path to the ...
def is_published(self): """Check fields 980 and 773 to see if the record has already been published. :return: True is published, else False """ field773 = record_get_field_instances(self.record, '773') for f773 in field773: if 'c' in field_get_subfields(f773): ...
Check fields 980 and 773 to see if the record has already been published. :return: True is published, else False
def dirty(name, target, user=None, username=None, password=None, ignore_unversioned=False): ''' Determine if the working directory has been changed. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} return _fail(ret, 'This functi...
Determine if the working directory has been changed.
def upload_sticker_file(self, user_id, png_sticker): """ Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success. https://core.telegram.org/bots/api#uploadstickerfile...
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success. https://core.telegram.org/bots/api#uploadstickerfile Parameters: :param user_id: User iden...
def save_signal(self,filename=None): """ Saves TransitSignal. Calls :func:`TransitSignal.save`; default filename is ``trsig.pkl`` in ``self.folder``. """ if filename is None: filename = os.path.join(self.folder,'trsig.pkl') self.trsig.save(filename)
Saves TransitSignal. Calls :func:`TransitSignal.save`; default filename is ``trsig.pkl`` in ``self.folder``.
def process_target(self): """Return target with transformations, if any""" if isinstance(self.target, str): # Replace single and double quotes with escaped single-quote self.target = self.target.replace("'", "\'").replace('"', "\'") return "\"{target}\"".format(target...
Return target with transformations, if any
def usb_control_out(library, session, request_type_bitmap_field, request_id, request_value, index, data=""): """Performs a USB control pipe transfer to the device. Corresponds to viUsbControlOut function of the VISA library. :param library: the visa library wrapped by ctypes. :para...
Performs a USB control pipe transfer to the device. Corresponds to viUsbControlOut function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param request_type_bitmap_field: bmRequestType parameter of the setup stage of a...
def overlay_gateway_monitor_vlan_range(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway, "name") name...
Auto Generated Code
def normalise_angle(th): """Normalise an angle to be in the range [-pi, pi].""" return th - (2.0 * np.pi) * np.floor((th + np.pi) / (2.0 * np.pi))
Normalise an angle to be in the range [-pi, pi].
def findReference(self, name, cls=QtGui.QWidget): """ Looks up a reference from the widget based on its object name. :param name | <str> cls | <subclass of QtGui.QObject> :return <QtGui.QObject> || None """ return s...
Looks up a reference from the widget based on its object name. :param name | <str> cls | <subclass of QtGui.QObject> :return <QtGui.QObject> || None
def find_records(self, check, keys=None): """Find records matching a query dict, optionally extracting subset of keys. Returns list of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optional] ...
Find records matching a query dict, optionally extracting subset of keys. Returns list of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optional] if specified, the subset of keys to extract. msg_id...
def get_num_ruptures(self): """ :returns: the number of ruptures per source group ID """ return {grp.id: sum(src.num_ruptures for src in grp) for grp in self.src_groups}
:returns: the number of ruptures per source group ID
def _format_syslog_config(cmd_ret): ''' Helper function to format the stdout from the get_syslog_config function. cmd_ret The return dictionary that comes from a cmd.run_all call. ''' ret_dict = {'success': cmd_ret['retcode'] == 0} if cmd_ret['retcode'] != 0: ret_dict['message'...
Helper function to format the stdout from the get_syslog_config function. cmd_ret The return dictionary that comes from a cmd.run_all call.
def read(self, pin, is_differential=False): """I2C Interface for ADS1x15-based ADCs reads. params: :param pin: individual or differential pin. :param bool is_differential: single-ended or differential read. """ pin = pin if is_differential else pin + 0x04 ...
I2C Interface for ADS1x15-based ADCs reads. params: :param pin: individual or differential pin. :param bool is_differential: single-ended or differential read.
def _adj(self, k): """ Description: Adjacent breaking Paramters: k: not used """ G = np.zeros((self.m, self.m)) for i in range(self.m): for j in range(self.m): if i == j+1 or j == i+1: G[i]...
Description: Adjacent breaking Paramters: k: not used
def mother(self): """Parent of this individual""" if self._mother == []: self._mother = self.sub_tag("FAMC/WIFE") return self._mother
Parent of this individual
def get_value(row, field_name): ''' Returns the value found in the field_name attribute of the row dictionary. ''' result = None dict_row = convert_to_dict(row) if detect_list(field_name): temp = row for field in field_name: dict_temp = convert_to_dict(temp) ...
Returns the value found in the field_name attribute of the row dictionary.
def get_contract(firma, pravni_forma, sidlo, ic, dic, zastoupen): """ Compose contract and create PDF. Args: firma (str): firma pravni_forma (str): pravni_forma sidlo (str): sidlo ic (str): ic dic (str): dic zastoupen (str): zastoupen Returns: ob...
Compose contract and create PDF. Args: firma (str): firma pravni_forma (str): pravni_forma sidlo (str): sidlo ic (str): ic dic (str): dic zastoupen (str): zastoupen Returns: obj: StringIO file instance containing PDF file.
def chk(self, annotations, fout_err): """Check annotations.""" for idx, ntd in enumerate(annotations): self._chk_fld(ntd, "Qualifier") # optional 0 or greater self._chk_fld(ntd, "DB_Reference", 1) # required 1 or greater self._chk_fld(ntd, "With_From") ...
Check annotations.
def service_present(name, service_type, description=None, profile=None, **connection_args): ''' Ensure service present in Keystone catalog name The name of the service service_type The type of Openstack Service description (optional) Description of the ...
Ensure service present in Keystone catalog name The name of the service service_type The type of Openstack Service description (optional) Description of the service
def calc_system(self, x, Y, Y_agg=None, L=None, population=None): """ Calculates the missing part of the extension plus accounts This method allows to specify an aggregated Y_agg for the account calculation (see Y_agg below). However, the full Y needs to be specified for the calculation...
Calculates the missing part of the extension plus accounts This method allows to specify an aggregated Y_agg for the account calculation (see Y_agg below). However, the full Y needs to be specified for the calculation of FY or SY. Calculates: - for each sector and country: ...
def docinfo2dict(doctree): """ Return the docinfo field list from a doctree as a dictionary Note: there can be multiple instances of a single field in the docinfo. Since a dictionary is returned, the last instance's value will win. Example: pub = rst2pub(rst_string) print docinfo2...
Return the docinfo field list from a doctree as a dictionary Note: there can be multiple instances of a single field in the docinfo. Since a dictionary is returned, the last instance's value will win. Example: pub = rst2pub(rst_string) print docinfo2dict(pub.document)
def assuan_serialize(data): """Serialize data according to ASSUAN protocol (for GPG daemon communication).""" for c in [b'%', b'\n', b'\r']: escaped = '%{:02X}'.format(ord(c)).encode('ascii') data = data.replace(c, escaped) return data
Serialize data according to ASSUAN protocol (for GPG daemon communication).
def create_parser(prog): """Create an argument parser, adding in the list of providers.""" parser = argparse.ArgumentParser(prog=prog, formatter_class=DsubHelpFormatter) parser.add_argument( '--provider', default='google-v2', choices=['local', 'google', 'google-v2', 'test-fails'], help=""...
Create an argument parser, adding in the list of providers.
def set_source_filter(self, source): """ Only search for tweets entered via given source :param source: String. Name of the source to search for. An example \ would be ``source=twitterfeed`` for tweets submitted via TwitterFeed :raises: TwitterSearchException """ if isi...
Only search for tweets entered via given source :param source: String. Name of the source to search for. An example \ would be ``source=twitterfeed`` for tweets submitted via TwitterFeed :raises: TwitterSearchException
def clusterStatus(self): """ Returns a dict of cluster nodes and their status information """ servers = yield self.getClusterServers() d = { 'workers': {}, 'crons': {}, 'queues': {} } now = time.time() reverse_map = {...
Returns a dict of cluster nodes and their status information
def to_pwm(self, precision=4, extra_str=""): """Return pwm as string. Parameters ---------- precision : int, optional, default 4 Floating-point precision. extra_str |: str, optional Extra text to include with motif id line. Retur...
Return pwm as string. Parameters ---------- precision : int, optional, default 4 Floating-point precision. extra_str |: str, optional Extra text to include with motif id line. Returns ------- motif_str : str M...
def simple_moving_average(data, period): """ Simple Moving Average. Formula: SUM(data / N) """ catch_errors.check_for_period_error(data, period) # Mean of Empty Slice RuntimeWarning doesn't affect output so it is # supressed with warnings.catch_warnings(): warnings.simplefil...
Simple Moving Average. Formula: SUM(data / N)
def diff_charsToLines(self, diffs, lineArray): """Rehydrate the text in a diff from a string of line hashes to real lines of text. Args: diffs: Array of diff tuples. lineArray: Array of unique strings. """ for i in range(len(diffs)): text = [] for char in diffs[i][1]: ...
Rehydrate the text in a diff from a string of line hashes to real lines of text. Args: diffs: Array of diff tuples. lineArray: Array of unique strings.
def connect_delete_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501 """connect_delete_namespaced_pod_proxy_with_path # noqa: E501 connect DELETE requests to proxy of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an ...
connect_delete_namespaced_pod_proxy_with_path # noqa: E501 connect DELETE requests to proxy of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_delete_namespaced_pod_prox...
def create_user(self, username, first_name=None, last_name=None): """ Creates a new user object on database Returns the User Object. Must be linked to a new trainer soon after """ url = api_url+'users/' payload = { 'username':username } if first_name: payload['first_name'] = first_name if las...
Creates a new user object on database Returns the User Object. Must be linked to a new trainer soon after
def register_properties_handler(self, handler_function): """register `handler_function` to receive `signal_name`. Uses dbus interface IPROPERTIES and objects path self.OBJ_PATH to match 'PropertiesChanged' signal. :param function handler_function: The function to be called. """...
register `handler_function` to receive `signal_name`. Uses dbus interface IPROPERTIES and objects path self.OBJ_PATH to match 'PropertiesChanged' signal. :param function handler_function: The function to be called.
def wait(self, readfds, writefds, timeout): """ Wait for file descriptors or timeout. Adds the current process in the correspondent waiting list and yield the cpu to another running process. """ logger.debug("WAIT:") logger.debug(f"\tProcess {self._current} is goi...
Wait for file descriptors or timeout. Adds the current process in the correspondent waiting list and yield the cpu to another running process.
def js2str(js, sort_keys=True, indent=4): """Encode js to nicely formatted human readable string. (utf-8 encoding) Usage:: >>> from weatherlab.lib.dataIO.js import js2str >>> s = js2str({"a": 1, "b": 2}) >>> print(s) { "a": 1, "b": 2 } **中文文...
Encode js to nicely formatted human readable string. (utf-8 encoding) Usage:: >>> from weatherlab.lib.dataIO.js import js2str >>> s = js2str({"a": 1, "b": 2}) >>> print(s) { "a": 1, "b": 2 } **中文文档** 将可Json化的Python对象转化成格式化的字符串。
def setAlternatingRowColors( self, state ): """ Sets the alternating row colors state for this widget. :param state | <bool> """ self._alternatingRowColors = state self.treeWidget().setAlternatingRowColors(state)
Sets the alternating row colors state for this widget. :param state | <bool>
def draw(data, size=(600, 400), node_size=2.0, edge_size=0.25, default_node_color=0x5bc0de, default_edge_color=0xaaaaaa, z=100, shader='basic', optimize=True, directed=True, display_html=True, show_save=False): """Draws an interactive 3D visualization of the inputted graph. Args: ...
Draws an interactive 3D visualization of the inputted graph. Args: data: Either an adjacency list of tuples (ie. [(1,2),...]) or object size: (Optional) Dimensions of visualization, in pixels node_size: (Optional) Defaults to 2.0 edge_size: (Optional) Defaults to 0.25 defaul...
def linkify(self, timeperiods): """ Will make timeperiod in exclude with id of the timeperiods :param timeperiods: Timeperiods object :type timeperiods: :return: None """ new_exclude = [] if hasattr(self, 'exclude') and self.exclude != []: log...
Will make timeperiod in exclude with id of the timeperiods :param timeperiods: Timeperiods object :type timeperiods: :return: None
def parse_uri_path(self, path): """ Given a uri path, return the Redis specific configuration options in that path string according to iana definition http://www.iana.org/assignments/uri-schemes/prov/redis :param path: string containing the path. Example: "/0" :return: m...
Given a uri path, return the Redis specific configuration options in that path string according to iana definition http://www.iana.org/assignments/uri-schemes/prov/redis :param path: string containing the path. Example: "/0" :return: mapping containing the options. Example: {"db": "0"}
def forward(self, obj): """ Forward an object to clients. :param obj: The object to be forwarded :type obj: smsframework.data.IncomingMessage|smsframework.data.MessageStatus :raises Exception: if any of the clients failed """ assert isinstance(obj, (IncomingMessage, Mess...
Forward an object to clients. :param obj: The object to be forwarded :type obj: smsframework.data.IncomingMessage|smsframework.data.MessageStatus :raises Exception: if any of the clients failed
def upload(self, src_dir, replica, staging_bucket, timeout_seconds=1200): """ Upload a directory of files from the local filesystem and create a bundle containing the uploaded files. :param str src_dir: file path to a directory of files to upload to the replica. :param str replica: the ...
Upload a directory of files from the local filesystem and create a bundle containing the uploaded files. :param str src_dir: file path to a directory of files to upload to the replica. :param str replica: the replica to upload to. The supported replicas are: `aws` for Amazon Web Services, and ...
def day_fraction(time): """Convert a 24-hour time to a fraction of a day. For example, midnight corresponds to 0.0, and noon to 0.5. :param time: Time in the form of 'HH:MM' (24-hour time) :type time: string :return: A day fraction :rtype: float :Examples: .. code-block:: python ...
Convert a 24-hour time to a fraction of a day. For example, midnight corresponds to 0.0, and noon to 0.5. :param time: Time in the form of 'HH:MM' (24-hour time) :type time: string :return: A day fraction :rtype: float :Examples: .. code-block:: python day_fraction("18:30")
def delete_project(project_id): """Delete Project.""" project = get_data_or_404('project', project_id) if project['owner_id'] != get_current_user_id(): return jsonify(message='forbidden'), 403 delete_instance('project', project_id) return jsonify({})
Delete Project.
def set_offset( self, offset ): """Set the current read offset (in bytes) for the instance.""" assert offset in range( len( self.buffer ) ) self.pos = offset self._fill_buffer()
Set the current read offset (in bytes) for the instance.
def get_import_resource_kwargs(self, request, *args, **kwargs): """Prepares/returns kwargs used when initializing Resource""" return self.get_resource_kwargs(request, *args, **kwargs)
Prepares/returns kwargs used when initializing Resource
def sequence(self, per_exon=False): """ Return the sequence for this feature. if per-exon is True, return an array of exon sequences This sequence is never reverse complemented """ db = self.db if not per_exon: start = self.txStart + 1 retu...
Return the sequence for this feature. if per-exon is True, return an array of exon sequences This sequence is never reverse complemented
def remove_sources(self, sources): """ Remove sources from the decomposition. This function removes sources from the decomposition. Doing so invalidates currently fitted VAR models and connectivity estimates. Parameters ---------- sources : {slice, int, array of ints} ...
Remove sources from the decomposition. This function removes sources from the decomposition. Doing so invalidates currently fitted VAR models and connectivity estimates. Parameters ---------- sources : {slice, int, array of ints} Indices of components to remove. ...
def _null_sia(subsystem, phi=0.0): """Return a |SystemIrreducibilityAnalysis| with zero |big_phi| and empty cause-effect structures. This is the analysis result for a reducible subsystem. """ return SystemIrreducibilityAnalysis(subsystem=subsystem, cut_subsys...
Return a |SystemIrreducibilityAnalysis| with zero |big_phi| and empty cause-effect structures. This is the analysis result for a reducible subsystem.
def find_endurance_tier_iops_per_gb(volume): """Find the tier for the given endurance volume (IOPS per GB) :param volume: The volume for which the tier level is desired :return: Returns a float value indicating the IOPS per GB for the volume """ tier = volume['storageTierLevel'] iops_per_gb = 0...
Find the tier for the given endurance volume (IOPS per GB) :param volume: The volume for which the tier level is desired :return: Returns a float value indicating the IOPS per GB for the volume
def sync(self): """Sync the timeout index entry with the shelf.""" if self.writeback and self.cache: super(_TimeoutMixin, self).__delitem__(self._INDEX) super(_TimeoutMixin, self).sync() self.writeback = False super(_TimeoutMixin, self).__setitem__(self._I...
Sync the timeout index entry with the shelf.
def wrap_results(self, **kwargs): """ Wrap returned http response into a well formatted dict :param kwargs: this dict param should contains following keys: fd: file directory to url: the test url fo the result files...
Wrap returned http response into a well formatted dict :param kwargs: this dict param should contains following keys: fd: file directory to url: the test url fo the result files_count: the number of files under har/ directory ...
def dump_process_memory(self, pid, working_dir="c:\\windows\\carbonblack\\", path_to_procdump=None): """Use sysinternals procdump to dump process memory on a specific process. If only the pid is specified, the default behavior is to use the version of ProcDump supplied with cbinterface's pip3 installer....
Use sysinternals procdump to dump process memory on a specific process. If only the pid is specified, the default behavior is to use the version of ProcDump supplied with cbinterface's pip3 installer. :requires: SysInternals ProcDump v9.0 included with cbinterface==1.1.0 :arguments pid: Process...
def open(self): """Opens the connection.""" self._id = str(uuid.uuid4()) self._client.open_connection(self._id, info=self._connection_args)
Opens the connection.
def write_file_list(filename, file_list=[], glob=None): """Write a list of files to a file. :param filename: the name of the file to write the list to :param file_list: a list of filenames to write to a file :param glob: if glob is specified, it will ignore file_list and instead create a list...
Write a list of files to a file. :param filename: the name of the file to write the list to :param file_list: a list of filenames to write to a file :param glob: if glob is specified, it will ignore file_list and instead create a list of files based on the pattern provide by glob (ex. *.cub)
def split_text(text: str, length: int = MAX_MESSAGE_LENGTH) -> typing.List[str]: """ Split long text :param text: :param length: :return: list of parts :rtype: :obj:`typing.List[str]` """ return [text[i:i + length] for i in range(0, len(text), length)]
Split long text :param text: :param length: :return: list of parts :rtype: :obj:`typing.List[str]`
def setLevel(self, level): r"""Overrides the parent method to adapt the formatting string to the level. Parameters ---------- level : int The new log level to set. See the logging levels in the logging module for details. Examples -------...
r"""Overrides the parent method to adapt the formatting string to the level. Parameters ---------- level : int The new log level to set. See the logging levels in the logging module for details. Examples -------- >>> import logging ...
def shift(self, delta): """Shift this `Series` forward on the X-axis by ``delta`` This modifies the series in-place. Parameters ---------- delta : `float`, `~astropy.units.Quantity`, `str` The amount by which to shift (in x-axis units if `float`), give a...
Shift this `Series` forward on the X-axis by ``delta`` This modifies the series in-place. Parameters ---------- delta : `float`, `~astropy.units.Quantity`, `str` The amount by which to shift (in x-axis units if `float`), give a negative value to shift backwards ...
def get_person(people_id): ''' Return a single person ''' result = _get(people_id, settings.PEOPLE) return People(result.content)
Return a single person
def _create_alpha(self, data, fill_value=None): """Create an alpha band DataArray object. If `fill_value` is provided and input data is an integer type then it is used to determine invalid "null" pixels instead of xarray's `isnull` and `notnull` methods. The returned array is 1...
Create an alpha band DataArray object. If `fill_value` is provided and input data is an integer type then it is used to determine invalid "null" pixels instead of xarray's `isnull` and `notnull` methods. The returned array is 1 where data is valid, 0 where invalid.
def _initialize(self, provide_data: List[mx.io.DataDesc], provide_label: List[mx.io.DataDesc], default_bucket_key: Tuple[int, int]) -> None: """ Initializes model components, creates scoring symbol and module, and binds it. :param prov...
Initializes model components, creates scoring symbol and module, and binds it. :param provide_data: List of data descriptors. :param provide_label: List of label descriptors. :param default_bucket_key: The default maximum (source, target) lengths.
def show_account(): """ Exports current account configuration in shell-friendly form. Takes into account explicit top-level flags like --organization. """ click.echo("# tonomi api") for (key, env) in REVERSE_MAPPING.items(): value = QUBELL.get(key, None) if value: ...
Exports current account configuration in shell-friendly form. Takes into account explicit top-level flags like --organization.
def silence_warnings(*warnings): """ Context manager for silencing bokeh validation warnings. """ for warning in warnings: silence(warning) try: yield finally: for warning in warnings: silence(warning, False)
Context manager for silencing bokeh validation warnings.
def vsreenqueue(item_id, item_s, args, **kwargs): '''Enqueue a string, or string-like object to other queues, with arbitrary arguments, sreenqueue is to reenqueue what sprintf is to printf, sreenqueue is to vsreenqueue what sprintf is to vsprintf. ''' charset = kwargs.get('charset', _c.FSQ_CHA...
Enqueue a string, or string-like object to other queues, with arbitrary arguments, sreenqueue is to reenqueue what sprintf is to printf, sreenqueue is to vsreenqueue what sprintf is to vsprintf.
def run_process(self, process): """Runs a single action.""" message = u'#{bright}' message += u'{} '.format(str(process)[:68]).ljust(69, '.') stashed = False if self.unstaged_changes and not self.include_unstaged_changes: out, err, code = self.git.stash(keep_index=Tr...
Runs a single action.
def import_from_dict(session, data, sync=[]): """Imports databases and druid clusters from dictionary""" if isinstance(data, dict): logging.info('Importing %d %s', len(data.get(DATABASES_KEY, [])), DATABASES_KEY) for database in data.get(DATABASES_KEY, [...
Imports databases and druid clusters from dictionary
def evaluate(): """ Evaluate loop for the trained model """ print(eval_model) eval_model.initialize(mx.init.Xavier(), ctx=context[0]) eval_model.hybridize(static_alloc=True, static_shape=True) epoch = args.from_epoch if args.from_epoch else 0 while epoch < args.epochs: checkpoint_name = ...
Evaluate loop for the trained model