code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def ProcesarPlantillaPDF(self, num_copias=1, lineas_max=24, qty_pos='izq', clave=''): "Generar el PDF según la factura creada y plantilla cargada" try: f = self.template liq = self.params_out # actualizo los campos según la clave (a...
Generar el PDF según la factura creada y plantilla cargada
def convert(self, to_mag, from_mag=None): """ Converts magnitudes using UBVRIJHKLMNQ photometry in Taurus-Auriga (Kenyon+ 1995) ReadMe+ftp1995ApJS..101..117K Colors for main-sequence stars If from_mag isn't specified the program will cycle through provided magnitudes and choose one. Note that...
Converts magnitudes using UBVRIJHKLMNQ photometry in Taurus-Auriga (Kenyon+ 1995) ReadMe+ftp1995ApJS..101..117K Colors for main-sequence stars If from_mag isn't specified the program will cycle through provided magnitudes and choose one. Note that all magnitudes are first converted to V, and...
def parse_interval(interval): """ Attepmt to parse an ISO8601 formatted ``interval``. Returns a tuple of ``datetime.datetime`` and ``datetime.timedelta`` objects, order dependent on ``interval``. """ a, b = str(interval).upper().strip().split('/') if a[0] is 'P' and b[0] is 'P': ra...
Attepmt to parse an ISO8601 formatted ``interval``. Returns a tuple of ``datetime.datetime`` and ``datetime.timedelta`` objects, order dependent on ``interval``.
def rdl_decomposition(T, k=None, reversible=False, norm='standard', mu=None): r"""Compute the decomposition into left and right eigenvectors. Parameters ---------- T : (M, M) ndarray Transition matrix k : int (optional) Number of eigenvector/eigenvalue pairs norm: {'standard', '...
r"""Compute the decomposition into left and right eigenvectors. Parameters ---------- T : (M, M) ndarray Transition matrix k : int (optional) Number of eigenvector/eigenvalue pairs norm: {'standard', 'reversible', 'auto'} standard: (L'R) = Id, L[:,0] is a probability distrib...
def describe_table(self, table_name): """ Polls until the table is ready, then returns the first result when the table was ready. The returned dict is standardized to ensure all fields are present, even when empty or across different DynamoDB API versions. TTL information is als...
Polls until the table is ready, then returns the first result when the table was ready. The returned dict is standardized to ensure all fields are present, even when empty or across different DynamoDB API versions. TTL information is also inserted. :param table_name: The name of the ta...
def _parse_abbreviation(uri_link): """ Returns a team's abbreviation. A school or team's abbreviation is generally embedded in a URI link which contains other relative link information. For example, the URI for the New England Patriots for the 2017 season is "/teams/nwe/2017.htm". This function...
Returns a team's abbreviation. A school or team's abbreviation is generally embedded in a URI link which contains other relative link information. For example, the URI for the New England Patriots for the 2017 season is "/teams/nwe/2017.htm". This function strips all of the contents before and after "n...
def get(img, cache_dir=CACHE_DIR, iterative=False): """Validate image input.""" if os.path.isfile(img): wal_img = img elif os.path.isdir(img): if iterative: wal_img = get_next_image(img) else: wal_img = get_random_image(img) else: logging.error(...
Validate image input.
def run_algorithms(file_struct, boundaries_id, labels_id, config, annotator_id=0): """Runs the algorithms with the specified identifiers on the audio_file. Parameters ---------- file_struct: `msaf.io.FileStruct` Object with the file paths. boundaries_id: str Ident...
Runs the algorithms with the specified identifiers on the audio_file. Parameters ---------- file_struct: `msaf.io.FileStruct` Object with the file paths. boundaries_id: str Identifier of the boundaries algorithm to use ("gt" for ground truth). labels_id: str Identifier of th...
def requirements_check(): """ Ensure we have programs needed to download/manipulate the data """ required_programs = [ ('samtools', 'http://samtools.sourceforge.net/'), ('bedtools', 'http://bedtools.readthedocs.org/en/latest/'), ('bigWigToBedGraph', 'ht...
Ensure we have programs needed to download/manipulate the data
def list(self, identity=values.unset, limit=None, page_size=None): """ Lists MemberInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param unicode identity: The `identity` value of the r...
Lists MemberInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param unicode identity: The `identity` value of the resources to read :param int limit: Upper limit for the number of records to ret...
def make_image(location, size, fmt): ''' Create a blank virtual machine image file of the specified size in megabytes. The image can be created in any format supported by qemu CLI Example: .. code-block:: bash salt '*' qemu_img.make_image /tmp/image.qcow 2048 qcow2 salt '*' qemu_i...
Create a blank virtual machine image file of the specified size in megabytes. The image can be created in any format supported by qemu CLI Example: .. code-block:: bash salt '*' qemu_img.make_image /tmp/image.qcow 2048 qcow2 salt '*' qemu_img.make_image /tmp/image.raw 10240 raw
def create_content_type(json): """Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance. """ result = ContentType(json['sys']) for field in json['fields']: field_id = field['id'] del field['id'] ...
Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance.
def make_primitive(cas_coords, window_length=3): """Calculates running average of cas_coords with a fixed averaging window_length. Parameters ---------- cas_coords : list(numpy.array or float or tuple) Each element of the list must have length 3. window_length : int, optional The nu...
Calculates running average of cas_coords with a fixed averaging window_length. Parameters ---------- cas_coords : list(numpy.array or float or tuple) Each element of the list must have length 3. window_length : int, optional The number of coordinate sets to average each time. Retur...
def base_warfare(name, bases, attributes): """ Adds any number of attributes to an existing class. :param name: Name. :type name: unicode :param bases: Bases. :type bases: list :param attributes: Attributes. :type attributes: dict :return: Base. :rtype: object """ asser...
Adds any number of attributes to an existing class. :param name: Name. :type name: unicode :param bases: Bases. :type bases: list :param attributes: Attributes. :type attributes: dict :return: Base. :rtype: object
def _translate_string(self, data, length): """Translate string into character texture positions""" for index, char in enumerate(data): if index == length: break yield self._meta.characters - 1 - self._ct[char]
Translate string into character texture positions
def publish(self, topic, data, defer=None): """Publish a message to the given topic over tcp. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in milliseconds to defer before publishing (requires nsq 0.3.6) """ ...
Publish a message to the given topic over tcp. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in milliseconds to defer before publishing (requires nsq 0.3.6)
def Cps(self): r'''Solid-phase heat capacity of the chemical at its current temperature, in units of [J/kg/K]. For calculation of this property at other temperatures, or specifying manually the method used to calculate it, and more - see the object oriented interface :obj:`thermo...
r'''Solid-phase heat capacity of the chemical at its current temperature, in units of [J/kg/K]. For calculation of this property at other temperatures, or specifying manually the method used to calculate it, and more - see the object oriented interface :obj:`thermo.heat_capacity.HeatCapa...
def mk_external_entity(metamodel, s_ee): ''' Create a python object from a BridgePoint external entity with bridges realized as python member functions. ''' bridges = many(s_ee).S_BRG[19]() names = [brg.Name for brg in bridges] EE = collections.namedtuple(s_ee.Key_Lett, names) funcs = l...
Create a python object from a BridgePoint external entity with bridges realized as python member functions.
def callback(self, *incoming): """ Gets called by the CallbackManager if a new message was received """ message = incoming[0] if message: address, command = message[0], message[2] profile = self.get_profile(address) if profile is not None: ...
Gets called by the CallbackManager if a new message was received
def _updateToAdded(self,directory,fn,dentry,db,service): """Changes to status to 'A' as long as a handler exists, also generates a hash directory - DIR where stuff is happening fn - File name to be added dentry - dictionary entry as returned by GetStatus for this file db ...
Changes to status to 'A' as long as a handler exists, also generates a hash directory - DIR where stuff is happening fn - File name to be added dentry - dictionary entry as returned by GetStatus for this file db - pusher DB for this directory service - None means all serv...
def out_of_bag_mae(self): """ Returns the mean absolute error for predictions on the out-of-bag samples. """ if not self._out_of_bag_mae_clean: try: self._out_of_bag_mae = self.test(self.out_of_bag_samples) self._out_of_bag_mae_clean = ...
Returns the mean absolute error for predictions on the out-of-bag samples.
def _load_metadata(self): """load metadata only if needed""" if self._schema is None: self._schema = self._get_schema() self.datashape = self._schema.datashape self.dtype = self._schema.dtype self.shape = self._schema.shape self.npartitions = s...
load metadata only if needed
def message(self, data): """Function to display messages to the user """ msg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, data) msg.set_resizable(1) msg.set_title(self.dialog_title) self.img.set_from_file...
Function to display messages to the user
def custom_field_rendering(context, field, *args, **kwargs): """ Wrapper for rendering the field via an external renderer """ if CUSTOM_FIELD_RENDERER: mod, cls = CUSTOM_FIELD_RENDERER.rsplit(".", 1) field_renderer = getattr(import_module(mod), cls) if field_renderer: return ...
Wrapper for rendering the field via an external renderer
def action(route, template='', methods=['GET']): """Decorator to create an action""" def real_decorator(function): function.pi_api_action = True function.pi_api_route = route function.pi_api_template = template function.pi_api_methods = methods if hasattr(function, 'pi_a...
Decorator to create an action
def _parse_tables(cls, parsed_content): """ Parses the information tables contained in a character's page. Parameters ---------- parsed_content: :class:`bs4.BeautifulSoup` A :class:`BeautifulSoup` object containing all the content. Returns ------- ...
Parses the information tables contained in a character's page. Parameters ---------- parsed_content: :class:`bs4.BeautifulSoup` A :class:`BeautifulSoup` object containing all the content. Returns ------- :class:`OrderedDict`[str, :class:`list`of :class:`bs4....
def alias_event_handler(_, **kwargs): """ An event handler for alias transformation when EVENT_INVOKER_PRE_TRUNCATE_CMD_TBL event is invoked. """ try: telemetry.start() start_time = timeit.default_timer() args = kwargs.get('args') alias_manager = AliasManager(**kwargs) ...
An event handler for alias transformation when EVENT_INVOKER_PRE_TRUNCATE_CMD_TBL event is invoked.
def serialize(self, node: SchemaNode, appstruct: Union[PotentialDatetimeType, ColanderNullType]) \ -> Union[str, ColanderNullType]: """ Serializes Python object to string representation. """ if not appstru...
Serializes Python object to string representation.
def build_frame(command, payload): """Build raw bytes from command and payload.""" packet_length = 2 + len(payload) + 1 ret = struct.pack("BB", 0, packet_length) ret += struct.pack(">H", command.value) ret += payload ret += struct.pack("B", calc_crc(ret)) return r...
Build raw bytes from command and payload.
def create_throttle(): """ Create a THROTTLE statement """ throttle_amount = "*" | Combine(number + "%") | number return Group( function("throttle", throttle_amount, throttle_amount, caseless=True) ).setResultsName("throttle")
Create a THROTTLE statement
def save_webdriver_logs(self, test_name): """Get webdriver logs and write them to log files :param test_name: test that has generated these logs """ try: log_types = self.driver_wrapper.driver.log_types except Exception: # geckodriver does not implement l...
Get webdriver logs and write them to log files :param test_name: test that has generated these logs
def profile_add(user, profile): ''' Add profile to user user : string username profile : string profile name CLI Example: .. code-block:: bash salt '*' rbac.profile_add martine 'Primary Administrator' salt '*' rbac.profile_add martine 'User Management,User Sec...
Add profile to user user : string username profile : string profile name CLI Example: .. code-block:: bash salt '*' rbac.profile_add martine 'Primary Administrator' salt '*' rbac.profile_add martine 'User Management,User Security'
def place(vertices_resources, nets, machine, constraints, vertex_order=None, chip_order=None): """Blindly places vertices in sequential order onto chips in the machine. This algorithm sequentially places vertices onto chips in the order specified (or in an undefined order if not specified). This ...
Blindly places vertices in sequential order onto chips in the machine. This algorithm sequentially places vertices onto chips in the order specified (or in an undefined order if not specified). This algorithm is essentially the simplest possible valid placement algorithm and is intended to form the bas...
def draw(filestems, gformat): """Draw ANIb/ANIm/TETRA results - filestems - filestems for output files - gformat - the format for output graphics """ # Draw heatmaps for filestem in filestems: fullstem = os.path.join(args.outdirname, filestem) outfilename = fullstem + ".%s" % gf...
Draw ANIb/ANIm/TETRA results - filestems - filestems for output files - gformat - the format for output graphics
def run(self, *, connector: Union[EnvVar, Token, SlackClient, None] = None, interval: float = 0.5, retries: int = 16, backoff: Callable[[int], float] = None, until: Callable[[List[dict]], bool] = None) -> None: """ Connect to the Slack API and run the even...
Connect to the Slack API and run the event handler loop. Args: connector: A means of connecting to the Slack API. This can be an API :obj:`Token`, an :obj:`EnvVar` from which a token can be retrieved, or an established :obj:`SlackClient` instance. If ...
def get_facet_objects_serializer(self, *args, **kwargs): """ Return the serializer instance which should be used for serializing faceted objects. """ facet_objects_serializer_class = self.get_facet_objects_serializer_class() kwargs["context"] = self.get_serializer_context...
Return the serializer instance which should be used for serializing faceted objects.
def grow(self, width, height=None): """ Expands the region by ``width`` on both sides and ``height`` on the top and bottom. If only one value is provided, expands the region by that amount on all sides. Equivalent to ``nearby()``. """ if height is None: return self.n...
Expands the region by ``width`` on both sides and ``height`` on the top and bottom. If only one value is provided, expands the region by that amount on all sides. Equivalent to ``nearby()``.
def on(self, dev_id): """Turn ON all features of the device. schedules, weather intelligence, water budget, etc. """ path = 'device/on' payload = {'id': dev_id} return self.rachio.put(path, payload)
Turn ON all features of the device. schedules, weather intelligence, water budget, etc.
def analog_sensor_power(cls, bus, operation): """ Method that turns on all of the analog sensor modules Includes all attached soil moisture sensors Note that all of the SensorCluster object should be attached in parallel and only 1 GPIO pin is available ...
Method that turns on all of the analog sensor modules Includes all attached soil moisture sensors Note that all of the SensorCluster object should be attached in parallel and only 1 GPIO pin is available to toggle analog sensor power. The sensor p...
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' mtype = m.get_type() if mtype in ['WAYPOINT_COUNT','MISSION_COUNT']: if self.wp_op is None: self.console.error("No waypoint load started") else: self.wploader.clear() ...
handle an incoming mavlink packet
def which_with_node_modules(self): """ Which with node_path and node_modules """ if self.binary is None: return None # first, log down the pedantic things... if isdir(self.join_cwd(NODE_MODULES)): logger.debug( "'%s' instance will...
Which with node_path and node_modules
def make_script_directory(cls, config): """ Alembic uses a "script directory" to encapsulate its `env.py` file, its migrations directory, and its `script.py.mako` revision template. We'd rather not have such a directory at all as the default `env.py` rarely works without manipulation, migrations a...
Alembic uses a "script directory" to encapsulate its `env.py` file, its migrations directory, and its `script.py.mako` revision template. We'd rather not have such a directory at all as the default `env.py` rarely works without manipulation, migrations are better saved in a location within the source tree...
def ModuleLogger(globs): """Create a module level logger. To debug a module, create a _debug variable in the module, then use the ModuleLogger function to create a "module level" logger. When a handler is added to this logger or a child of this logger, the _debug variable will be incremented. ...
Create a module level logger. To debug a module, create a _debug variable in the module, then use the ModuleLogger function to create a "module level" logger. When a handler is added to this logger or a child of this logger, the _debug variable will be incremented. All of the calls within functio...
def position_target_global_int_encode(self, time_boot_ms, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): ''' Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This ...
Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This should match the commands sent in SET_POSITION_TARGET_GLOBAL_INT if the vehicle is being controlled this way. time_boot_ms ...
def _make_ssh_forward_handler_class(self, remote_address_): """ Make SSH Handler class """ class Handler(_ForwardHandler): remote_address = remote_address_ ssh_transport = self._transport logger = self.logger return Handler
Make SSH Handler class
def interfaces(self): """Get the wifi interface lists.""" ifaces = [] for f in sorted(os.listdir(CTRL_IFACE_DIR)): sock_file = '/'.join([CTRL_IFACE_DIR, f]) mode = os.stat(sock_file).st_mode if stat.S_ISSOCK(mode): iface = {} ...
Get the wifi interface lists.
def who(self, target): """ Runs a WHO on a target Required arguments: * target - /WHO <target> Returns a dictionary, with a nick as the key and - the value is a list in the form of; [0] - Username [1] - Priv level [2] - Real name ...
Runs a WHO on a target Required arguments: * target - /WHO <target> Returns a dictionary, with a nick as the key and - the value is a list in the form of; [0] - Username [1] - Priv level [2] - Real name [3] - Hostname
def remove_host(kwargs=None, call=None): ''' Remove the specified host system from this VMware environment CLI Example: .. code-block:: bash salt-cloud -f remove_host my-vmware-config host="myHostSystemName" ''' if call != 'function': raise SaltCloudSystemExit( 'Th...
Remove the specified host system from this VMware environment CLI Example: .. code-block:: bash salt-cloud -f remove_host my-vmware-config host="myHostSystemName"
def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' helper function to validate tags are correct ''' ret = {'result': True, 'comment': '', 'changes': {}} if tags: sg = __salt__['boto_secgroup.get_config'](name=name...
helper function to validate tags are correct
def member_command(self, member_id, command): """apply command (start/stop/restart) to member instance of replica set Args: member_id - member index command - string command (start/stop/restart) return True if operation success otherwise False """ server_...
apply command (start/stop/restart) to member instance of replica set Args: member_id - member index command - string command (start/stop/restart) return True if operation success otherwise False
def pulse_train(time, start, duration, repeat_time, end): """ Implements vensim's PULSE TRAIN function In range [-inf, start) returns 0 In range [start + n * repeat_time, start + n * repeat_time + duration) return 1 In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0 ...
Implements vensim's PULSE TRAIN function In range [-inf, start) returns 0 In range [start + n * repeat_time, start + n * repeat_time + duration) return 1 In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0
def bytes_block_cast(block, include_text=True, include_link_tokens=True, include_css=True, include_features=True, **kwargs): """ Converts any string-like items in input Block object to bytes-like values, ...
Converts any string-like items in input Block object to bytes-like values, with respect to python version Parameters ---------- block : blocks.Block any string-like objects contained in the block object will be converted to bytes include_text : bool, default=True if True, ca...
def load_module(name, filename): '''Load a module into name given its filename''' if sys.version_info < (3, 5): import imp import warnings with warnings.catch_warnings(): # Required for Python 2.7 warnings.simplefilter("ignore", RuntimeWarning) return imp.load_so...
Load a module into name given its filename
def midl_emitter(target, source, env): """Produces a list of outputs from the MIDL compiler""" base, _ = SCons.Util.splitext(str(target[0])) tlb = target[0] incl = base + '.h' interface = base + '_i.c' targets = [tlb, incl, interface] midlcom = env['MIDLCOM'] if midlcom.find('/proxy') ...
Produces a list of outputs from the MIDL compiler
def delete(self, container, del_objects=False): """ Deletes the specified container. If the container contains objects, the command will fail unless 'del_objects' is passed as True. In that case, each object will be deleted first, and then the container. """ if del_object...
Deletes the specified container. If the container contains objects, the command will fail unless 'del_objects' is passed as True. In that case, each object will be deleted first, and then the container.
def _post(url:str, params:dict, headers:dict) -> dict: """ Make a POST call. """ response = requests.post(url, params=params, headers=headers) data = response.json() if response.status_code != 200 or "error" in data: raise GoogleApiError({"status_code": response.status_code, ...
Make a POST call.
def public_ip_addresses_list(resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 List all public IP addresses within a resource group. :param resource_group: The resource group name to list public IP addresses within. CLI Example: .. code-block:: bash salt-call azurear...
.. versionadded:: 2019.2.0 List all public IP addresses within a resource group. :param resource_group: The resource group name to list public IP addresses within. CLI Example: .. code-block:: bash salt-call azurearm_network.public_ip_addresses_list testgroup
def send_data_message( self, condition=None, collapse_key=None, delay_while_idle=False, time_to_live=None, restricted_package_name=None, low_priority=False, dry_run=False, data_message=None, content_a...
Send single data message.
def build_response(self, response, path=None, parser=json_decode_wrapper, async=False): """ Builds a List or Dict response object. Wrapper for a response from the DataSift REST API, can be accessed as a list. :param response: HTTP response to wrap :type response: :class:`~d...
Builds a List or Dict response object. Wrapper for a response from the DataSift REST API, can be accessed as a list. :param response: HTTP response to wrap :type response: :class:`~datasift.requests.DictResponse` :param parser: optional parser to overload how the data i...
def main(connection_file): """watch iopub channel, and print messages""" ctx = zmq.Context.instance() with open(connection_file) as f: cfg = json.loads(f.read()) location = cfg['location'] reg_url = cfg['url'] session = Session(key=str_to_bytes(cfg['exec_key'])) q...
watch iopub channel, and print messages
def _do_scale(image, size): """Rescale the image by scaling the smaller spatial dimension to `size`.""" shape = tf.cast(tf.shape(image), tf.float32) w_greater = tf.greater(shape[0], shape[1]) shape = tf.cond(w_greater, lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32), ...
Rescale the image by scaling the smaller spatial dimension to `size`.
def move_field_m2o( cr, pool, registry_old_model, field_old_model, m2o_field_old_model, registry_new_model, field_new_model, quick_request=True, compute_func=None, binary_field=False): """ Use that function in the following case: A field moves from a model A to the model B wi...
Use that function in the following case: A field moves from a model A to the model B with : A -> m2o -> B. (For exemple product_product -> product_template) This function manage the migration of this field. available on post script migration. :param registry_old_model: registry of the model A; :...
def install(self, ref, table_name=None, index_columns=None,logger=None): """ Finds partition by reference and installs it to warehouse db. Args: ref (str): id, vid (versioned id), name or vname (versioned name) of the partition. """ try: obj_number = ObjectNum...
Finds partition by reference and installs it to warehouse db. Args: ref (str): id, vid (versioned id), name or vname (versioned name) of the partition.
def run(self): """run the model""" model = self.model configfile = self.configfile interval = self.interval sockets = self.sockets model.initialize(configfile) if model.state == 'pause': logger.info( "model initialized and started in ...
run the model
def com_google_fonts_check_family_single_directory(fonts): """Checking all files are in the same directory. If the set of font files passed in the command line is not all in the same directory, then we warn the user since the tool will interpret the set of files as belonging to a single family (and it is unlik...
Checking all files are in the same directory. If the set of font files passed in the command line is not all in the same directory, then we warn the user since the tool will interpret the set of files as belonging to a single family (and it is unlikely that the user would store the files from a single family s...
def makeLinearcFunc(self,mNrm,cNrm): ''' Make a linear interpolation to represent the (unconstrained) consumption function conditional on the current period state. Parameters ---------- mNrm : np.array Array of normalized market resource values for interpolat...
Make a linear interpolation to represent the (unconstrained) consumption function conditional on the current period state. Parameters ---------- mNrm : np.array Array of normalized market resource values for interpolation. cNrm : np.array Array of normali...
def _inflate(cls, data): """Update config by deserialising input dictionary""" for k, v in data[Constants.CONFIG_KEY].items(): setattr(cls, k, v) return cls._deflate()
Update config by deserialising input dictionary
def police_priority_map_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer") name = ET.SubElement(police_priority_map, "name") name.t...
Auto Generated Code
def process_text(text, out_format='json_ld', save_json='eidos_output.json', webservice=None): """Return an EidosProcessor by processing the given text. This constructs a reader object via Java and extracts mentions from the text. It then serializes the mentions into JSON and processes ...
Return an EidosProcessor by processing the given text. This constructs a reader object via Java and extracts mentions from the text. It then serializes the mentions into JSON and processes the result with process_json. Parameters ---------- text : str The text to be processed. out_...
def parent_for_matching_rest_name(self, rest_names): """ Return parent that matches a rest name """ parent = self while parent: if parent.rest_name in rest_names: return parent parent = parent.parent_object return None
Return parent that matches a rest name
def crypto_secretstream_xchacha20poly1305_init_push(state, key): """ Initialize a crypto_secretstream_xchacha20poly1305 encryption buffer. :param state: a secretstream state object :type state: crypto_secretstream_xchacha20poly1305_state :param key: must be :data:`.crypto_secretstre...
Initialize a crypto_secretstream_xchacha20poly1305 encryption buffer. :param state: a secretstream state object :type state: crypto_secretstream_xchacha20poly1305_state :param key: must be :data:`.crypto_secretstream_xchacha20poly1305_KEYBYTES` long :type key: bytes :return: header ...
def mequ(m1): """ Set one double precision 3x3 matrix equal to another. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mequ_c.html :param m1: input matrix. :type m1: 3x3-Element Array of floats :return: Output matrix equal to m1. :rtype: 3x3-Element Array of floats """ m1 ...
Set one double precision 3x3 matrix equal to another. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mequ_c.html :param m1: input matrix. :type m1: 3x3-Element Array of floats :return: Output matrix equal to m1. :rtype: 3x3-Element Array of floats
def _fill(self): """Fill self with variable information.""" types_to_exclude = ['module', 'function', 'builtin_function_or_method', 'instance', '_Feature', 'type', 'ufunc'] values = self.namespace.who_ls() def eval(expr): return self.namespace.she...
Fill self with variable information.
def index(): """Index page with uploader and list of existing depositions.""" ctx = mycommunities_ctx() p = request.args.get('p', type=str) so = request.args.get('so', type=str) page = request.args.get('page', type=int, default=1) so = so or current_app.config.get('COMMUNITIES_DEFAULT_SORTING_...
Index page with uploader and list of existing depositions.
def partition(self, id_): """Get a partition by the id number. Arguments: id_ -- a partition id value Returns: A partitions.Partition object Throws: a Sqlalchemy exception if the partition either does not exist or is not unique ...
Get a partition by the id number. Arguments: id_ -- a partition id value Returns: A partitions.Partition object Throws: a Sqlalchemy exception if the partition either does not exist or is not unique Because this method works on the bund...
def inverseHistogram(hist, bin_range): """sample data from given histogram and min, max values within range Returns: np.array: data that would create the same histogram as given """ data = hist.astype(float) / np.min(hist[np.nonzero(hist)]) new_data = np.empty(shape=np.sum(data, dtype=int))...
sample data from given histogram and min, max values within range Returns: np.array: data that would create the same histogram as given
def serialize_dict_keys(d, prefix=""): """returns all the keys in nested a dictionary. >>> sorted(serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } })) ['a', 'a.b', 'a.b.b', 'a.b.c'] """ keys = [] for k, v in d.items(): fqk = '{}{}'.format(prefix, k) keys.append(fqk) if ...
returns all the keys in nested a dictionary. >>> sorted(serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } })) ['a', 'a.b', 'a.b.b', 'a.b.c']
def _execute_query(self): '''Execute the query without fetching data. Returns the number of elements in the query.''' pipe = self.pipe if not self.card: if self.meta.ordering: self.ismember = getattr(self.backend.client, 'zrank') self.card = get...
Execute the query without fetching data. Returns the number of elements in the query.
def get_records_with_attachments(attachment_table, rel_object_field="REL_OBJECTID"): """returns a list of ObjectIDs for rows in the attachment table""" if arcpyFound == False: raise Exception("ArcPy is required to use this function") OIDs = [] with arcpy.da.SearchCursor(attachment_table, ...
returns a list of ObjectIDs for rows in the attachment table
def Kdiag(self, X): """Compute the diagonal of the covariance matrix associated to X.""" ret = np.empty(X.shape[0]) ret[:] = self.variance return ret
Compute the diagonal of the covariance matrix associated to X.
def unpack(self, buff, offset=0): """Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begi...
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exc...
def should_be_hidden_as_cause(exc): """ Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error """ # reduced traceback in case of HasWrongType (instance_of checks) from valid8.validation_lib.types import HasWrongType, IsWrongType return isinstance(exc, (H...
Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error
def setValue( self, value ): """ Moves the line to the given value and rebuilds it :param value | <variant> """ scene = self.scene() point = scene.mapFromChart(value, None) self.setPos(point.x(), self.pos().y()) self.rebuil...
Moves the line to the given value and rebuilds it :param value | <variant>
def remove_port_callback(self, port, cb): """Remove a callback for data that comes on a specific port""" logger.debug('Removing callback on port [%d] to [%s]', port, cb) for port_callback in self.cb: if port_callback.port == port and port_callback.callback == cb: self...
Remove a callback for data that comes on a specific port
def verbose(self, msg, *args, **kw): """Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`.""" if self.isEnabledFor(VERBOSE): self._log(VERBOSE, msg, args, **kw)
Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`.
def verify_checksum(message, previous_csum=0): """Verify checksum for incoming message. :param message: incoming message :param previous_csum: accumulated checksum value :return return True if message checksum type is None or checksum is correct """ if message.message_type in CHECKSUM_MSG_...
Verify checksum for incoming message. :param message: incoming message :param previous_csum: accumulated checksum value :return return True if message checksum type is None or checksum is correct
def pack_pipeline(self, commands): '''Packs pipeline commands into bytes.''' return b''.join( starmap(lambda *args: b''.join(self._pack_command(args)), (a for a, _ in commands)))
Packs pipeline commands into bytes.
def _get_min_distance_to_volcanic_front(lons, lats): """ Compute and return minimum distance between volcanic front and points specified by 'lon' and 'lat'. Distance is negative if point is located east of the volcanic front, positive otherwise. The method uses the same approach as :meth:`_get...
Compute and return minimum distance between volcanic front and points specified by 'lon' and 'lat'. Distance is negative if point is located east of the volcanic front, positive otherwise. The method uses the same approach as :meth:`_get_min_distance_to_sub_trench` but final distance is returned w...
def wishart_pairwise_pvals(self, axis=0): """Return matrices of column-comparison p-values as list of numpy.ndarrays. Square, symmetric matrix along *axis* of pairwise p-values for the null hypothesis that col[i] = col[j] for each pair of columns. *axis* (int): axis along which to perf...
Return matrices of column-comparison p-values as list of numpy.ndarrays. Square, symmetric matrix along *axis* of pairwise p-values for the null hypothesis that col[i] = col[j] for each pair of columns. *axis* (int): axis along which to perform comparison. Only columns (0) are implemen...
def _digest_md5_authentication(self, login, password, authz_id=""): """SASL DIGEST-MD5 authentication :param login: username :param password: clear password :return: True on success, False otherwise. """ code, data, challenge = \ self.__send_command("AUTHENTI...
SASL DIGEST-MD5 authentication :param login: username :param password: clear password :return: True on success, False otherwise.
def combine(self, expert_out, multiply_by_gates=True): """Sum together the expert output, multiplied by the corresponding gates. Args: expert_out: a list of `num_experts` `Tensor`s, each with shape `[expert_batch_size_i, <extra_output_dims>]`. multiply_by_gates: a boolean. Returns: ...
Sum together the expert output, multiplied by the corresponding gates. Args: expert_out: a list of `num_experts` `Tensor`s, each with shape `[expert_batch_size_i, <extra_output_dims>]`. multiply_by_gates: a boolean. Returns: a list of num_datashards `Tensor`s with shapes `[ba...
def read_stats(self, *stats): """ Read stream statistics from chassis. :param stats: list of requested statistics to read, if empty - read all statistics. """ from ixexplorer.ixe_stream import IxePacketGroupStream sleep_time = 0.1 # in cases we only want few counters but very f...
Read stream statistics from chassis. :param stats: list of requested statistics to read, if empty - read all statistics.
def write_file_lines(self, filename, contents): """Write a file. This is useful when writing a file that may not fit within memory. :param filename: ``str`` :param contents: ``list`` """ with open(filename, 'wb') as f: self.log.debug(contents) f....
Write a file. This is useful when writing a file that may not fit within memory. :param filename: ``str`` :param contents: ``list``
def create_from_binary(cls, mft_config, binary_data, entry_number): #TODO test carefully how to find the correct index entry, specially with NTFS versions < 3 '''Creates a MFTEntry from a binary stream. It correctly process the binary data extracting the MFTHeader, all the attributes and the ...
Creates a MFTEntry from a binary stream. It correctly process the binary data extracting the MFTHeader, all the attributes and the slack information from the binary stream. The binary data WILL be changed to apply the fixup array. Args: mft_config (:obj:`MFTConfig`) - An in...
def from_file(self, file_name=None): """Loads a DataFrame with all the needed info about the experiment""" file_name = self._check_file_name(file_name) with open(file_name, 'r') as infile: top_level_dict = json.load(infile) pages_dict = top_level_dict['info_df'] pa...
Loads a DataFrame with all the needed info about the experiment
def flatten_comments(comments, root_level=0): """ Flatten a PRAW comment tree while preserving the nested level of each comment via the `nested_level` attribute. There are a couple of different ways that the input comment list can be organized depending on its source: ...
Flatten a PRAW comment tree while preserving the nested level of each comment via the `nested_level` attribute. There are a couple of different ways that the input comment list can be organized depending on its source: 1. Comments that are returned from the get_submission() api cal...
def process_notice(self, notice): """ This method is called on notices that need processing. Here, we call ``on_object`` and ``on_account`` slots. """ id = notice["id"] _a, _b, _ = id.split(".") if id in self.subscription_objects: self.on_object(notice) ...
This method is called on notices that need processing. Here, we call ``on_object`` and ``on_account`` slots.
def all_sample_md5s(self, type_tag=None): """Return a list of all md5 matching the type_tag ('exe','pdf', etc). Args: type_tag: the type of sample. Returns: a list of matching samples. """ if type_tag: cursor = self.database[self.sample_coll...
Return a list of all md5 matching the type_tag ('exe','pdf', etc). Args: type_tag: the type of sample. Returns: a list of matching samples.
def free(self): """ Free the parameters with the coordinates (either ra,dec or l,b depending on how the class has been instanced) """ if self._coord_type == 'equatorial': self.ra.fix = False self.dec.fix = False else: self....
Free the parameters with the coordinates (either ra,dec or l,b depending on how the class has been instanced)
def transform(self, features): """Uses the Continuous MDR feature map to construct a new feature from the provided features. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix to transform Returns ---------- array-like:...
Uses the Continuous MDR feature map to construct a new feature from the provided features. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix to transform Returns ---------- array-like: {n_samples} Constructed featu...