docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
checks the type (type name) of an unique named object (no fully qualified name) Args: root: start of search name: name of object class_name: the name of the type to be checked Returns: nothing (if not unique, raises an error)
def check_unique_named_object_has_class(root, name, class_name): assert class_name == get_unique_named_object(root, name).__class__.__name__
353,504
get a list of all models stored within a model (including the owning model). Args: model: the owning model Returns: a list of all models
def get_all_models_including_attached_models(model): if (hasattr(model, "_tx_model_repository")): models = list( model._tx_model_repository.all_models.filename_to_model.values()) if model not in models: models.append(model) else: models = [model] return m...
353,506
create a new repo for a model Args: all_models: models to be added to this new repository.
def __init__(self, all_models=None): self.local_models = ModelRepository() # used for current model if all_models: self.all_models = all_models # used to reuse already loaded models else: self.all_models = ModelRepository()
353,509
add a new model to all relevant objects Args: filename_pattern: models to be loaded model: model holding the loaded models in its _tx_model_repository field (may be None). glob_args: arguments passed to the glob.glob function. Returns: ...
def load_models_using_filepattern( self, filename_pattern, model, glob_args, is_main_model=False, encoding='utf-8', add_to_local_models=True): if (model): self.update_model_in_repo_based_on_filename(model) filenames = glob.glob(filename_pattern, **glob_args) ...
353,510
add a new model to all relevant objects Args: filename: models to be loaded model: model holding the loaded models in its _tx_model_repository field (may be None). search_path: list of search directories. Returns: the loaded model
def load_model_using_search_path( self, filename, model, search_path, is_main_model=False, encoding='utf8', add_to_local_models=True): if (model): self.update_model_in_repo_based_on_filename(model) for the_path in search_path: full_filename = join...
353,511
load a single model Args: the_metamodel: the metamodel used to load the model filename: the model to be loaded (if not cached) Returns: the loaded/cached model
def load_model( self, the_metamodel, filename, is_main_model, encoding='utf-8', add_to_local_models=True): if not self.local_models.has_model(filename): if self.all_models.has_model(filename): new_model = self.all_models.filename_to_model[filename] ...
353,512
Adds a model to the repo (not initially visible) Args: model: the model to be added. If the model has no filename, a name is invented Returns: the filename of the model added to the repo
def update_model_in_repo_based_on_filename(self, model): if model._tx_filename is None: for fn in self.all_models.filename_to_model: if self.all_models.filename_to_model[fn] == model: return fn i = 0 while self.all_models.has_model...
353,514
(internal: used to store a model after parsing into the repository) Args: other_model: the parsed model Returns: nothing
def pre_ref_resolution_callback(self, other_model): # print("PRE-CALLBACK{}".format(filename)) filename = other_model._tx_filename assert (filename) other_model._tx_model_repository = \ GlobalModelRepository(self.all_models) self.all_models.filename_to_model[...
353,515
Finds first object up the parent chain of the given type. If no parent of the given type exists None is returned. Args: typ(str or python class): The type of the model object we are looking for. obj (model object): Python model object which is the start of the search pro...
def get_parent_of_type(typ, obj): if type(typ) is not text: typ = typ.__name__ while hasattr(obj, 'parent'): obj = obj.parent if obj.__class__.__name__ == typ: return obj
353,546
Returns a list of all model elements of type 'typ' starting from model element 'root'. The search process will follow containment links only. Non-containing references shall not be followed. Args: decider(obj): a callable returning True if the object is of interest. root (model object): Pyt...
def get_children(decider, root): collected = [] def follow(elem): if elem in collected: return # Use meta-model to search for all contained child elements. cls = elem.__class__ if hasattr(cls, '_tx_attrs') and decider(elem): collected.append(elem)...
353,547
Returns a list of all model elements of type 'typ' starting from model element 'root'. The search process will follow containment links only. Non-containing references shall not be followed. Args: typ(str or python class): The type of the model object we are looking for. root (m...
def get_children_of_type(typ, root): if type(typ) is not text: typ = typ.__name__ return get_children(lambda x: x.__class__.__name__ == typ, root)
353,548
the default scope provider Args: obj: unused (used for multi_metamodel_support) attr: unused obj_ref: the cross reference to be resolved Returns: the resolved reference or None
def __call__(self, obj, attr, obj_ref): from textx.const import RULE_COMMON, RULE_ABSTRACT from textx.model import ObjCrossRef from textx.scoping.tools import get_parser if obj_ref is None: return None # an error! (see model.py: resolve_refs (TODO check) a...
353,557
find a fully qualified name. Use this callable as scope_provider in a meta-model: my_metamodel.register_scope_provider( {"*.*":textx.scoping.providers.FQN}) Args: current_obj: object corresponding a instance of an object (rule instance) ...
def __call__(self, current_obj, attr, obj_ref): def _find_obj_fqn(p, fqn_name, cls): def find_obj(parent, name): if parent is not current_obj and \ self.scope_redirection_logic is not None: from textx.scoping import ...
353,558
Constructs parser and initializes metamodel from language description given in textX language. Args: language_def (str): A language description in textX. metamodel (TextXMetaModel): A metamodel to initialize. Returns: Parser for the new language.
def language_from_str(language_def, metamodel): if type(language_def) is not text: raise TextXError("textX accepts only unicode strings.") if metamodel.debug: metamodel.dprint("*** PARSING LANGUAGE DEFINITION ***") # Check the cache for already conctructed textX parser if metamod...
353,578
Creates a new metamodel from the textX description given as a string. Args: lang_desc(str): A textX language description. metamodel(TextXMetaModel): A metamodel that should be used. other params: See TextXMetaModel.
def metamodel_from_str(lang_desc, metamodel=None, **kwargs): if not metamodel: metamodel = TextXMetaModel(**kwargs) language_from_str(lang_desc, metamodel) return metamodel
353,614
Creates new metamodel from the given file. Args: file_name(str): The name of the file with textX language description. other params: See metamodel_from_str.
def metamodel_from_file(file_name, **kwargs): with codecs.open(file_name, 'r', 'utf-8') as f: lang_desc = f.read() metamodel = metamodel_from_str(lang_desc=lang_desc, file_name=file_name, **kwargs) return metamodel
353,615
Starts a new import. Args: import_name(str): A relative import in the dot syntax (e.g. "first.second.expressions")
def _new_import(self, import_name): # Import can't be used if meta-model is loaded from string assert self.root_path is not None, \ '"import" statement can not be used if meta-model is ' \ 'loaded from string.' # Find the absolute file name of the import based ...
353,620
Initialize obj attributes. Args: obj(object): A python object to set attributes to. user(bool): If this object is a user object mangle attribute names.
def _init_obj_attrs(self, obj, user=False): for attr in obj.__class__._tx_attrs.values(): if user: # Mangle name to prvent name clashing attr_name = "_txa_%s" % attr.name else: attr_name = attr.name if attr.mult in [M...
353,624
Object processors are callables that will be called after each successful model object construction. Those callables receive model object as its parameter. Registration of new object processors will replace previous. Args: obj_processors(dict): A dictionary where key=class n...
def register_obj_processors(self, obj_processors): self.obj_processors = obj_processors self.type_convertors.update(obj_processors)
353,633
Initializes and runs the processor. Arguments: serializer: a DREST serializer data: the serializer's representation
def __init__(self, serializer, data): if isinstance(serializer, ListSerializer): serializer = serializer.child self.data = {} self.seen = defaultdict(set) self.plural_name = serializer.get_plural_name() self.name = serializer.get_name() # process th...
353,829
Return a field given a model and field name. Arguments: model: a Django model field_name: the name of a field Returns: A Django field if `field_name` is a valid field for `model`, None otherwise.
def get_model_field(model, field_name): meta = model._meta try: if DJANGO19: field = meta.get_field(field_name) else: field = meta.get_field_by_name(field_name)[0] return field except: if DJANGO19: related_objs = ( f fo...
353,840
Check whether a given model field is a remote field. A remote field is the inverse of a one-to-many or a many-to-many relationship. Arguments: model: a Django model field_name: the name of a field Returns: True if `field_name` is a remote field, False otherwise.
def is_field_remote(model, field_name): if not hasattr(model, '_meta'): # ephemeral model with no metaclass return False model_field = get_model_field(model, field_name) return isinstance(model_field, (ManyToManyField, RelatedObject))
353,842
Parses the request for a particular feature. Arguments: name: A feature name. Returns: A feature parsed from the URL if the feature is supported, or None.
def get_request_feature(self, name): if '[]' in name: # array-type return self.request.query_params.getlist( name) if name in self.features else None elif '{}' in name: # object-type (keys are not consistent) return self._extract_o...
353,905
Returns a queryset for this request. Arguments: queryset: Optional root-level queryset.
def get_queryset(self, queryset=None): serializer = self.get_serializer() return getattr(self, 'queryset', serializer.Meta.model.objects.all())
353,907
Modified to_representation with optimizations. 1) Returns a plain old dict as opposed to OrderedDict. (Constructing ordered dict is ~100x slower than `{}`.) 2) Ensure we use a cached list of fields (this optimization exists in DRF 3.2 but not 3.1) Arguments: ...
def _faster_to_representation(self, instance): ret = {} fields = self._readable_fields is_fast = isinstance(instance, prefetch.FastObject) id_fields = self._readable_id_fields for field in fields: attribute = None # we exclude dynamic fields h...
353,948
Modified to_representation method. Optionally may cache objects. Arguments: instance: A model instance or data object. Returns: Instance ID if the serializer is meant to represent its ID. Otherwise, a tagged data dict representation.
def to_representation(self, instance): if self.id_only(): return instance.pk pk = getattr(instance, 'pk', None) if not settings.ENABLE_SERIALIZER_OBJECT_CACHE or pk is None: return self._to_representation(instance) else: if pk not in self.obj...
353,950
Provides post processing. Sub-classes should implement their own to_representation method, but pass the resulting dict through this function to get tagging and field selection. Arguments: instance: Serialized dict, or object. If object, it will be serialized by the s...
def to_representation(self, instance): if not isinstance(instance, dict): data = super( DynamicEphemeralSerializer, self ).to_representation(instance) else: data = instance instance = EphemeralObject(data) ...
353,955
Register a viewset that should be considered the canonical endpoint for a particular resource. In addition to generating and registering the route, it adds the route in a reverse map to allow DREST to build the canonical URL for a given resource. Arguments: viewset - viewset...
def register_resource(self, viewset, namespace=None): # Try to extract resource name from viewset. try: serializer = viewset.serializer_class() resource_key = serializer.get_resource_key() resource_name = serializer.get_name() path_name = seriali...
353,961
Return canonical resource path. Arguments: resource_key - Canonical resource key i.e. Serializer.get_resource_key(). pk - (Optional) Object's primary key for a single-resource URL. Returns: Absolute URL as string.
def get_canonical_path(resource_key, pk=None): if resource_key not in resource_map: # Note: Maybe raise? return None base_path = get_script_prefix() + resource_map[resource_key]['path'] if pk: return '%s/%s/' % (base_path, pk) else: ...
353,962
Return canonical serializer for a given resource name. Arguments: resource_key - Resource key, usually DB table for model-based resources, otherwise the plural name. model - (Optional) Model class to look up by. instance - (Optional) Model object i...
def get_canonical_serializer( resource_key, model=None, instance=None, resource_name=None ): if model: resource_key = get_model_table(model) elif instance: resource_key = instance._meta.db_table elif resource_name: ...
353,963
Get the key that can be passed to Django's filter method. To account for serialier field name rewrites, this method translates serializer field names to model field names by inspecting `serializer`. For example, a query like `filter{users.events}` would be returned as `users__e...
def generate_query_key(self, serializer): rewritten = [] last = len(self.field) - 1 s = serializer field = None for i, field_name in enumerate(self.field): # Note: .fields can be empty for related serializers that aren't # sideloaded. Fields that ...
353,973
Stringifies input dict as toml Args: o: Object to dump into toml preserve: Boolean parameter. If true, preserve inline tables. Returns: String containing the toml corresponding to dict
def dumps(o, encoder=None): retval = "" if encoder is None: encoder = TomlEncoder(o.__class__) addtoretval, sections = encoder.dump_sections(o, "") retval += addtoretval outer_objs = [id(o)] while sections: section_ids = [id(section) for section in sections] for out...
353,992
This function returns the sum of the squared error Parameters: two arrays constrained to 0..1 Returns: sum of the squared error between the histograms
def histogram_distance(arr1, arr2, bins=None): eps = 1e-6 assert arr1.min() > 0 - eps assert arr1.max() < 1 + eps assert arr2.min() > 0 - eps assert arr2.max() < 1 + eps if not bins: bins = [x / 10 for x in range(11)] hist1 = np.histogram(arr1, bins=bins)[0] / arr1.size his...
354,040
Validates that the 'iss' claim is valid. The "iss" (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The "iss" value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL. Args: ...
def _validate_iss(claims, issuer=None): if issuer is not None: if isinstance(issuer, string_types): issuer = (issuer,) if claims.get('iss') not in issuer: raise JWTClaimsError('Invalid issuer')
354,611
Helper method to base64url_decode a string. Args: input (str): A base64url_encoded string to decode.
def base64url_decode(input): rem = len(input) % 4 if rem > 0: input += b'=' * (4 - rem) return base64.urlsafe_b64decode(input)
354,627
Helper for comparing string in constant time, independent of the python version being used. Args: a (str): A string to compare b (str): A string to compare
def constant_time_string_compare(a, b): try: return hmac.compare_digest(a, b) except AttributeError: if len(a) != len(b): return False result = 0 for x, y in zip(a, b): result |= ord(x) ^ ord(y) return result == 0
354,628
Generates the subset of 'characters' that can be encoded by 'encodings'. Args: characters: The characters to check for encodeability e.g. 'abcd'. encodings: The encodings to check against e.g. ['cp1252', 'iso-8859-5']. Returns: The subset of 'characters' that can be encoded using one o...
def generate_encodeable_characters(characters: Iterable[str], encodings: Iterable[str]) -> Iterable[str]: for c in characters: for encoding in encodings: try: c.encode(encoding) yield c except UnicodeEncodeError:...
354,836
Return a mapping between each given character and its length. Args: measurer: The TextMeasurer used to measure the width of the text in pixels. characters: The characters to measure e.g. "ml". Returns: A mapping from the given characters to their length in pixels, as ...
def calculate_character_to_length_mapping( measurer: text_measurer.TextMeasurer, characters: Iterable[str]) -> Mapping[str, float]: char_to_length = {} for c in characters: char_to_length[c] = measurer.text_width(c) return char_to_length
354,837
A container for a SAX SVG light tree objects document. This class provides functions for extracting SVG data into Path objects. Args: filename (str): The filename of the SVG file
def __init__(self, filename): self.root_values = {} self.tree = [] # remember location of original svg file if filename is not None and os.path.dirname(filename) == '': self.original_filename = os.path.join(os.getcwd(), filename) else: self.origin...
356,279
Returns the apriori candidates as a list. Arguments: prev_candidates -- Previous candidates as a list. length -- The lengths of the next candidates.
def create_next_candidates(prev_candidates, length): # Solve the items. item_set = set() for candidate in prev_candidates: for item in candidate: item_set.add(item) items = sorted(item_set) # Create the temporary candidates. These will be filtered below. tmp_next_candid...
356,535
Returns a generator of support records with given transactions. Arguments: transaction_manager -- Transactions as a TransactionManager instance. min_support -- A minimum support (float). Keyword arguments: max_length -- The maximum length of relations (integer).
def gen_support_records(transaction_manager, min_support, **kwargs): # Parse arguments. max_length = kwargs.get('max_length') # For testing. _create_next_candidates = kwargs.get( '_create_next_candidates', create_next_candidates) # Process. candidates = transaction_manager.initial...
356,536
Returns a generator of ordered statistics as OrderedStatistic instances. Arguments: transaction_manager -- Transactions as a TransactionManager instance. record -- A support record as a SupportRecord instance.
def gen_ordered_statistics(transaction_manager, record): items = record.items for combination_set in combinations(sorted(items), len(items) - 1): items_base = frozenset(combination_set) items_add = frozenset(items.difference(items_base)) confidence = ( record.support / t...
356,537
Filter OrderedStatistic objects. Arguments: ordered_statistics -- A OrderedStatistic iterable object. Keyword arguments: min_confidence -- The minimum confidence of relations (float). min_lift -- The minimum lift of relations (float).
def filter_ordered_statistics(ordered_statistics, **kwargs): min_confidence = kwargs.get('min_confidence', 0.0) min_lift = kwargs.get('min_lift', 0.0) for ordered_statistic in ordered_statistics: if ordered_statistic.confidence < min_confidence: continue if ordered_statisti...
356,538
Executes Apriori algorithm and returns a RelationRecord generator. Arguments: transactions -- A transaction iterable object (eg. [['A', 'B'], ['B', 'C']]). Keyword arguments: min_support -- The minimum support of relations (float). min_confidence -- The minimum ...
def apriori(transactions, **kwargs): # Parse the arguments. min_support = kwargs.get('min_support', 0.1) min_confidence = kwargs.get('min_confidence', 0.0) min_lift = kwargs.get('min_lift', 0.0) max_length = kwargs.get('max_length', None) # Check arguments. if min_support <= 0: ...
356,539
Parse commandline arguments. Arguments: argv -- An argument list without the program name.
def parse_args(argv): output_funcs = { 'json': dump_as_json, 'tsv': dump_as_two_item_tsv, } default_output_func_key = 'json' parser = argparse.ArgumentParser() parser.add_argument( '-v', '--version', action='version', version='%(prog)s {0}'.format(__version__)) ...
356,540
Load transactions and returns a generator for transactions. Arguments: input_file -- An input file. Keyword arguments: delimiter -- The delimiter of the transaction.
def load_transactions(input_file, **kwargs): delimiter = kwargs.get('delimiter', '\t') for transaction in csv.reader(input_file, delimiter=delimiter): yield transaction if transaction else ['']
356,541
Dump an relation record as a json value. Arguments: record -- A RelationRecord instance to dump. output_file -- A file to output.
def dump_as_json(record, output_file): def default_func(value): if isinstance(value, frozenset): return sorted(value) raise TypeError(repr(value) + " is not JSON serializable") converted_record = record._replace( ordered_statistics=[x._asdict() for x in record....
356,542
Dump a relation record as TSV only for 2 item relations. Arguments: record -- A RelationRecord instance to dump. output_file -- A file to output.
def dump_as_two_item_tsv(record, output_file): for ordered_stats in record.ordered_statistics: if len(ordered_stats.items_base) != 1: continue if len(ordered_stats.items_add) != 1: continue output_file.write('{0}\t{1}\t{2:.8f}\t{3:.8f}\t{4:.8f}{5}'.format( ...
356,543
Initialize. Arguments: transactions -- A transaction iterable object (eg. [['A', 'B'], ['B', 'C']]).
def __init__(self, transactions): self.__num_transaction = 0 self.__items = [] self.__transaction_index_map = {} for transaction in transactions: self.add_transaction(transaction)
356,545
Add a transaction. Arguments: transaction -- A transaction as an iterable object (eg. ['A', 'B']).
def add_transaction(self, transaction): for item in transaction: if item not in self.__transaction_index_map: self.__items.append(item) self.__transaction_index_map[item] = set() self.__transaction_index_map[item].add(self.__num_transaction) ...
356,546
Returns a support for items. Arguments: items -- Items as an iterable object (eg. ['A', 'B']).
def calc_support(self, items): # Empty items is supported by all transactions. if not items: return 1.0 # Empty transactions supports no items. if not self.num_transaction: return 0.0 # Create the transaction index intersection. sum_inde...
356,547
Convert PIL image to numpy grayscale array and numpy alpha array. Args: img (PIL.Image): PIL Image object. Returns: (gray, alpha): both numpy arrays.
def to_grayscale(img): gray = numpy.asarray(ImageOps.grayscale(img)).astype(numpy.float) imbands = img.getbands() alpha = None if 'A' in imbands: alpha = numpy.asarray(img.split()[-1]).astype(numpy.float) return gray, alpha
356,830
Create an SSIMImage. Args: img (str or PIL.Image): PIL Image object or file name. gaussian_kernel_1d (np.ndarray, optional): Gaussian kernel that was generated with utils.get_gaussian_kernel is used to precompute common objects for SSIM computation size (tuple,...
def __init__(self, img, gaussian_kernel_1d=None, size=None): # Use existing or create a new PIL.Image self.img = img if not isinstance(img, compat.basestring) \ else compat.Image.open(img) # Resize image if size is defined and different # from original image ...
356,832
Compute the SSIM value from the reference image to the target image. Args: target (str or PIL.Image): Input image to compare the reference image to. This may be a PIL Image object or, to save time, an SSIMImage object (e.g. the img member of another SSIM object). Returns:...
def ssim_value(self, target): # Performance boost if handed a compatible SSIMImage object. if not isinstance(target, SSIMImage) \ or not np.array_equal(self.gaussian_kernel_1d, target.gaussian_kernel_1d): target = SSIMImage(target, self.gaus...
356,834
Compute the complex wavelet SSIM (CW-SSIM) value from the reference image to the target image. Args: target (str or PIL.Image): Input image to compare the reference image to. This may be a PIL Image object or, to save time, an SSIMImage object (e.g. the img member of anoth...
def cw_ssim_value(self, target, width=30): if not isinstance(target, SSIMImage): target = SSIMImage(target, size=self.img.size) # Define a width for the wavelet convolution widths = np.arange(1, width+1) # Use the image data as arrays sig1 = np.asarray(self...
356,835
Computes SSIM. Args: im1: First PIL Image object to compare. im2: Second PIL Image object to compare. Returns: SSIM float value.
def compute_ssim(image1, image2, gaussian_kernel_sigma=1.5, gaussian_kernel_width=11): gaussian_kernel_1d = get_gaussian_kernel( gaussian_kernel_width, gaussian_kernel_sigma) return SSIM(image1, gaussian_kernel_1d).ssim_value(image2)
356,836
Sort blocks by Logical Erase Block number. Arguments: List:blocks -- List of block objects to sort. Returns: List -- Indexes of blocks sorted by LEB.
def by_leb(blocks): slist_len = len(blocks) slist = ['x'] * slist_len for block in blocks: if blocks[block].leb_num >= slist_len: add_elements = blocks[block].leb_num - slist_len + 1 slist += (['x'] * add_elements) slist_len = len(slist) slist[bloc...
360,057
Sort blocks by volume id Arguments: Obj:blocks -- List of block objects. List:slist -- (optional) List of block indexes. Return: Dict -- blocks grouped in lists with dict key as volume id.
def by_vol_id(blocks, slist=None): vol_blocks = {} # sort block by volume # not reliable with multiple partitions (fifo) for i in blocks: if slist and i not in slist: continue elif not blocks[i].is_valid: continue if blocks[i].vid_hdr.vol_id not i...
360,058
Extract UBIFS contents to_path/ Arguments: Obj:ubifs -- UBIFS object. Str:out_path -- Path to extract contents to.
def extract_files(ubifs, out_path, perms=False): try: inodes = {} bad_blocks = [] walk.index(ubifs, ubifs.master_node.root_lnum, ubifs.master_node.root_offs, inodes, bad_blocks) if len(inodes) < 2: raise Exception('No inodes found') for dent in inodes[1]['...
360,060
Filter out old layout blocks from list Arguments: List:blocks -- List of block objects List:layout_blocks -- List of layout block indexes Returns: List -- Newest layout blocks in list
def get_newest(blocks, layout_blocks): layout_temp = list(layout_blocks) for i in range(0, len(layout_temp)): for k in range(0, len(layout_blocks)): if blocks[layout_temp[i]].ec_hdr.image_seq != blocks[layout_blocks[k]].ec_hdr.image_seq: continue if blocks[...
360,077
Sort a list of layout blocks into pairs Arguments: List:blocks -- List of block objects List:layout_blocks -- List of layout block indexes Returns: List -- Layout block pair indexes grouped in a list
def group_pairs(blocks, layout_blocks_list): image_dict={} for block_id in layout_blocks_list: image_seq=blocks[block_id].ec_hdr.image_seq if image_seq not in image_dict: image_dict[image_seq]=[block_id] else: image_dict[image_seq].append(block_id) log(...
360,078
Group block indexes with appropriate layout pairs Arguments: List:blocks -- List of block objects List:layout_pairs -- List of grouped layout blocks Int:start_peb_num -- Number of the PEB to start from. Returns: List -- Layout block pairs grouped with associated block ranges.
def associate_blocks(blocks, layout_pairs, start_peb_num): seq_blocks = [] for layout_pair in layout_pairs: seq_blocks = sort.by_image_seq(blocks, blocks[layout_pair[0]].ec_hdr.image_seq) layout_pair.append(seq_blocks) return layout_pairs
360,079
Get a list of UBI volume objects from list of blocks Arguments: List:blocks -- List of layout block objects List:layout_info -- Layout info (indexes of layout blocks and associated data blocks.) Returns: Dict -- Of Volume objects by volume name...
def get_volumes(blocks, layout_info): volumes = {} vol_blocks_lists = sort.by_vol_id(blocks, layout_info[2]) for vol_rec in blocks[layout_info[0]].vtbl_recs: vol_name = vol_rec.name.strip(b'\x00').decode('utf-8') if vol_rec.rec_index not in vol_blocks_lists: vol_blocks_lis...
360,088
Parse node key Arguments: Str:key -- Hex string literal of node key. Returns: Int:key_type -- Type of key, data, ino, dent, etc. Int:ino_num -- Inode number. Int:khash -- Key hash.
def parse_key(key): hkey, lkey = struct.unpack('<II',key[0:UBIFS_SK_LEN]) ino_num = hkey & UBIFS_S_KEY_HASH_MASK key_type = lkey >> UBIFS_S_KEY_BLOCK_BITS khash = lkey #if key_type < UBIFS_KEY_TYPES_CNT: return {'type':key_type, 'ino_num':ino_num, 'khash': khash}
360,091
Decompress data. Arguments: Int:ctype -- Compression type LZO, ZLIB (*currently unused*). Int:unc_len -- Uncompressed data lenth. Str:data -- Data to be uncompessed. Returns: Uncompressed Data.
def decompress(ctype, unc_len, data): if ctype == UBIFS_COMPR_LZO: try: return lzo.decompress(b''.join((b'\xf0', struct.pack('>I', unc_len), data))) except Exception as e: error(decompress, 'Warn', 'LZO Error: %s' % e) elif ctype == UBIFS_COMPR_ZLIB: try: ...
360,092
Get LEB size from superblock Arguments: Str:path -- Path to file. Returns: Int -- LEB size. Searches file for superblock and retrieves leb size.
def guess_leb_size(path): f = open(path, 'rb') f.seek(0,2) file_size = f.tell()+1 f.seek(0) block_size = None for _ in range(0, file_size, FILE_CHUNK_SZ): buf = f.read(FILE_CHUNK_SZ) for m in re.finditer(UBIFS_NODE_MAGIC, buf): start = m.start() ch...
360,104
Determine the most likely block size Arguments: Str:path -- Path to file. Returns: Int -- PEB size. Searches file for Magic Number, picks most common length between them.
def guess_peb_size(path): file_offset = 0 offsets = [] f = open(path, 'rb') f.seek(0,2) file_size = f.tell()+1 f.seek(0) for _ in range(0, file_size, FILE_CHUNK_SZ): buf = f.read(FILE_CHUNK_SZ) for m in re.finditer(UBI_EC_HDR_MAGIC, buf): start = m.start() ...
360,105
Parse the image upload response to obtain status. Args: res: http_utils.FetchResponse instance, the upload response Returns: dict, sessionStatus of the response Raises: hangups.NetworkError: If the upload request failed.
def _get_upload_session_status(res): response = json.loads(res.body.decode()) if 'sessionStatus' not in response: try: info = ( response['errorMessage']['additionalInfo'] ['uploader_service.GoogleRupioAdditionalInfo'] ...
360,378
Send a Protocol Buffer formatted chat API request. Args: endpoint (str): The chat API endpoint to use. request_pb: The request body as a Protocol Buffer message. response_pb: The response body as a Protocol Buffer message. Raises: NetworkError: If the re...
async def _pb_request(self, endpoint, request_pb, response_pb): logger.debug('Sending Protocol Buffer request %s:\n%s', endpoint, request_pb) res = await self._base_request( 'https://clients6.google.com/chat/v1/{}'.format(endpoint), 'application/x-pr...
360,381
Build :class:`.UserList` and :class:`.ConversationList`. This method requests data necessary to build the list of conversations and users. Users that are not in the contact list but are participating in a conversation will also be retrieved. Args: client (Client): Connected client. Return...
async def build_user_conversation_list(client): conv_states, sync_timestamp = await _sync_all_conversations(client) # Retrieve entities participating in all conversations. required_user_ids = set() for conv_state in conv_states: required_user_ids |= { user.UserID(chat_id=part.i...
360,433
Sync all conversations by making paginated requests. Conversations are ordered by ascending sort timestamp. Args: client (Client): Connected client. Raises: NetworkError: If the requests fail. Returns: tuple of list of ``ConversationState`` messages and sync timestamp
async def _sync_all_conversations(client): conv_states = [] sync_timestamp = None request = hangouts_pb2.SyncRecentConversationsRequest( request_header=client.get_request_header(), max_conversations=CONVERSATIONS_PER_REQUEST, max_events_per_conversation=1, sync_filter=[ ...
360,434
:class:`.Event` fired when an event occurs in this conversation. Args: conv_event: :class:`.ConversationEvent` that occurred.
def __init__(self, client, user_list, conversation, events=[], event_cont_token=None): # pylint: disable=dangerous-default-value self._client = client # Client self._user_list = user_list # UserList self._conversation = conversation # hangouts_pb2.Conversation ...
360,435
Update the internal state of the conversation. This method is used by :class:`.ConversationList` to maintain this instance. Args: conversation: ``Conversation`` message.
def update_conversation(self, conversation): # StateUpdate.conversation is actually a delta; fields that aren't # specified are assumed to be unchanged. Until this class is # refactored, hide this by saving and restoring previous values where # necessary. new_state = co...
360,442
Add an event to the conversation. This method is used by :class:`.ConversationList` to maintain this instance. Args: event_: ``Event`` message. Returns: :class:`.ConversationEvent` representing the event.
def add_event(self, event_): conv_event = self._wrap_event(event_) if conv_event.id_ not in self._events_dict: self._events.append(conv_event) self._events_dict[conv_event.id_] = conv_event else: # If this happens, there's probably a bug. ...
360,444
Rename this conversation. Hangouts only officially supports renaming group conversations, so custom names for one-to-one conversations may or may not appear in all first party clients. Args: name (str): New name. Raises: .NetworkError: If conversation c...
async def rename(self, name): await self._client.rename_conversation( hangouts_pb2.RenameConversationRequest( request_header=self._client.get_request_header(), new_name=name, event_request_header=self._get_event_request_header(), )...
360,449
Set the notification level of this conversation. Args: level: ``NOTIFICATION_LEVEL_QUIET`` to disable notifications, or ``NOTIFICATION_LEVEL_RING`` to enable them. Raises: .NetworkError: If the request fails.
async def set_notification_level(self, level): await self._client.set_conversation_notification_level( hangouts_pb2.SetConversationNotificationLevelRequest( request_header=self._client.get_request_header(), conversation_id=hangouts_pb2.ConversationId(id=self....
360,450
Set your typing status in this conversation. Args: typing: (optional) ``TYPING_TYPE_STARTED``, ``TYPING_TYPE_PAUSED``, or ``TYPING_TYPE_STOPPED`` to start, pause, or stop typing, respectively. Defaults to ``TYPING_TYPE_STARTED``. Raises: .Network...
async def set_typing(self, typing=hangouts_pb2.TYPING_TYPE_STARTED): # TODO: Add rate-limiting to avoid unnecessary requests. try: await self._client.set_typing( hangouts_pb2.SetTypingRequest( request_header=self._client.get_request_header(), ...
360,451
Update the timestamp of the latest event which has been read. This method will avoid making an API request if it will have no effect. Args: read_timestamp (datetime.datetime): (optional) Timestamp to set. Defaults to the timestamp of the newest event. Raises: ...
async def update_read_timestamp(self, read_timestamp=None): if read_timestamp is None: read_timestamp = (self.events[-1].timestamp if self.events else datetime.datetime.now(datetime.timezone.utc)) if read_timestamp > self.latest_read_timestamp: ...
360,452
Get the event following another event in this conversation. Args: event_id (str): ID of the event. prev (bool): If ``True``, return the previous event rather than the next event. Defaults to ``False``. Raises: KeyError: If no such :class:`.Conversati...
def next_event(self, event_id, prev=False): i = self.events.index(self._events_dict[event_id]) if prev and i > 0: return self.events[i - 1] elif not prev and i + 1 < len(self.events): return self.events[i + 1] else: return None
360,454
:class:`.Event` fired when an event occurs in any conversation. Args: conv_event: :class:`ConversationEvent` that occurred.
def __init__(self, client, conv_states, user_list, sync_timestamp): self._client = client # Client self._conv_dict = {} # {conv_id: Conversation} self._sync_timestamp = sync_timestamp # datetime self._user_list = user_list # UserList # Initialize the list of conversations fr...
360,455
Get all the conversations. Args: include_archived (bool): (optional) Whether to include archived conversations. Defaults to ``False``. Returns: List of all :class:`.Conversation` objects.
def get_all(self, include_archived=False): return [conv for conv in self._conv_dict.values() if not conv.is_archived or include_archived]
360,456
Leave a conversation. Args: conv_id (str): ID of conversation to leave.
async def leave_conversation(self, conv_id): logger.info('Leaving conversation: {}'.format(conv_id)) await self._conv_dict[conv_id].leave() del self._conv_dict[conv_id]
360,457
Receive a StateUpdate and fan out to Conversations. Args: state_update: hangouts_pb2.StateUpdate instance
async def _on_state_update(self, state_update): # The state update will include some type of notification: notification_type = state_update.WhichOneof('state_update') # If conversation fields have been updated, the state update will have # a conversation containing changed fiel...
360,459
Get a cached conversation or fetch a missing conversation. Args: conv_id: string, conversation identifier Raises: NetworkError: If the request to fetch the conversation fails. Returns: :class:`.Conversation` with matching ID.
async def _get_or_fetch_conversation(self, conv_id): conv = self._conv_dict.get(conv_id, None) if conv is None: logger.info('Fetching unknown conversation %s', conv_id) res = await self._client.get_conversation( hangouts_pb2.GetConversationRequest( ...
360,460
Receive a hangouts_pb2.Event and fan out to Conversations. Args: event_: hangouts_pb2.Event instance
async def _on_event(self, event_): conv_id = event_.conversation_id.id try: conv = await self._get_or_fetch_conversation(conv_id) except exceptions.NetworkError: logger.warning( 'Failed to fetch conversation for event notification: %s', ...
360,461
Receive Conversation delta and create or update the conversation. Args: conversation: hangouts_pb2.Conversation instance Raises: NetworkError: A request to fetch the complete conversation failed.
async def _handle_conversation_delta(self, conversation): conv_id = conversation.conversation_id.id conv = self._conv_dict.get(conv_id, None) if conv is None: # Ignore the delta and fetch the complete conversation. await self._get_or_fetch_conversation(conv_id) ...
360,462
Receive SetTypingNotification and update the conversation. Args: set_typing_notification: hangouts_pb2.SetTypingNotification instance
async def _handle_set_typing_notification(self, set_typing_notification): conv_id = set_typing_notification.conversation_id.id res = parsers.parse_typing_status_message(set_typing_notification) await self.on_typing.fire(res) try: conv = await self._get_or_fetch_conve...
360,463
Receive WatermarkNotification and update the conversation. Args: watermark_notification: hangouts_pb2.WatermarkNotification instance
async def _handle_watermark_notification(self, watermark_notification): conv_id = watermark_notification.conversation_id.id res = parsers.parse_watermark_notification(watermark_notification) await self.on_watermark_notification.fire(res) try: conv = await self._get_o...
360,464
Upgrade name type of this user. Google Voice participants often first appear with no name at all, and then get upgraded unpredictably to numbers ("+12125551212") or names. Args: user_ (~hangups.user.User): User to upgrade with.
def upgrade_name(self, user_): if user_.name_type > self.name_type: self.full_name = user_.full_name self.first_name = user_.first_name self.name_type = user_.name_type logger.debug('Added %s name to User "%s": %s', self.name_type...
360,467
Construct user from ``Entity`` message. Args: entity: ``Entity`` message. self_user_id (~hangups.user.UserID or None): The ID of the current user. If ``None``, assume ``entity`` is the current user. Returns: :class:`~hangups.user.User` object.
def from_entity(entity, self_user_id): user_id = UserID(chat_id=entity.id.chat_id, gaia_id=entity.id.gaia_id) return User(user_id, entity.properties.display_name, entity.properties.first_name, entity.properties.photo_url, ...
360,468
Construct user from ``ConversationParticipantData`` message. Args: conv_part_id: ``ConversationParticipantData`` message. self_user_id (~hangups.user.UserID or None): The ID of the current user. If ``None``, assume ``conv_part_id`` is the current user. Returns: ...
def from_conv_part_data(conv_part_data, self_user_id): user_id = UserID(chat_id=conv_part_data.id.chat_id, gaia_id=conv_part_data.id.gaia_id) return User(user_id, conv_part_data.fallback_name, None, None, [], (self_user_id == user_id) or (self_user_i...
360,469
Get a user by its ID. Args: user_id (~hangups.user.UserID): The ID of the user. Raises: KeyError: If no such user is known. Returns: :class:`~hangups.user.User` with the given ID.
def get_user(self, user_id): try: return self._user_dict[user_id] except KeyError: logger.warning('UserList returning unknown User for UserID %s', user_id) return User(user_id, None, None, None, [], False)
360,471
Add an observer to this event. Args: callback: A function or coroutine callback to call when the event is fired. Raises: ValueError: If the callback has already been added.
def add_observer(self, callback): if callback in self._observers: raise ValueError('{} is already an observer of {}' .format(callback, self)) self._observers.append(callback)
360,473
Remove an observer from this event. Args: callback: A function or coroutine callback to remove from this event. Raises: ValueError: If the callback is not an observer of this event.
def remove_observer(self, callback): if callback not in self._observers: raise ValueError('{} is not an observer of {}' .format(callback, self)) self._observers.remove(callback)
360,474
Run a hangups example coroutine. Args: example_coroutine (coroutine): Coroutine to run with a connected hangups client and arguments namespace as arguments. extra_args (str): Any extra command line arguments required by the example.
def run_example(example_coroutine, *extra_args): args = _get_parser(extra_args).parse_args() logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING) # Obtain hangups authentication cookies, prompting for credentials from # standard input if necessary. cookies = hangups.auth....
360,481
Print column headers and rows as a reStructuredText table. Args: col_tuple: Tuple of column name strings. row_tuples: List of tuples containing row data.
def print_table(col_tuple, row_tuples): col_widths = [max(len(str(row[col])) for row in [col_tuple] + row_tuples) for col in range(len(col_tuple))] format_str = ' '.join('{{:<{}}}'.format(col_width) for col_width in col_widths) header_border = ' '.join('=' * ...
360,484
Generate doc for an enum. Args: enum_descriptor: descriptor_pb2.EnumDescriptorProto instance for enum to generate docs for. locations: Dictionary of location paths tuples to descriptor_pb2.SourceCodeInfo.Location instances. path: Path tuple to the enum definition. ...
def generate_enum_doc(enum_descriptor, locations, path, name_prefix=''): print(make_subsection(name_prefix + enum_descriptor.name)) location = locations[path] if location.HasField('leading_comments'): print(textwrap.dedent(location.leading_comments)) row_tuples = [] for value_index, va...
360,485
Generate docs for message and nested messages and enums. Args: message_descriptor: descriptor_pb2.DescriptorProto instance for message to generate docs for. locations: Dictionary of location paths tuples to descriptor_pb2.SourceCodeInfo.Location instances. path: Path...
def generate_message_doc(message_descriptor, locations, path, name_prefix=''): # message_type is 4 prefixed_name = name_prefix + message_descriptor.name print(make_subsection(prefixed_name)) location = locations[path] if location.HasField('leading_comments'): print(textwrap.dedent(locat...
360,486
Compile proto file to descriptor set. Args: proto_file_path: Path to proto file to compile. Returns: Path to file containing compiled descriptor set. Raises: SystemExit if the compilation fails.
def compile_protofile(proto_file_path): out_file = tempfile.mkstemp()[1] try: subprocess.check_output(['protoc', '--include_source_info', '--descriptor_set_out', out_file, proto_file_path]) except subprocess.CalledProcessError as...
360,487
Simple wrapper for :func:`get_auth` that prompts the user using stdin. Args: refresh_token_filename (str): Path to file where refresh token will be cached. manual_login (bool): If true, prompt user to log in through a browser and enter authorization code manually. Defaults t...
def get_auth_stdin(refresh_token_filename, manual_login=False): refresh_token_cache = RefreshTokenCache(refresh_token_filename) return get_auth( CredentialsPrompt(), refresh_token_cache, manual_login=manual_login )
360,540