code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def domain(self, domain=None, last_domain=None): """ Manage the case that we want to test only a domain. :param domain: The domain or IP to test. :type domain: str :param last_domain: The last domain to test if we are testing a file. :type last_domain: str ...
Manage the case that we want to test only a domain. :param domain: The domain or IP to test. :type domain: str :param last_domain: The last domain to test if we are testing a file. :type last_domain: str :param return_status: Tell us if we need to return the status...
def tvBrowserExposure_selection_changed(self): """Update layer description label.""" (is_compatible, desc) = self.get_layer_description_from_browser( 'exposure') self.lblDescribeBrowserExpLayer.setText(desc) self.parent.pbnNext.setEnabled(is_compatible)
Update layer description label.
def to_struct(self, value): """Cast `time` object to string.""" if self.str_format: return value.strftime(self.str_format) return value.isoformat()
Cast `time` object to string.
def run(self): """ Run import. """ latest_track = Track.objects.all().order_by('-last_played') latest_track = latest_track[0] if latest_track else None importer = self.get_importer() tracks = importer.run() # Create/update Django Track objects fo...
Run import.
def rgba(self, val): """Set the color using an Nx4 array of RGBA floats""" # Note: all other attribute sets get routed here! # This method is meant to do the heavy lifting of setting data rgba = _user_to_rgba(val, expand=False) if self._rgba is None: self._rgba = rgba...
Set the color using an Nx4 array of RGBA floats
def apt_autoremove(purge=True, fatal=False): """Purge one or more packages.""" cmd = ['apt-get', '--assume-yes', 'autoremove'] if purge: cmd.append('--purge') _run_apt_command(cmd, fatal)
Purge one or more packages.
def _ExtractMetadataFromFileEntry(self, mediator, file_entry, data_stream): """Extracts metadata from a file entry. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_entry (dfvfs.FileEntry): file entry ...
Extracts metadata from a file entry. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_entry (dfvfs.FileEntry): file entry to extract metadata from. data_stream (dfvfs.DataStream): data stream or None...
def str_blockIndent(astr_buf, a_tabs=1, a_tabLength=4, **kwargs): """ For the input string <astr_buf>, replace each '\n' with '\n<tab>' where the number of tabs is indicated by <a_tabs> and the length of the tab by <a_tabLength> Trailing '\n' are *not* replaced. """ str_tabBoundary = " " ...
For the input string <astr_buf>, replace each '\n' with '\n<tab>' where the number of tabs is indicated by <a_tabs> and the length of the tab by <a_tabLength> Trailing '\n' are *not* replaced.
def gen_method_keys(self, *args, **kwargs): '''Given a node, return the string to use in computing the matching visitor methodname. Can also be a generator of strings. ''' token = args[0] for mro_type in type(token).__mro__[:-1]: name = mro_type.__name__ y...
Given a node, return the string to use in computing the matching visitor methodname. Can also be a generator of strings.
def findBinomialNsWithLowerBoundSampleMinimum(confidence, desiredValuesSorted, p, numSamples, nMax): """ For each desired value, find an approximate n for which the sample minimum has a probabilistic lower bound equal to this value. For each value, find an adjacent...
For each desired value, find an approximate n for which the sample minimum has a probabilistic lower bound equal to this value. For each value, find an adjacent pair of n values whose lower bound sample minima are below and above the desired value, respectively, and return a linearly-interpolated n between the...
def get(self, id): """ 根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 """ document = self._get_document(id) if document: session_json = document["session"] return json_loads(session_json) return {}
根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
def display_lookback_returns(self): """ Displays the current lookback returns for each series. """ return self.lookback_returns.apply( lambda x: x.map('{:,.2%}'.format), axis=1)
Displays the current lookback returns for each series.
def create_event(self, type, data, **kwargs): """ Create event. The **Events** API can be used to create log entries that are associated with specific queries. For example, you can record which documents in the results set were \"clicked\" by a user and when that click occured. ...
Create event. The **Events** API can be used to create log entries that are associated with specific queries. For example, you can record which documents in the results set were \"clicked\" by a user and when that click occured. :param str type: The event type to be created. :p...
def aDiffCytoscape(df,aging_genes,target,species="caenorhabditis elegans",limit=None, cutoff=0.4,\ taxon=None,host=cytoscape_host,port=cytoscape_port): """ Plots tables from aDiff/cuffdiff into cytoscape using String protein queries. Uses top changed genes as well as first neighbours and ...
Plots tables from aDiff/cuffdiff into cytoscape using String protein queries. Uses top changed genes as well as first neighbours and difusion fo generate subnetworks. :param df: df as outputed by aDiff for differential gene expression :param aging_genes: ENS gene ids to be labeled with a diagonal ...
def draw_zijderveld(self): """ Draws the zijderveld plot in the GUI on canvas1 """ self.fig1.clf() axis_bounds = [0, .1, 1, .85] self.zijplot = self.fig1.add_axes( axis_bounds, frameon=False, facecolor='None', label='zig_orig', zorder=0) self.zijplot.c...
Draws the zijderveld plot in the GUI on canvas1
def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item...
List servers
def reverse_dummies(self, X, mapping): """ Convert dummy variable into numerical variables Parameters ---------- X : DataFrame mapping: list-like Contains mappings of column to be transformed to it's new columns and value represented Returns ...
Convert dummy variable into numerical variables Parameters ---------- X : DataFrame mapping: list-like Contains mappings of column to be transformed to it's new columns and value represented Returns ------- numerical: DataFrame
def generate_context(context_file='cookiecutter.json', default_context=None, extra_context=None): """Generate the context for a Cookiecutter project template. Loads the JSON file as a Python object, with key being the JSON filename. :param context_file: JSON file containing key/value ...
Generate the context for a Cookiecutter project template. Loads the JSON file as a Python object, with key being the JSON filename. :param context_file: JSON file containing key/value pairs for populating the cookiecutter's variables. :param default_context: Dictionary containing config to take in...
def update(self, name: str, value=None, default=None, description: str=None): """ Like add, but can tolerate existing values; also updates the value. Mostly used for setting fields from imported INI files and modified CLI flags. """ if name in self._vars: description...
Like add, but can tolerate existing values; also updates the value. Mostly used for setting fields from imported INI files and modified CLI flags.
def get_max_bond_lengths(structure, el_radius_updates=None): """ Provides max bond length estimates for a structure based on the JMol table and algorithms. Args: structure: (structure) el_radius_updates: (dict) symbol->float to update atomic radii Returns: (dict) - (Element...
Provides max bond length estimates for a structure based on the JMol table and algorithms. Args: structure: (structure) el_radius_updates: (dict) symbol->float to update atomic radii Returns: (dict) - (Element1, Element2) -> float. The two elements are ordered by Z.
def unlock(self): """Remove current lock. This function does not crash if it is unable to properly delete the lock file and directory. The reason is that it should be allowed for multiple jobs running in parallel to unlock the same directory at the same time (e.g. when reaching ...
Remove current lock. This function does not crash if it is unable to properly delete the lock file and directory. The reason is that it should be allowed for multiple jobs running in parallel to unlock the same directory at the same time (e.g. when reaching their timeout limit).
def do_execute(self): """ Actual execution of the director. :return: None if successful, otherwise error message :rtype: str """ self._stopped = False self._stopping = False not_finished_actor = self.owner.first_active pending_actors = [] ...
Actual execution of the director. :return: None if successful, otherwise error message :rtype: str
def get_tokens(self, *, payer_id, credit_card_token_id, start_date, end_date): """ With this functionality you can query previously the Credit Cards Token. Args: payer_id: credit_card_token_id: start_date: end_date: Returns: """ ...
With this functionality you can query previously the Credit Cards Token. Args: payer_id: credit_card_token_id: start_date: end_date: Returns:
def get_fptr(self): """Get the function pointer.""" cmpfunc = ctypes.CFUNCTYPE(ctypes.c_int, WPARAM, LPARAM, ctypes.POINTER(KBDLLHookStruct)) return cmpfunc(self.handle_input)
Get the function pointer.
def plot_labels(ax, label_fontsize=14, xlabel=None, xlabel_arg=None, ylabel=None, ylabel_arg=None, zlabel=None, zlabel_arg=None): """Sets the labels options of a matplotlib plot Args: ax: matplotlib axes label_fontsize(int): Size of the labels' fo...
Sets the labels options of a matplotlib plot Args: ax: matplotlib axes label_fontsize(int): Size of the labels' font xlabel(str): The xlabel for the figure xlabel_arg(dict): Passsed into matplotlib as xlabel arguments ylabel(str): The ylabel for the figure ylabel_ar...
def remove_overlap(self, also_remove_contiguous: bool = False) -> None: """ Merges any overlapping intervals. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging? """ overlap = True while over...
Merges any overlapping intervals. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging?
def emissive_part_3x(self, tb=True): """Get the emissive part of the 3.x band""" try: # Emissive part: self._e3x = self._rad3x_t11 * (1 - self._r3x) # Unsure how much sense it makes to apply the co2 correction term here!? # FIXME! # self._e3x *...
Get the emissive part of the 3.x band
def execute_ccm_remotely(remote_options, ccm_args): """ Execute CCM operation(s) remotely :return A tuple defining the execution of the command * output - The output of the execution if the output was not displayed * exit_status - The exit status of remotely executed script...
Execute CCM operation(s) remotely :return A tuple defining the execution of the command * output - The output of the execution if the output was not displayed * exit_status - The exit status of remotely executed script :raises Exception if invalid options are passed for `--dse-...
def check_guest_exist(check_index=0): """Check guest exist in database. :param check_index: The parameter index of userid(s), default as 0 """ def outer(f): @six.wraps(f) def inner(self, *args, **kw): userids = args[check_index] if isinstance(userids, list): ...
Check guest exist in database. :param check_index: The parameter index of userid(s), default as 0
def to_genshi(walker): """Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes """ text = [] for token in walker: type = token["type"] if type in ("Characters", "SpaceCharacters"): tex...
Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes
def occupy(self, start, stop): """ Mark a given interval as occupied so that the manager could skip the values from ``start`` to ``stop`` (**inclusive**). :param start: beginning of the interval. :param stop: end of the interval. :type start: int ...
Mark a given interval as occupied so that the manager could skip the values from ``start`` to ``stop`` (**inclusive**). :param start: beginning of the interval. :param stop: end of the interval. :type start: int :type stop: int
def get_confirmation_url(email, request, name="email_registration_confirm", **kwargs): """ Returns the confirmation URL """ return request.build_absolute_uri( reverse(name, kwargs={"code": get_confirmation_code(email, request, **kwargs)}) )
Returns the confirmation URL
def load_nddata(self, ndd, naxispath=None): """Load from an astropy.nddata.NDData object. """ self.clear_metadata() # Make a header based on any NDData metadata ahdr = self.get_header() ahdr.update(ndd.meta) self.setup_data(ndd.data, naxispath=naxispath) ...
Load from an astropy.nddata.NDData object.
def add(self, resource, replace=False): """Add a resource or an iterable collection of resources. Will throw a ValueError if the resource (ie. same uri) already exists in the ResourceList, unless replace=True. """ if isinstance(resource, collections.Iterable): for r ...
Add a resource or an iterable collection of resources. Will throw a ValueError if the resource (ie. same uri) already exists in the ResourceList, unless replace=True.
def get_user_list(host_name, client_name, client_pass): """ Pulls the list of users in a client. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - client_name: The PServer client name. - client_pass: The PServer client's pass...
Pulls the list of users in a client. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - client_name: The PServer client name. - client_pass: The PServer client's password. Output: - user_id_list: A python list of user ids.
def updateGroup(self, group, vendorSpecific=None): """See Also: updateGroupResponse() Args: group: vendorSpecific: Returns: """ response = self.updateGroupResponse(group, vendorSpecific) return self._read_boolean_response(response)
See Also: updateGroupResponse() Args: group: vendorSpecific: Returns:
def time_at_shadow_length(day, latitude, multiplier): """Compute the time at which an object's shadow is a multiple of its length. Specifically, determine the time the length of the shadow is a multiple of the object's length + the length of the object's shadow at noon This is used in the calculation ...
Compute the time at which an object's shadow is a multiple of its length. Specifically, determine the time the length of the shadow is a multiple of the object's length + the length of the object's shadow at noon This is used in the calculation for Asr time. Hanafi uses a multiplier of 2, and everyone...
def chunked(data, chunksize): """ Returns a list of chunks containing at most ``chunksize`` elements of data. """ if chunksize < 1: raise ValueError("Chunksize must be at least 1!") if int(chunksize) != chunksize: raise ValueError("Chunksize needs to be an integer") res = [] ...
Returns a list of chunks containing at most ``chunksize`` elements of data.
def calcAFunc(self,MaggNow,AaggNow): ''' Calculate a new aggregate savings rule based on the history of the aggregate savings and aggregate market resources from a simulation. Parameters ---------- MaggNow : [float] List of the history of the simulated aggreg...
Calculate a new aggregate savings rule based on the history of the aggregate savings and aggregate market resources from a simulation. Parameters ---------- MaggNow : [float] List of the history of the simulated aggregate market resources for an economy. AaggNow : [f...
def audio_output_enumerate_devices(self): """Enumerate the defined audio output devices. @return: list of dicts {name:, description:, devices:} """ r = [] head = libvlc_audio_output_list_get(self) if head: i = head while i: i = i.c...
Enumerate the defined audio output devices. @return: list of dicts {name:, description:, devices:}
def create_connection(self, *args, **kwargs): """This method is trying to establish connection with one of the zookeeper nodes. Somehow strategy "fail earlier and retry more often" works way better comparing to the original strategy "try to connect with specified timeout". Since...
This method is trying to establish connection with one of the zookeeper nodes. Somehow strategy "fail earlier and retry more often" works way better comparing to the original strategy "try to connect with specified timeout". Since we want to try connect to zookeeper more often (with the...
def _get_coordinator_for_group(self, consumer_group): """Returns the coordinator (broker) for a consumer group Returns the broker for a given consumer group or Raises ConsumerCoordinatorNotAvailableError """ if self.consumer_group_to_brokers.get(consumer_group) is None: ...
Returns the coordinator (broker) for a consumer group Returns the broker for a given consumer group or Raises ConsumerCoordinatorNotAvailableError
def checksum(self): """Grab checksum string """ md5sum, md5sum64, = [], [] for line in self.SLACKBUILDS_TXT.splitlines(): if line.startswith(self.line_name): sbo_name = line[17:].strip() if line.startswith(self.line_md5_64): if sbo_...
Grab checksum string
def _all_same_area(self, dataset_ids): """Return True if all areas for the provided IDs are equal.""" all_areas = [] for ds_id in dataset_ids: for scn in self.scenes: ds = scn.get(ds_id) if ds is None: continue all_a...
Return True if all areas for the provided IDs are equal.
def open_file(self, path): """ Creates a new GenericCodeEdit, opens the requested file and adds it to the tab widget. :param path: Path of the file to open """ if path: editor = self.tabWidget.open_document(path) editor.cursorPositionChanged.conne...
Creates a new GenericCodeEdit, opens the requested file and adds it to the tab widget. :param path: Path of the file to open
def get_fragment(self, **kwargs): """ Return a complete fragment. :param gp: :return: """ gen, namespaces, plan = self.get_fragment_generator(**kwargs) graph = ConjunctiveGraph() [graph.bind(prefix, u) for (prefix, u) in namespaces] [graph.add((s, ...
Return a complete fragment. :param gp: :return:
def sign_remote_certificate(argdic, **kwargs): ''' Request a certificate to be remotely signed according to a signing policy. argdic: A dict containing all the arguments to be passed into the create_certificate function. This will become kwargs when passed to create_certificate. ...
Request a certificate to be remotely signed according to a signing policy. argdic: A dict containing all the arguments to be passed into the create_certificate function. This will become kwargs when passed to create_certificate. kwargs: kwargs delivered from publish.publish ...
def global_request(self, kind, data=None, wait=True): """ Make a global request to the remote host. These are normally extensions to the SSH2 protocol. :param str kind: name of the request. :param tuple data: an optional tuple containing additional data to attach to...
Make a global request to the remote host. These are normally extensions to the SSH2 protocol. :param str kind: name of the request. :param tuple data: an optional tuple containing additional data to attach to the request. :param bool wait: ``True`` i...
def readFromFile(self, filename): ''' read the distortion coeffs from file ''' s = dict(np.load(filename)) try: self.coeffs = s['coeffs'][()] except KeyError: #LEGENCY - remove self.coeffs = s try: self.op...
read the distortion coeffs from file
def postalCodeLookup(self, countryCode, postalCode): """ Looks up locations for this country and postal code. """ params = {"country": countryCode, "postalcode": postalCode} d = self._call("postalCodeLookupJSON", params) d.addCallback(operator.itemgetter("postalcodes")) ...
Looks up locations for this country and postal code.
def is_connectable(host: str, port: Union[int, str]) -> bool: """Tries to connect to the device to see if it is connectable. Args: host: The host to connect. port: The port to connect. Returns: True or False. """ socket_ = None try: socket_ = socket.create_conne...
Tries to connect to the device to see if it is connectable. Args: host: The host to connect. port: The port to connect. Returns: True or False.
def decrypt(ciphertext, secret, inital_vector, checksum=True, lazy=True): """Decrypts ciphertext with secret ciphertext - encrypted content to decrypt secret - secret to decrypt ciphertext inital_vector - initial vector lazy - pad secret if less than legal blocksize (default: ...
Decrypts ciphertext with secret ciphertext - encrypted content to decrypt secret - secret to decrypt ciphertext inital_vector - initial vector lazy - pad secret if less than legal blocksize (default: True) checksum - verify crc32 byte encoded checksum (default: True) ...
def clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ comment = self.cleaned_data["text"] if settings.COMMENTS_ALLOW_PROFANITIES is False: bad_words = [w for w in settings....
If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST.
def appendInputWithNSimilarValues(inputs, numNear = 10): """ Creates a neighboring record for each record in the inputs and adds new records at the end of the inputs list """ numInputs = len(inputs) skipOne = False for i in xrange(numInputs): input = inputs[i] numChanged = 0 newInput = copy.deep...
Creates a neighboring record for each record in the inputs and adds new records at the end of the inputs list
def new_action(project_id): """Add action.""" project = get_data_or_404('project', project_id) if project['owner_id'] != get_current_user_id(): return jsonify(message='forbidden'), 403 form = NewActionForm() if not form.validate_on_submit(): return jsonify(errors=form.errors), 400...
Add action.
def parse_args(self, command_selected, flags, _free_args): # type: (str, Dict[str, str], List[str]) -> bool """ Parse the args and fill the global data Currently we disregard the free parameters :param command_selected: :param flags: :param _free_args: :re...
Parse the args and fill the global data Currently we disregard the free parameters :param command_selected: :param flags: :param _free_args: :return:
def retry_on_exception(num_retries, base_delay=0, exc_type=Exception): """If the decorated function raises exception exc_type, allow num_retries retry attempts before raise the exception. """ def _retry_on_exception_inner_1(f): def _retry_on_exception_inner_2(*args, **kwargs): retrie...
If the decorated function raises exception exc_type, allow num_retries retry attempts before raise the exception.
def load_emacs_open_in_editor_bindings(): """ Pressing C-X C-E will open the buffer in an external editor. """ registry = Registry() registry.add_binding(Keys.ControlX, Keys.ControlE, filter=EmacsMode() & ~HasSelection())( get_by_name('edit-and-execute-command')) ...
Pressing C-X C-E will open the buffer in an external editor.
def installSite(self): """ Not using the dependency system for this class because it's only installed via the command line, and multiple instances can be installed. """ for iface, priority in self.__getPowerupInterfaces__([]): self.store.powerUp(self, iface, p...
Not using the dependency system for this class because it's only installed via the command line, and multiple instances can be installed.
def assemble_notification_request(method, params=tuple()): """serialize a JSON-RPC-Notification :Parameters: see dumps_request :Returns: | {"method": "...", "params": ..., "id": null} | "method", "params" and "id" are always in this order. :Raises: see dumps_req...
serialize a JSON-RPC-Notification :Parameters: see dumps_request :Returns: | {"method": "...", "params": ..., "id": null} | "method", "params" and "id" are always in this order. :Raises: see dumps_request
def _drawContents(self, currentRti=None): """ Draws the attributes of the currentRTI """ #logger.debug("_drawContents: {}".format(currentRti)) table = self.table table.setUpdatesEnabled(False) try: table.clearContents() verticalHeader = table.verti...
Draws the attributes of the currentRTI
def c_typedefs(self): """Get the typedefs of the module.""" defs = [] attrs = self.opts.attrs + '\n' if self.opts.attrs else '' for name, args in self.funcs: logging.debug('name: %s args: %s', name, args) defs.append( 'typedef\n{}\n{}{}({});\n'.for...
Get the typedefs of the module.
def save_rst(self, file_name='pysb_model.rst', module_name='pysb_module'): """Save the assembled model as an RST file for literate modeling. Parameters ---------- file_name : Optional[str] The name of the file to save the RST in. Default: pysb_model.rst m...
Save the assembled model as an RST file for literate modeling. Parameters ---------- file_name : Optional[str] The name of the file to save the RST in. Default: pysb_model.rst module_name : Optional[str] The name of the python function defining the mo...
def getTerms(self, term=None, getFingerprint=None, startIndex=0, maxResults=10): """Get term objects Args: term, str: A term in the retina (optional) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) startIndex, in...
Get term objects Args: term, str: A term in the retina (optional) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) startIndex, int: The start-index for pagination (optional) maxResults, int: Max results per pa...
def QA_indicator_BBI(DataFrame, N1=3, N2=6, N3=12, N4=24): '多空指标' C = DataFrame['close'] bbi = (MA(C, N1) + MA(C, N2) + MA(C, N3) + MA(C, N4)) / 4 DICT = {'BBI': bbi} return pd.DataFrame(DICT)
多空指标
def datetime( self, year, month, day, hour=0, minute=0, second=0, microsecond=0 ): # type: (int, int, int, int, int, int, int) -> datetime """ Return a normalized datetime for the current timezone. """ if _HAS_FOLD: return self.convert( datetime(y...
Return a normalized datetime for the current timezone.
def assert_valid_path(self, path): """ Ensures that the path represents an existing file @type path: str @param path: path to check """ if not isinstance(path, str): raise NotFoundResourceException( "Resource passed to load() method must be a...
Ensures that the path represents an existing file @type path: str @param path: path to check
def set_led(self, led_number, led_value): """ Set front-panel controller LEDs. The DS3 controller has four, labelled, LEDs on the front panel that can be either on or off. :param led_number: Integer between 1 and 4 :param led_value: Value, set to 0 to tur...
Set front-panel controller LEDs. The DS3 controller has four, labelled, LEDs on the front panel that can be either on or off. :param led_number: Integer between 1 and 4 :param led_value: Value, set to 0 to turn the LED off, 1 to turn it on
def slice_image(image, axis=None, idx=None): """ Slice an image. Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> mni2 = ants.slice_image(mni, axis=1, idx=100) """ if image.dimension < 3: raise ValueError('image must have at least 3 dimensi...
Slice an image. Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> mni2 = ants.slice_image(mni, axis=1, idx=100)
def _quantize_channelwise_linear(weight, nbits, axis=0): """ Linearly quantize weight blob. :param weight: numpy.array Weight to be quantized. :param nbits: int Number of bits per weight element :param axis: int Axis of the weight blob to compute channel-wise quantization,...
Linearly quantize weight blob. :param weight: numpy.array Weight to be quantized. :param nbits: int Number of bits per weight element :param axis: int Axis of the weight blob to compute channel-wise quantization, can be 0 or 1 Returns ------- quantized_weight: numpy.a...
def limit(self, n, skip=None): """ Limit the result set. However when the query set already has limit field before, this would raise an exception :Parameters: - n : The maximum number of rows returned - skip: how many rows to skip :Return: a new QuerySet object so...
Limit the result set. However when the query set already has limit field before, this would raise an exception :Parameters: - n : The maximum number of rows returned - skip: how many rows to skip :Return: a new QuerySet object so we can chain operations
def close_project(self): """ Close current project and return to a window without an active project """ if self.current_active_project: self.switch_to_plugin() if self.main.editor is not None: self.set_project_filenames( ...
Close current project and return to a window without an active project
def __make_thumbnail(self, width, height): """ Create the page's thumbnail """ (w, h) = self.size factor = max( (float(w) / width), (float(h) / height) ) w /= factor h /= factor return self.get_image((round(w), round(h)))
Create the page's thumbnail
def _get_sv_exclude_file(items): """Retrieve SV file of regions to exclude. """ sv_bed = utils.get_in(items[0], ("genome_resources", "variation", "sv_repeat")) if sv_bed and os.path.exists(sv_bed): return sv_bed
Retrieve SV file of regions to exclude.
def _preprocess(project_dict): """Pre-process certain special keys to convert them from None values into empty containers, and to turn strings into arrays of strings. """ handlers = { ('archive',): _list_if_none, ('on-run-start',): _list_if_none_or_string, ...
Pre-process certain special keys to convert them from None values into empty containers, and to turn strings into arrays of strings.
def build_options(payload, options, maxsize = 576, overload = OVERLOAD_FILE | OVERLOAD_SNAME, allowpartial = True): ''' Split a list of options This is the reverse operation of `reassemble_options`, it splits `dhcp_option` into `dhcp_option_partial` if necessary, and set overload option if field ov...
Split a list of options This is the reverse operation of `reassemble_options`, it splits `dhcp_option` into `dhcp_option_partial` if necessary, and set overload option if field overloading is used. :param options: a list of `dhcp_option` :param maxsize: Limit the maximum DHCP message ...
def run_cmd(cmd, return_output=False, ignore_status=False, log_output=True, **kwargs): """ run provided command on host system using the same user as you invoked this code, raises subprocess.CalledProcessError if it fails :param cmd: list of str :param return_output: bool, return output of the comm...
run provided command on host system using the same user as you invoked this code, raises subprocess.CalledProcessError if it fails :param cmd: list of str :param return_output: bool, return output of the command :param ignore_status: bool, do not fail in case nonzero return code :param log_output: ...
def send_media_group(chat_id, media, reply_to_message_id=None, disable_notification=False, **kwargs): """ Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned. :param chat_id: Unique identifier for t...
Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :param media: A list of InputMedia objects to be sent, must include 2–...
def common_req(self, execute, send_body=True): "Common code for GET and POST requests" self._SERVER = {'CLIENT_ADDR_HOST': self.client_address[0], 'CLIENT_ADDR_PORT': self.client_address[1]} self._to_log = True self._cmd ...
Common code for GET and POST requests
def derivative(self, x): """Derivative of the broadcast operator. Parameters ---------- x : `domain` element The point to take the derivative in Returns ------- adjoint : linear `BroadcastOperator` The derivative Examples ...
Derivative of the broadcast operator. Parameters ---------- x : `domain` element The point to take the derivative in Returns ------- adjoint : linear `BroadcastOperator` The derivative Examples -------- Example with an af...
def cancel_registration(self): """ Cancels the currents client's account with the server. Even if the cancelation is succesful, this method will raise an exception due to he account no longer exists for the server, so the client will fail. To continue with the execution,...
Cancels the currents client's account with the server. Even if the cancelation is succesful, this method will raise an exception due to he account no longer exists for the server, so the client will fail. To continue with the execution, this method should be surrounded by a try/...
def masked_arith_op(x, y, op): """ If the given arithmetic operation fails, attempt it again on only the non-null elements of the input array(s). Parameters ---------- x : np.ndarray y : np.ndarray, Series, Index op : binary operator """ # For Series `x` is 1D so ravel() is a no...
If the given arithmetic operation fails, attempt it again on only the non-null elements of the input array(s). Parameters ---------- x : np.ndarray y : np.ndarray, Series, Index op : binary operator
def _get_columns(self, X, cols): """ Get a subset of columns from the given table X. X a Pandas dataframe; the table to select columns from cols a string or list of strings representing the columns to select Returns a numpy array with the data from the se...
Get a subset of columns from the given table X. X a Pandas dataframe; the table to select columns from cols a string or list of strings representing the columns to select Returns a numpy array with the data from the selected columns
def valid_level(value): """Validation function for parser, logging level argument.""" value = value.upper() if getattr(logging, value, None) is None: raise argparse.ArgumentTypeError("%s is not a valid level" % value) return value
Validation function for parser, logging level argument.
def get_filetypes(filelist, path=None, size=os.path.getsize): """ Get a sorted list of file types and their weight in percent from an iterable of file names. @return: List of weighted file extensions (no '.'), sorted in descending order @rtype: list of (weight, filetype) """ path = ...
Get a sorted list of file types and their weight in percent from an iterable of file names. @return: List of weighted file extensions (no '.'), sorted in descending order @rtype: list of (weight, filetype)
def to_frame(self, *args): """Convert the cells in the view into a DataFrame object. If ``args`` is not given, this method returns a DataFrame that has an Index or a MultiIndex depending of the number of cells parameters and columns each of which corresponds to each cells includ...
Convert the cells in the view into a DataFrame object. If ``args`` is not given, this method returns a DataFrame that has an Index or a MultiIndex depending of the number of cells parameters and columns each of which corresponds to each cells included in the view. ``args`` can ...
def _update_object_map(self, obj_map): """stub""" creation_time = obj_map['creationTime'] obj_map['creationTime'] = dict() obj_map['creationTime']['year'] = creation_time.year obj_map['creationTime']['month'] = creation_time.month obj_map['creationTime']['day'] = creation...
stub
def invert(self): """ Multiplying a matrix by its inverse produces the identity matrix. """ m = self.matrix d = m[0] * m[4] - m[1] * m[3] self.matrix = [ m[4] / d, -m[1] / d, 0, -m[3] / d, m[0] / d, 0, (m[3] * m[7] - m[4] * m[6]) / ...
Multiplying a matrix by its inverse produces the identity matrix.
def setHintColor(self, color): """ Sets the hint color for this combo box provided its line edit is an XLineEdit instance. :param color | <QColor> """ lineEdit = self.lineEdit() if isinstance(lineEdit, XLineEdit): lineEdit.setHintColor(co...
Sets the hint color for this combo box provided its line edit is an XLineEdit instance. :param color | <QColor>
def create_project_config_path( path, mode=0o777, parents=False, exist_ok=False ): """Create new project configuration folder.""" # FIXME check default directory mode project_path = Path(path).absolute().joinpath(RENKU_HOME) project_path.mkdir(mode=mode, parents=parents, exist_ok=exist_ok) retur...
Create new project configuration folder.
def _determine_supported_alleles(command, supported_allele_flag): """ Try asking the commandline predictor (e.g. netMHCpan) which alleles it supports. """ try: # convert to str since Python3 returns a `bytes` object supported_alleles_output = check_output(...
Try asking the commandline predictor (e.g. netMHCpan) which alleles it supports.
def write_document(self, gh_user, doc_id, file_content, branch, author, commit_msg=None): """Given a document id, temporary filename of content, branch and auth_info Deprecated but needed until we merge api local-dep to master... """ parent_sha = None fc = tempfile.NamedTempora...
Given a document id, temporary filename of content, branch and auth_info Deprecated but needed until we merge api local-dep to master...
def json_dumps(inbox): """ Serializes the first element of the input using the JSON protocol as implemented by the ``json`` Python 2.6 library. """ gc.disable() str_ = json.dumps(inbox[0]) gc.enable() return str_
Serializes the first element of the input using the JSON protocol as implemented by the ``json`` Python 2.6 library.
def _single_orbit_find_actions(orbit, N_max, toy_potential=None, force_harmonic_oscillator=False): """ Find approximate actions and angles for samples of a phase-space orbit, `w`, at times `t`. Uses toy potentials with known, analytic action-angle transformations to approx...
Find approximate actions and angles for samples of a phase-space orbit, `w`, at times `t`. Uses toy potentials with known, analytic action-angle transformations to approximate the true coordinates as a Fourier sum. This code is adapted from Jason Sanders' `genfunc <https://github.com/jlsanders/genfunc>...
def link(self, href, **kwargs): """Retuns a new link relative to this resource.""" return link.Link(dict(href=href, **kwargs), self.base_uri)
Retuns a new link relative to this resource.
def __meta_metadata(self, field, key): """Return the value for key for the field in the metadata""" mf = '' try: mf = str([f[key] for f in self.metadata if f['field_name'] == field][0]) except IndexError: print("%s not in metadata field:%s" % ...
Return the value for key for the field in the metadata
def copy(self): """Return a deep copy""" result = Scalar(self.size, self.deriv) result.v = self.v if self.deriv > 0: result.d[:] = self.d[:] if self.deriv > 1: result.dd[:] = self.dd[:] return result
Return a deep copy
def return_features_numpy_base(dbpath, set_object, points_amt, names): """ Generic function which returns a 2d numpy array of extracted features Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the database ...
Generic function which returns a 2d numpy array of extracted features Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the database points_amt : int, number of data points in the database names : list of stri...
def running(concurrent=False): ''' Return a list of strings that contain state return data if a state function is already running. This function is used to prevent multiple state calls from being run at the same time. CLI Example: .. code-block:: bash salt '*' state.running ''' ...
Return a list of strings that contain state return data if a state function is already running. This function is used to prevent multiple state calls from being run at the same time. CLI Example: .. code-block:: bash salt '*' state.running
def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): """Issues a request to create a table or view in the specified dataset with the specified id. A schema must be provided to create a Table, or a query must be provided to create a View. ...
Issues a request to create a table or view in the specified dataset with the specified id. A schema must be provided to create a Table, or a query must be provided to create a View. Args: table_name: the name of the table as a tuple of components. schema: the schema, if this is a Table creation....