Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
367,600
def ProcesarPlantillaPDF(self, num_copias=1, lineas_max=24, qty_pos=, clave=): "Generar el PDF según la factura creada y plantilla cargada" try: f = self.template liq = self.params_out if clave and clave in liq: ...
Generar el PDF según la factura creada y plantilla cargada
367,601
def convert(self, to_mag, from_mag=None): allowed_mags = "UBVJIHKLMN" if from_mag: if to_mag == : return self._convert_to_from(, from_mag) if from_mag == : magV = self.magV else: magV = self._convert_to_from(...
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...
367,602
def parse_interval(interval): a, b = str(interval).upper().strip().split() if a[0] is and b[0] is : raise ParseError() if a[0] != and b[0] != : return parse_date(a), parse_date(b) if a[0] is : a = parse_duration(a) else: a = parse_date(a) if b[0] is : ...
Attepmt to parse an ISO8601 formatted ``interval``. Returns a tuple of ``datetime.datetime`` and ``datetime.timedelta`` objects, order dependent on ``interval``.
367,603
def rdl_decomposition(T, k=None, reversible=False, norm=, mu=None): r if norm == : if is_reversible(T): norm = else: norm = if reversible: R, D, L = rdl_decomposition_rev(T, norm=norm, mu=mu) else: R, D, L = rdl_decomposition_nrev(T, norm=n...
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...
367,604
def describe_table(self, table_name): if table_name in self._tables: return self._tables[table_name] status, description = None, {} calls = 0 while status is not ready: calls += 1 try: description = self.dynamodb_client.describ...
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...
367,605
def _parse_abbreviation(uri_link): abbr = re.sub(r, , uri_link().attr()) abbr = re.sub(r, , abbr) abbr = re.sub(r, , abbr) return abbr.upper()
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...
367,606
def get(img, cache_dir=CACHE_DIR, iterative=False): 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("No valid image file found....
Validate image input.
367,607
def run_algorithms(file_struct, boundaries_id, labels_id, config, annotator_id=0): if config["features"].features.shape[0] <= msaf.config.minimum_frames: logging.warning("Audio file too short, or too many few beats " "estimated. Returning empty estimation...
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...
367,608
def requirements_check(): required_programs = [ (, ), (, ), (, ), (, ), ] for req, url in required_programs: try: p = subprocess.Popen( [req], stderr=subprocess.PIPE, stdout=subprocess.PIPE) ...
Ensure we have programs needed to download/manipulate the data
367,609
def list(self, identity=values.unset, limit=None, page_size=None): return list(self.stream(identity=identity, limit=limit, page_size=page_size, ))
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...
367,610
def make_image(location, size, fmt): ** if not os.path.isabs(location): return if not os.path.isdir(os.path.dirname(location)): return if not __salt__[]( .format( fmt, location, size), python_shell=False): ...
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
367,611
def create_content_type(json): result = ContentType(json[]) for field in json[]: field_id = field[] del field[] result.fields[field_id] = field result.name = json[] result.display_field = json.get() return result
Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance.
367,612
def make_primitive(cas_coords, window_length=3): if len(cas_coords) >= window_length: primitive = [] count = 0 for _ in cas_coords[:-(window_length - 1)]: group = cas_coords[count:count + window_length] average_x = sum([x[0] for x in group]) / window_length ...
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...
367,613
def base_warfare(name, bases, attributes): assert len(bases) == 1, "{0} | object has multiple bases!".format(__name__, name) base = foundations.common.get_first_item(bases) for name, value in attributes.iteritems(): if name != "__metaclass__": setattr(base, name, value) retur...
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
367,614
def _translate_string(self, data, length): for index, char in enumerate(data): if index == length: break yield self._meta.characters - 1 - self._ct[char]
Translate string into character texture positions
367,615
def publish(self, topic, data, defer=None): if defer is None: self.send(nsq.publish(topic, data)) else: self.send(nsq.deferpublish(topic, data, defer))
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)
367,616
def Cps(self): rpalladiumpalladium Cpsm = self.HeatCapacitySolid(self.T) if Cpsm: return property_molar_to_mass(Cpsm, self.MW) return None
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...
367,617
def mk_external_entity(metamodel, s_ee): bridges = many(s_ee).S_BRG[19]() names = [brg.Name for brg in bridges] EE = collections.namedtuple(s_ee.Key_Lett, names) funcs = list() for s_brg in many(s_ee).S_BRG[19](): fn = mk_bridge(metamodel, s_brg) funcs.append(fn) return EE...
Create a python object from a BridgePoint external entity with bridges realized as python member functions.
367,618
def callback(self, *incoming): message = incoming[0] if message: address, command = message[0], message[2] profile = self.get_profile(address) if profile is not None: try: getattr(profile, command)(self, message) ...
Gets called by the CallbackManager if a new message was received
367,619
def _updateToAdded(self,directory,fn,dentry,db,service): services=self.sman.GetServices(fn) if services is None: print("%s - No services handle this file" %(fn)) return servicenames=[] for s in services: servicenames.append...
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...
367,620
def out_of_bag_mae(self): 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 = True except NodeNotReadyToPredict: return return self._out_of_bag_mae....
Returns the mean absolute error for predictions on the out-of-bag samples.
367,621
def _load_metadata(self): 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 = self._schema.npartitions ...
load metadata only if needed
367,622
def message(self, data): 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(self.sun_icon) msg.set_image(self.img) ...
Function to display messages to the user
367,623
def custom_field_rendering(context, field, *args, **kwargs): if CUSTOM_FIELD_RENDERER: mod, cls = CUSTOM_FIELD_RENDERER.rsplit(".", 1) field_renderer = getattr(import_module(mod), cls) if field_renderer: return field_renderer(field, **kwargs).render() return field
Wrapper for rendering the field via an external renderer
367,624
def action(route, template=, methods=[]): 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, ): if not function.pi_api_crossdoma...
Decorator to create an action
367,625
def _parse_tables(cls, parsed_content): tables = parsed_content.find_all(, attrs={"width": "100%"}) output = OrderedDict() for table in tables: title = table.find("td").text output[title] = table.find_all("tr")[1:] return output
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....
367,626
def alias_event_handler(_, **kwargs): try: telemetry.start() start_time = timeit.default_timer() args = kwargs.get() alias_manager = AliasManager(**kwargs) args[:] = alias_manager.transform(args) if is_alias_command([, ], args): load_cmd_t...
An event handler for alias transformation when EVENT_INVOKER_PRE_TRUNCATE_CMD_TBL event is invoked.
367,627
def serialize(self, node: SchemaNode, appstruct: Union[PotentialDatetimeType, ColanderNullType]) \ -> Union[str, ColanderNullType]: if not appstruct: return colander.null try: appstruct = ...
Serializes Python object to string representation.
367,628
def build_frame(command, 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 ret
Build raw bytes from command and payload.
367,629
def create_throttle(): throttle_amount = "*" | Combine(number + "%") | number return Group( function("throttle", throttle_amount, throttle_amount, caseless=True) ).setResultsName("throttle")
Create a THROTTLE statement
367,630
def save_webdriver_logs(self, test_name): try: log_types = self.driver_wrapper.driver.log_types except Exception: log_types = [, ] self.logger.debug("Reading logs from and writing them to log files", .join(log_types)) for log_type in log_ty...
Get webdriver logs and write them to log files :param test_name: test that has generated these logs
367,631
def profile_add(user, profile): *Primary Administrator*User Management,User Security ret = {} profiles = profile.split() known_profiles = profile_list().keys() valid_profiles = [p for p in profiles if p in known_profiles] log.debug( , profiles, known_profiles, ...
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'
367,632
def place(vertices_resources, nets, machine, constraints, vertex_order=None, chip_order=None): if len(vertices_resources) == 0: return {} machine = machine.copy() placements = {} vertices_resources, nets, constraints, substitutions = \ ...
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...
367,633
def draw(filestems, gformat): for filestem in filestems: fullstem = os.path.join(args.outdirname, filestem) outfilename = fullstem + ".%s" % gformat infilename = fullstem + ".tab" df = pd.read_csv(infilename, index_col=0, sep="\t") logger.info("Writing heatmap to %s...
Draw ANIb/ANIm/TETRA results - filestems - filestems for output files - gformat - the format for output graphics
367,634
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: backoff = backoff or _truncated_exponential ...
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 ...
367,635
def get_facet_objects_serializer(self, *args, **kwargs): facet_objects_serializer_class = self.get_facet_objects_serializer_class() kwargs["context"] = self.get_serializer_context() return facet_objects_serializer_class(*args, **kwargs)
Return the serializer instance which should be used for serializing faceted objects.
367,636
def grow(self, width, height=None): if height is None: return self.nearby(width) else: return Region( self.x-width, self.y-height, self.w+(2*width), self.h+(2*height)).clipRegionToScreen()
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()``.
367,637
def on(self, dev_id): path = payload = {: dev_id} return self.rachio.put(path, payload)
Turn ON all features of the device. schedules, weather intelligence, water budget, etc.
367,638
def analog_sensor_power(cls, bus, operation): reg_data = get_IO_reg(bus, 0x20, cls.power_bank) if operation == "on": reg_data = reg_data | 1 << cls.analog_power_pin elif operation == "off": reg_data = reg_data & (0b11111111 ^ (1 << cls.a...
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...
367,639
def mavlink_packet(self, m): mtype = m.get_type() if mtype in [,]: if self.wp_op is None: self.console.error("No waypoint load started") else: self.wploader.clear() self.wploader.expected_count = m.count sel...
handle an incoming mavlink packet
367,640
def which_with_node_modules(self): if self.binary is None: return None if isdir(self.join_cwd(NODE_MODULES)): logger.debug( " instance will attempt to locate binary from " "%s%s%s%s%s, located through the working directory", ...
Which with node_path and node_modules
367,641
def make_script_directory(cls, config): temporary_dir = config.get_main_option("temporary_dir") migrations_dir = config.get_main_option("migrations_dir") return cls( dir=temporary_dir, version_locations=[migrations_dir], )
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...
367,642
def ModuleLogger(globs): if not globs.has_key(): raise RuntimeError("define _debug before creating a module logger") logger_name = globs[] logger = logging.getLogger(logger_name) logger.globs = globs if not in logger_name: hdlr = logging.StreamHandl...
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...
367,643
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): return MAVLink_position_target_global_int_message(time_boot_ms, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, a...
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 ...
367,644
def _make_ssh_forward_handler_class(self, remote_address_): class Handler(_ForwardHandler): remote_address = remote_address_ ssh_transport = self._transport logger = self.logger return Handler
Make SSH Handler class
367,645
def interfaces(self): 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 = {} iface[] = f ifa...
Get the wifi interface lists.
367,646
def who(self, target): with self.lock: self.send( % target) who_lst = {} while self.readable(): msg = self._recv(expected_replies=(, )) if msg[0] == : raw_who = msg[2].split(None, 7) prefix = ra...
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
367,647
def remove_host(kwargs=None, call=None): if call != : raise SaltCloudSystemExit( ) host_name = kwargs.get() if kwargs and in kwargs else None if not host_name: raise SaltCloudSystemExit( ) si = _get_si() host_ref =...
Remove the specified host system from this VMware environment CLI Example: .. code-block:: bash salt-cloud -f remove_host my-vmware-config host="myHostSystemName"
367,648
def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ret = {: True, : , : {}} if tags: sg = __salt__[](name=name, group_id=None, region=region, key=key, keyid=keyid, profile=pr...
helper function to validate tags are correct
367,649
def member_command(self, member_id, command): server_id = self._servers.host_to_server_id( self.member_id_to_host(member_id)) return self._servers.command(server_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
367,650
def pulse_train(time, start, duration, repeat_time, end): t = time() if start <= t < end: return 1 if (t - start) % repeat_time < duration else 0 else: 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
367,651
def bytes_block_cast(block, include_text=True, include_link_tokens=True, include_css=True, include_features=True, **kwargs): if include_text: block.text = bytes_cast(block.text, **kwargs) if inc...
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...
367,652
def load_module(name, filename): if sys.version_info < (3, 5): import imp import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) return imp.load_source(name, filename) else: from importlib.machinery import So...
Load a module into name given its filename
367,653
def midl_emitter(target, source, env): base, _ = SCons.Util.splitext(str(target[0])) tlb = target[0] incl = base + interface = base + targets = [tlb, incl, interface] midlcom = env[] if midlcom.find() != -1: proxy = base + targets.append(proxy) if midlcom.find()...
Produces a list of outputs from the MIDL compiler
367,654
def delete(self, container, del_objects=False): if del_objects: nms = self.list_object_names(container, full_listing=True) self.api.bulk_delete(container, nms, async_=False) uri = "/%s" % utils.get_name(container) resp, resp_body = self.api.method_delete(uri)
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.
367,655
def _post(url:str, params:dict, headers:dict) -> dict: 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, "error": da...
Make a POST call.
367,656
def public_ip_addresses_list(resource_group, **kwargs): result = {} netconn = __utils__[](, **kwargs) try: pub_ips = __utils__[]( netconn.public_ip_addresses.list( resource_group_name=resource_group ) ) for ip in pub_ips: resu...
.. 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
367,657
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.
367,658
def build_response(self, response, path=None, parser=json_decode_wrapper, async=False): if async: response.process = lambda: self.build_response(response.result(), path=path, parser=parser, async=False) return response if response.status_code != 204: try: ...
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...
367,659
def main(connection_file): ctx = zmq.Context.instance() with open(connection_file) as f: cfg = json.loads(f.read()) location = cfg[] reg_url = cfg[] session = Session(key=str_to_bytes(cfg[])) query = ctx.socket(zmq.DEALER) query.connect(disambiguate_url(cfg[]...
watch iopub channel, and print messages
367,660
def _do_scale(image, 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), lambda: tf.cast([size, shape[1] / shape[0] * size], tf.int32)) ret...
Rescale the image by scaling the smaller spatial dimension to `size`.
367,661
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): def default_func(cr, pool, id, vals): quantity = {}.fromkeys(set(vals), 0) ...
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; :...
367,662
def install(self, ref, table_name=None, index_columns=None,logger=None): try: obj_number = ObjectNumber.parse(ref) if isinstance(obj_number, TableNumber): table = self._library.table(ref) connection = self._backend._get_connection() ...
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.
367,663
def run(self): model = self.model configfile = self.configfile interval = self.interval sockets = self.sockets model.initialize(configfile) if model.state == : logger.info( "model initialized and started in pause mode, waiting for re...
run the model
367,664
def com_google_fonts_check_family_single_directory(fonts): directories = [] for target_file in fonts: directory = os.path.dirname(target_file) if directory not in directories: directories.append(directory) if len(directories) == 1: yield PASS, "All files are in the same directory." else: ...
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...
367,665
def makeLinearcFunc(self,mNrm,cNrm): cFuncUnc = LinearInterp(mNrm,cNrm,self.MPCminNow_j*self.hNrmNow_j,self.MPCminNow_j) return cFuncUnc
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...
367,666
def _inflate(cls, data): for k, v in data[Constants.CONFIG_KEY].items(): setattr(cls, k, v) return cls._deflate()
Update config by deserialising input dictionary
367,667
def police_priority_map_name(self, **kwargs): 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.text = kwargs.pop() callba...
Auto Generated Code
367,668
def process_text(text, out_format=, save_json=, webservice=None): if not webservice: if eidos_reader is None: logger.error() return None json_dict = eidos_reader.process_text(text, out_format) else: res = requests.post( % webservice, ...
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_...
367,669
def parent_for_matching_rest_name(self, rest_names): 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
367,670
def crypto_secretstream_xchacha20poly1305_init_push(state, key): ensure( isinstance(state, crypto_secretstream_xchacha20poly1305_state), , raising=exc.TypeError, ) ensure( isinstance(key, bytes), , raising=exc.TypeError, ) ensure( len(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_secretstream_xchacha20poly1305_KEYBYTES` long :type key: bytes :return: header ...
367,671
def mequ(m1): m1 = stypes.toDoubleMatrix(m1) mout = stypes.emptyDoubleMatrix() libspice.mequ_c(m1, mout) return stypes.cMatrixToNumpy(mout)
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
367,672
def _fill(self): types_to_exclude = [, , , , , , ] values = self.namespace.who_ls() def eval(expr): return self.namespace.shell.ev(expr) var = [(v, type(eval(v)).__name__, str(_getsizeof(eval(v))), ...
Fill self with variable information.
367,673
def index(): ctx = mycommunities_ctx() p = request.args.get(, type=str) so = request.args.get(, type=str) page = request.args.get(, type=int, default=1) so = so or current_app.config.get() communities = Community.filter_communities(p, so) featured_community = FeaturedCommunity.get_fe...
Index page with uploader and list of existing depositions.
367,674
def partition(self, id_): from ..orm import Partition as OrmPartition from sqlalchemy import or_ from ..identity import PartialPartitionName if isinstance(id_, PartitionIdentity): id_ = id_.id_ elif isinstance(id_, PartialPartitionName): id_ = 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 Because this method works on the bund...
367,675
def inverseHistogram(hist, bin_range): data = hist.astype(float) / np.min(hist[np.nonzero(hist)]) new_data = np.empty(shape=np.sum(data, dtype=int)) i = 0 xvals = np.linspace(bin_range[0], bin_range[1], len(data)) for d, x in zip(data, xvals): new_data[i:i + d] = x i += int(d) ...
sample data from given histogram and min, max values within range Returns: np.array: data that would create the same histogram as given
367,676
def serialize_dict_keys(d, prefix=""): keys = [] for k, v in d.items(): fqk = .format(prefix, k) keys.append(fqk) if isinstance(v, dict): keys.extend(serialize_dict_keys(v, prefix="{}.".format(fqk))) return keys
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']
367,677
def _execute_query(self): pipe = self.pipe if not self.card: if self.meta.ordering: self.ismember = getattr(self.backend.client, ) self.card = getattr(pipe, ) self._check_member = self.zism else: se...
Execute the query without fetching data. Returns the number of elements in the query.
367,678
def get_records_with_attachments(attachment_table, rel_object_field="REL_OBJECTID"): if arcpyFound == False: raise Exception("ArcPy is required to use this function") OIDs = [] with arcpy.da.SearchCursor(attachment_table, [rel_object_field]) as rows: for r...
returns a list of ObjectIDs for rows in the attachment table
367,679
def Kdiag(self, X): ret = np.empty(X.shape[0]) ret[:] = self.variance return ret
Compute the diagonal of the covariance matrix associated to X.
367,680
def unpack(self, buff, offset=0): header = UBInt16() header.unpack(buff[offset:offset+2]) self.tlv_type = header.value >> 9 length = header.value & 511 begin, end = offset + 2, offset + 2 + length self._value = BinaryData(buff[begin:end])
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...
367,681
def should_be_hidden_as_cause(exc): from valid8.validation_lib.types import HasWrongType, IsWrongType return isinstance(exc, (HasWrongType, IsWrongType))
Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error
367,682
def setValue( self, value ): scene = self.scene() point = scene.mapFromChart(value, None) self.setPos(point.x(), self.pos().y()) self.rebuild(scene.gridRect())
Moves the line to the given value and rebuilds it :param value | <variant>
367,683
def remove_port_callback(self, port, cb): logger.debug(, port, cb) for port_callback in self.cb: if port_callback.port == port and port_callback.callback == cb: self.cb.remove(port_callback)
Remove a callback for data that comes on a specific port
367,684
def verbose(self, msg, *args, **kw): 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()`.
367,685
def verify_checksum(message, previous_csum=0): if message.message_type in CHECKSUM_MSG_TYPES: csum = compute_checksum( message.checksum[0], message.args, previous_csum, ) if csum == message.checksum[1]: return True else: ...
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
367,686
def pack_pipeline(self, commands): return b.join( starmap(lambda *args: b.join(self._pack_command(args)), (a for a, _ in commands)))
Packs pipeline commands into bytes.
367,687
def _get_min_distance_to_volcanic_front(lons, lats): vf = _construct_surface(VOLCANIC_FRONT_LONS, VOLCANIC_FRONT_LATS, 0., 10.) sites = Mesh(lons, lats, None) return vf.get_rx_distance(sites)
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...
367,688
def wishart_pairwise_pvals(self, axis=0): return [slice_.wishart_pairwise_pvals(axis=axis) for slice_ in self.slices]
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...
367,689
def _digest_md5_authentication(self, login, password, authz_id=""): code, data, challenge = \ self.__send_command("AUTHENTICATE", [b"DIGEST-MD5"], withcontent=True, nblines=1) dmd5 = DigestMD5(challenge, "sieve/%s" % self.srvaddr) code, data,...
SASL DIGEST-MD5 authentication :param login: username :param password: clear password :return: True on success, False otherwise.
367,690
def combine(self, expert_out, multiply_by_gates=True): expert_part_sizes = tf.unstack( tf.stack([d.part_sizes for d in self._dispatchers]), num=self._ep.n, axis=1) expert_output_parts = self._ep(tf.split, expert_out, expert_part_sizes) expert_output_parts_t = transpose_list...
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...
367,691
def read_stats(self, *stats): from ixexplorer.ixe_stream import IxePacketGroupStream sleep_time = 0.1 if not stats: stats = [m.attrname for m in IxePgStats.__tcl_members__ if m.flags & FLAG_RDONLY] sleep_time = 1 for port in self.tx_ports_stre...
Read stream statistics from chassis. :param stats: list of requested statistics to read, if empty - read all statistics.
367,692
def write_file_lines(self, filename, contents): with open(filename, ) as f: self.log.debug(contents) f.writelines(contents)
Write a file. This is useful when writing a file that may not fit within memory. :param filename: ``str`` :param contents: ``list``
367,693
def create_from_binary(cls, mft_config, binary_data, entry_number): bin_view = memoryview(binary_data) entry = None if bin_view[0:4] != b"\x00\x00\x00\x00": try: header = MFTHeader.create_from_binary(mft_config.ignore_signature_check, ...
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...
367,694
def from_file(self, file_name=None): file_name = self._check_file_name(file_name) with open(file_name, ) as infile: top_level_dict = json.load(infile) pages_dict = top_level_dict[] pages = pd.DataFrame(pages_dict) self.pages = pages self.file_name ...
Loads a DataFrame with all the needed info about the experiment
367,695
def flatten_comments(comments, root_level=0): stack = comments[:] for item in stack: item.nested_level = root_level retval, parent_candidates = [], {} while stack: item = stack.pop(0) if isinstance(item, praw.objec...
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...
367,696
def process_notice(self, notice): id = notice["id"] _a, _b, _ = id.split(".") if id in self.subscription_objects: self.on_object(notice) elif ".".join([_a, _b, "x"]) in self.subscription_objects: self.on_object(notice) elif id[:4] == "2.6.": ...
This method is called on notices that need processing. Here, we call ``on_object`` and ``on_account`` slots.
367,697
def all_sample_md5s(self, type_tag=None): if type_tag: cursor = self.database[self.sample_collection].find({: type_tag}, {: 1, : 0}) else: cursor = self.database[self.sample_collection].find({}, {: 1, : 0}) return [match.values()[0] for match in cursor]
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.
367,698
def free(self): if self._coord_type == : self.ra.fix = False self.dec.fix = False else: self.l.fix = False self.b.fix = False
Free the parameters with the coordinates (either ra,dec or l,b depending on how the class has been instanced)
367,699
def transform(self, features): new_feature = np.zeros(features.shape[0], dtype=np.int) for row_i in range(features.shape[0]): feature_instance = tuple(features[row_i]) if feature_instance in self.feature_map: new_feature[row_i] = self.feature_map[feature...
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...