docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Build descriptor for Field instance. Args: field_definition: Field instance to provide descriptor for. Returns: Initialized FieldDescriptor instance describing the Field instance.
def describe_field(field_definition): field_descriptor = FieldDescriptor() field_descriptor.name = field_definition.name field_descriptor.number = field_definition.number field_descriptor.variant = field_definition.variant if isinstance(field_definition, messages.EnumField): field_desc...
388,309
Build descriptor for Message class. Args: message_definition: Message class to provide descriptor for. Returns: Initialized MessageDescriptor instance describing the Message class.
def describe_message(message_definition): message_descriptor = MessageDescriptor() message_descriptor.name = message_definition.definition_name().split( '.')[-1] fields = sorted(message_definition.all_fields(), key=lambda v: v.number) if fields: message_descript...
388,310
Build a file from a specified Python module. Args: module: Python module to describe. Returns: Initialized FileDescriptor instance describing the module.
def describe_file(module): descriptor = FileDescriptor() descriptor.package = util.get_package_for_module(module) if not descriptor.package: descriptor.package = None message_descriptors = [] enum_descriptors = [] # Need to iterate over all top level attributes of the module look...
388,311
Build a file set from a specified Python modules. Args: modules: Iterable of Python module to describe. Returns: Initialized FileSet instance describing the modules.
def describe_file_set(modules): descriptor = FileSet() file_descriptors = [] for module in modules: file_descriptors.append(describe_file(module)) if file_descriptors: descriptor.files = file_descriptors return descriptor
388,312
Describe any value as a descriptor. Helper function for describing any object with an appropriate descriptor object. Args: value: Value to describe as a descriptor. Returns: Descriptor message class if object is describable as a descriptor, else None.
def describe(value): if isinstance(value, types.ModuleType): return describe_file(value) elif isinstance(value, messages.Field): return describe_field(value) elif isinstance(value, messages.Enum): return describe_enum_value(value) elif isinstance(value, type): if iss...
388,313
Constructor. Args: descriptors: A dictionary or dictionary-like object that can be used to store and cache descriptors by definition name. definition_loader: A function used for resolving missing descriptors. The function takes a definition name as its parameter and ...
def __init__(self, descriptors=None, descriptor_loader=import_descriptor_loader): self.__descriptor_loader = descriptor_loader self.__descriptors = descriptors or {}
388,315
Lookup descriptor by name. Get descriptor from library by name. If descriptor is not found will attempt to find via descriptor loader if provided. Args: definition_name: Definition name to find. Returns: Descriptor that describes definition name. Raises: ...
def lookup_descriptor(self, definition_name): try: return self.__descriptors[definition_name] except KeyError: pass if self.__descriptor_loader: definition = self.__descriptor_loader(definition_name) self.__descriptors[definition_name] = ...
388,316
Determines the package name for any definition. Determine the package that any definition name belongs to. May check parent for package name and will resolve missing descriptors if provided descriptor loader. Args: definition_name: Definition name to find package for.
def lookup_package(self, definition_name): while True: descriptor = self.lookup_descriptor(definition_name) if isinstance(descriptor, FileDescriptor): return descriptor.package else: index = definition_name.rfind('.') i...
388,317
Constructor. Args: protojson_protocol: ProtoJson instance.
def __init__(self, protojson_protocol=None, **kwargs): super(MessageJSONEncoder, self).__init__(**kwargs) self.__protojson_protocol = ( protojson_protocol or ProtoJson.get_default())
388,319
Return dictionary instance from a message object. Args: value: Value to get dictionary for. If not encodable, will call superclasses default method.
def default(self, value): if isinstance(value, messages.Enum): return str(value) if six.PY3 and isinstance(value, bytes): return value.decode('utf8') if isinstance(value, messages.Message): result = {} for field in value.all_fields(): ...
388,320
Encode a python field value to a JSON value. Args: field: A ProtoRPC field instance. value: A python value supported by field. Returns: A JSON serializable value appropriate for field.
def encode_field(self, field, value): if isinstance(field, messages.BytesField): if field.repeated: value = [base64.b64encode(byte) for byte in value] else: value = base64.b64encode(value) elif isinstance(field, message_types.DateTimeField...
388,321
Encode Message instance to JSON string. Args: Message instance to encode in to JSON string. Returns: String encoding of Message instance in protocol JSON format. Raises: messages.ValidationError if message is not initialized.
def encode_message(self, message): message.check_initialized() return json.dumps(message, cls=MessageJSONEncoder, protojson_protocol=self)
388,322
Merge JSON structure to Message instance. Args: message_type: Message to decode data to. encoded_message: JSON encoded version of message. Returns: Decoded instance of message_type. Raises: ValueError: If encoded_message is not valid JSON. mes...
def decode_message(self, message_type, encoded_message): encoded_message = six.ensure_str(encoded_message) if not encoded_message.strip(): return message_type() dictionary = json.loads(encoded_message) message = self.__decode_dictionary(message_type, dictionary) ...
388,323
Find the messages.Variant type that describes this value. Args: value: The value whose variant type is being determined. Returns: The messages.Variant value that best describes value's type, or None if it's a type we don't know how to handle.
def __find_variant(self, value): if isinstance(value, bool): return messages.Variant.BOOL elif isinstance(value, six.integer_types): return messages.Variant.INT64 elif isinstance(value, float): return messages.Variant.DOUBLE elif isinstance(va...
388,324
Merge dictionary in to message. Args: message: Message to merge dictionary in to. dictionary: Dictionary to extract information from. Dictionary is as parsed from JSON. Nested objects will also be dictionaries.
def __decode_dictionary(self, message_type, dictionary): message = message_type() for key, value in six.iteritems(dictionary): if value is None: try: message.reset(key) except AttributeError: pass # This is an ...
388,325
Decode a JSON value to a python value. Args: field: A ProtoRPC field instance. value: A serialized JSON value. Return: A Python value compatible with field.
def decode_field(self, field, value): if isinstance(field, messages.EnumField): try: return field.type(value) except TypeError: raise messages.DecodeError( 'Invalid enum value "%s"' % (value or '')) elif isinstance(fie...
388,326
Initialize this download by setting self.http and self.url. We want the user to be able to override self.http by having set the value in the constructor; in that case, we ignore the provided http. Args: http: An httplib2.Http instance or None. url: The url for this ...
def _Initialize(self, http, url): self.EnsureUninitialized() if self.http is None: self.__http = http or http_wrapper.GetHttp() self.__url = url
388,338
Initialize this download by making a request. Args: http_request: The HttpRequest to use to initialize this download. http: The httplib2.Http instance for this request. client: If provided, let this client process the final URL before sending any additional requests....
def InitializeDownload(self, http_request, http=None, client=None): self.EnsureUninitialized() if http is None and client is None: raise exceptions.UserError('Must provide client or http.') http = http or client.http if client is not None: http_request.ur...
388,348
Send this resumable upload in a single request. Args: callback: Progress callback function with inputs (http_wrapper.Response, transfer.Upload) finish_callback: Final callback function with inputs (http_wrapper.Response, transfer.Upload) additional_head...
def StreamMedia(self, callback=None, finish_callback=None, additional_headers=None): return self.__StreamMedia( callback=callback, finish_callback=finish_callback, additional_headers=additional_headers, use_chunks=False)
388,374
Read at most size bytes from this buffer. Bytes read from this buffer are consumed and are permanently removed. Args: size: If provided, read no more than size bytes from the buffer. Otherwise, this reads the entire buffer. Returns: The bytes read from this buf...
def read(self, size=None): if size is None: size = self.__size ret_list = [] while size > 0 and self.__buf: data = self.__buf.popleft() size -= len(data) ret_list.append(data) if size < 0: ret_list[-1], remainder = ret_...
388,381
Get package name for a module. Helper calculates the package name of a module. Args: module: Module to get name for. If module is a string, try to find module in sys.modules. Returns: If module contains 'package' attribute, uses that as package name. Else, if module is not the ...
def get_package_for_module(module): if isinstance(module, six.string_types): try: module = sys.modules[module] except KeyError: return None try: return six.text_type(module.package) except AttributeError: if module.__name__ == '__main__': ...
388,408
Decode a DateTimeField parameter from a string to a python datetime. Args: encoded_datetime: A string in RFC 3339 format. Returns: A datetime object with the date and time specified in encoded_datetime. Raises: ValueError: If the string is not in a recognized format.
def decode_datetime(encoded_datetime): # Check if the string includes a time zone offset. Break out the # part that doesn't include time zone info. Convert to uppercase # because all our comparisons should be case-insensitive. time_zone_match = _TIME_ZONE_RE.search(encoded_datetime) if time_z...
388,410
Initialize a time zone offset. Args: offset: Integer or timedelta time zone offset, in minutes from UTC. This can be negative.
def __init__(self, offset): super(TimeZoneOffset, self).__init__() if isinstance(offset, datetime.timedelta): offset = total_seconds(offset) / 60 self.__offset = offset
388,411
Convert DateTimeMessage to a datetime. Args: A DateTimeMessage instance. Returns: A datetime instance.
def value_from_message(self, message): message = super(DateTimeField, self).value_from_message(message) if message.time_zone_offset is None: return datetime.datetime.utcfromtimestamp( message.milliseconds / 1000.0) # Need to subtract the time zone offset, be...
388,413
Calculates amount of time to wait before a retry attempt. Wait time grows exponentially with the number of attempts. A random amount of jitter is added to spread out retry attempts from different clients. Args: retry_attempt: Retry attempt counter. max_wait: Upper bound for wait time [seco...
def CalculateWaitForRetry(retry_attempt, max_wait=60): wait_time = 2 ** retry_attempt max_jitter = wait_time / 4.0 wait_time += random.uniform(-max_jitter, max_jitter) return max(1, min(wait_time, max_wait))
388,419
Get the userinfo associated with the given credentials. This is dependent on the token having either the userinfo.email or userinfo.profile scope for the given token. Args: credentials: (oauth2client.client.Credentials) incoming credentials http: (httplib2.Http, optional) http instance to use ...
def GetUserinfo(credentials, http=None): # pylint: disable=invalid-name http = http or httplib2.Http() url = _GetUserinfoUrl(credentials) # We ignore communication woes here (i.e. SSL errors, socket # timeout), as handling these should be done in a common location. response, content = http.req...
388,470
Initializes the credentials instance. Args: scopes: The scopes to get. If None, whatever scopes that are available to the instance are used. service_account_name: The service account to retrieve the scopes from. **kwds: Additional keyword args.
def __init__(self, scopes=None, service_account_name='default', **kwds): # If there is a connectivity issue with the metadata server, # detection calls may fail even if we've already successfully # identified these scopes in the same execution. However, the # available scopes do...
388,476
Checks the cache file to see if it matches the given credentials. Args: cache_filename: Cache filename to check. scopes: Scopes for the desired credentials. Returns: List of scopes (if cache matches) or None.
def _CheckCacheFileForMatch(self, cache_filename, scopes): creds = { # Credentials metadata dict. 'scopes': sorted(list(scopes)) if scopes else None, 'svc_acct_name': self.__service_account_name, } cache_file = _MultiProcessCacheFile(cache_filename) try:...
388,477
Writes the credential metadata to the cache file. This does not save the credentials themselves (CredentialStore class optionally handles that after this class is initialized). Args: cache_filename: Cache filename to check. scopes: Scopes for the desired credentials.
def _WriteCacheFile(self, cache_filename, scopes): # Credentials metadata dict. creds = {'scopes': sorted(list(scopes)), 'svc_acct_name': self.__service_account_name} creds_str = json.dumps(creds) cache_file = _MultiProcessCacheFile(cache_filename) try: ...
388,478
Refresh self.access_token. Args: _: (ignored) A function matching httplib2.Http.request's signature.
def _refresh(self, _): # pylint: disable=import-error from google.appengine.api import app_identity try: token, _ = app_identity.get_access_token(self._scopes) except app_identity.Error as e: raise exceptions.CredentialsError(str(e)) self.access_t...
388,485
Acquire an interprocess lock and write a string. This method safely acquires the locks then writes a string to the cache file. If the string is written successfully the function will return True, if the write fails for any reason it will return False. Args: cache_data...
def LockedWrite(self, cache_data): if isinstance(cache_data, six.text_type): cache_data = cache_data.encode(encoding=self._encoding) with self._thread_lock: if not self._EnsureFileExists(): return False with self._process_lock_getter() as acq...
388,489
Rebuilds all http connections in the httplib2.Http instance. httplib2 overloads the map in http.connections to contain two different types of values: { scheme string: connection class } and { scheme + authority string : actual http connection } Here we remove all of the entries for actual connecti...
def RebuildHttpConnections(http): if getattr(http, 'connections', None): for conn_key in list(http.connections.keys()): if ':' in conn_key: del http.connections[conn_key]
388,534
Exception handler for http failures. This catches known failures and rebuilds the underlying HTTP connections. Args: retry_args: An ExceptionRetryArgs tuple.
def HandleExceptionsAndRebuildHttpConnections(retry_args): # If the server indicates how long to wait, use that value. Otherwise, # calculate the wait time on our own. retry_after = None # Transport failures if isinstance(retry_args.exc, (http_client.BadStatusLine, ...
388,535
Initialize a batch API request object. Args: batch_url: Base URL for batch API calls. retryable_codes: A list of integer HTTP codes that can be retried. response_encoding: The encoding type of response content.
def __init__(self, batch_url=None, retryable_codes=None, response_encoding=None): self.api_requests = [] self.retryable_codes = retryable_codes or [] self.batch_url = batch_url or 'https://www.googleapis.com/batch' self.response_encoding = response_encoding
388,583
Add a request to the batch. Args: service: A class inheriting base_api.BaseApiService. method: A string indicated desired method from the service. See the example in the class docstring. request: An input message appropriate for the specified service.me...
def Add(self, service, method, request, global_params=None): # Retrieve the configs for the desired method and service. method_config = service.GetMethodConfig(method) upload_config = service.GetUploadConfig(method) # Prepare the HTTP Request. http_request = service.Pre...
388,584
Convert a Content-ID header value to an id. Presumes the Content-ID header conforms to the format that _ConvertIdToHeader() returns. Args: header: A string indicating the Content-ID header value. Returns: The extracted id value. Raises: BatchErro...
def _ConvertHeaderToId(header): if not (header.startswith('<') or header.endswith('>')): raise exceptions.BatchError( 'Invalid value for Content-ID: %s' % header) if '+' not in header: raise exceptions.BatchError( 'Invalid value for Conten...
388,587
Convert a http_wrapper.Request object into a string. Args: request: A http_wrapper.Request to serialize. Returns: The request as a string in application/http format.
def _SerializeRequest(self, request): # Construct status line parsed = urllib_parse.urlsplit(request.url) request_line = urllib_parse.urlunsplit( ('', '', parsed.path, parsed.query, '')) if not isinstance(request_line, six.text_type): request_line = reque...
388,588
Convert string into Response and content. Args: payload: Header and body string to be deserialized. Returns: A Response object
def _DeserializeResponse(self, payload): # Strip off the status line. status_line, payload = payload.split('\n', 1) _, status, _ = status_line.split(' ', 2) # Parse the rest of the response. parser = email_parser.Parser() msg = parser.parsestr(payload) ...
388,589
Serialize batch request, send to server, process response. Args: http: A httplib2.Http object to be used to make the request with. Raises: httplib2.HttpLib2Error if a transport error has occured. apiclient.errors.BatchError if the response is the wrong format.
def _Execute(self, http): message = mime_multipart.MIMEMultipart('mixed') # Message should not write out its own headers. setattr(message, '_write_headers', lambda self: None) # Add all the individual requests. for key in self.__request_response_handlers: ms...
388,591
Execute all the requests as a single batched HTTP request. Args: http: A httplib2.Http object to be used with the request. Returns: None Raises: BatchError if the response is the wrong format.
def Execute(self, http): self._Execute(http) for key in self.__request_response_handlers: response = self.__request_response_handlers[key].response callback = self.__request_response_handlers[key].handler exception = None if response.status_co...
388,592
Overridden to avoid setting variables after init. Setting attributes on a class must work during the period of initialization to set the enumation value class variables and build the name/number maps. Once __init__ has set the __initialized flag to True prohibits setting any more values...
def __setattr__(cls, name, value): if cls.__initialized and name not in _POST_INIT_ATTRIBUTE_NAMES: raise AttributeError('May not change values: %s' % name) else: type.__setattr__(cls, name, value)
388,596
Get the assigned value of an attribute. Get the underlying value of an attribute. If value has not been set, will not return the default for the field. Args: name: Name of attribute to get. Returns: Value of attribute, None if it has not been set.
def get_assigned_value(self, name): message_type = type(self) try: field = message_type.field_by_name(name) except KeyError: raise AttributeError('Message %s has no field %s' % ( message_type.__name__, name)) return self.__tags.get(field.n...
388,615
Reset assigned value for field. Resetting a field will return it to its default value or None. Args: name: Name of field to reset.
def reset(self, name): message_type = type(self) try: field = message_type.field_by_name(name) except KeyError: if name not in message_type.__by_name: raise AttributeError('Message %s has no field %s' % ( message_type.__name__,...
388,616
Get the value and variant of an unknown field in this message. Args: key: The name or number of the field to retrieve. value_default: Value to be returned if the key isn't found. variant_default: Value to be returned as variant if the key isn't found. Returns:...
def get_unrecognized_field_info(self, key, value_default=None, variant_default=None): value, variant = self.__unrecognized_fields.get(key, (value_default, variant_default)) return value, variant
388,617
Set an unrecognized field, used when decoding a message. Args: key: The name or number used to refer to this unknown value. value: The value of the field. variant: Type information needed to interpret the value or re-encode it. Raises: TypeError: If ...
def set_unrecognized_field(self, key, value, variant): if not isinstance(variant, Variant): raise TypeError('Variant type %s is not valid.' % variant) self.__unrecognized_fields[key] = value, variant
388,618
Change set behavior for messages. Messages may only be assigned values that are fields. Does not try to validate field when set. Args: name: Name of field to assign to. value: Value to assign to field. Raises: AttributeError when trying to assign value t...
def __setattr__(self, name, value): if name in self.__by_name or name.startswith('_Message__'): object.__setattr__(self, name, value) else: raise AttributeError("May not assign arbitrary value %s " "to message %s" % (name, type(self).__na...
388,619
Constructor. Args: field_instance: Instance of field that validates the list. sequence: List or tuple to construct list from.
def __init__(self, field_instance, sequence): if not field_instance.repeated: raise FieldDefinitionError( 'FieldList may only accept repeated fields') self.__field = field_instance self.__field.validate(sequence) list.__init__(self, sequence)
388,622
Enable unpickling. Args: state: A 3-tuple containing: - The field instance, or None if it belongs to a Message class. - The Message class that the field instance belongs to, or None. - The field instance number of the Message class it belongs to, or ...
def __setstate__(self, state): field_instance, message_class, number = state if field_instance is None: self.__field = message_class.field_by_number(number) else: self.__field = field_instance
388,624
Setter overidden to prevent assignment to fields after creation. Args: name: Name of attribute to set. value: Value to assign.
def __setattr__(self, name, value): # Special case post-init names. They need to be set after constructor. if name in _POST_INIT_FIELD_ATTRIBUTE_NAMES: object.__setattr__(self, name, value) return # All other attributes must be set before __initialized. ...
388,632
Set value on message. Args: message_instance: Message instance to set value on. value: Value to set on message.
def __set__(self, message_instance, value): # Reaches in to message instance directly to assign to private tags. if value is None: if self.repeated: raise ValidationError( 'May not assign None to repeated field %s' % self.name) else: ...
388,633
Validate single element of field. This is different from validate in that it is used on individual values of repeated fields. Args: value: Value to validate. Returns: The value casted in the expected type. Raises: ValidationError if value is not ...
def validate_element(self, value): if not isinstance(value, self.type): # Authorize int values as float. if isinstance(value, six.integer_types) and self.type == float: return float(value) if value is None: if self.required: ...
388,635
Internal validation function. Validate an internal value using a function to validate individual elements. Args: value: Value to validate. validate_element: Function to use to validate individual elements. Raises: ValidationError if value is not expected ...
def __validate(self, value, validate_element): if not self.repeated: return validate_element(value) else: # Must be a list or tuple, may not be a string. if isinstance(value, (list, tuple)): result = [] for element in value: ...
388,636
Set value on message. Args: message_instance: Message instance to set value on. value: Value to set on message.
def __set__(self, message_instance, value): t = self.type if isinstance(t, type) and issubclass(t, Message): if self.repeated: if value and isinstance(value, (list, tuple)): value = [(t(**v) if isinstance(v, dict) else v) ...
388,639
Convert a message to a value instance. Used by deserializers to convert from underlying messages to value of expected user type. Args: message: A message instance of type self.message_type. Returns: Value of self.message_type.
def value_from_message(self, message): if not isinstance(message, self.message_type): raise DecodeError('Expected type %s, got %s: %r' % (self.message_type.__name__, type(message).__name__, message))...
388,641
Convert a value instance to a message. Used by serializers to convert Python user types to underlying messages for transmission. Args: value: A value of type self.type. Returns: An instance of type self.message_type.
def value_to_message(self, value): if not isinstance(value, self.type): raise EncodeError('Expected type %s, got %s: %r' % (self.type.__name__, type(value).__name__, value)) return value
388,642
Validate default element of Enum field. Enum fields allow for delayed resolution of default values when the type of the field has not been resolved. The default value of a field may be a string or an integer. If the Enum type of the field has been resolved, the default value is ...
def validate_default_element(self, value): if isinstance(value, (six.string_types, six.integer_types)): # Validation of the value does not happen for delayed resolution # enumerated types. Ignore if type is not yet resolved. if self.__type: self.__ty...
388,644
Add a custom wire encoding for a given enum value. This is primarily used in generated code, to handle enum values which happen to be Python keywords. Args: enum_type: (messages.Enum) An enum type python_name: (basestring) Python name for this value. json_name: (basestring) JSON name to ...
def AddCustomJsonEnumMapping(enum_type, python_name, json_name, package=None): # pylint: disable=unused-argument if not issubclass(enum_type, messages.Enum): raise exceptions.TypecheckError( 'Cannot set JSON enum mapping for non-enum "%s"' % enum_type) if p...
388,666
Add a custom wire encoding for a given message field. This is primarily used in generated code, to handle enum values which happen to be Python keywords. Args: message_type: (messages.Message) A message type python_name: (basestring) Python name for this value. json_name: (basestring) JS...
def AddCustomJsonFieldMapping(message_type, python_name, json_name, package=None): # pylint: disable=unused-argument if not issubclass(message_type, messages.Message): raise exceptions.TypecheckError( 'Cannot set JSON field mapping for ' 'non-messa...
388,667
Decode the given JSON value. Args: field: a messages.Field for the field we're decoding. value: a python value we'd like to decode. Returns: A value suitable for assignment to field.
def decode_field(self, field, value): for decoder in _GetFieldCodecs(field, 'decoder'): result = decoder(field, value) value = result.value if result.complete: return value if isinstance(field, messages.MessageField): field_value =...
388,680
Encode the given value as JSON. Args: field: a messages.Field for the field we're encoding. value: a value for field. Returns: A python value suitable for json.dumps.
def encode_field(self, field, value): for encoder in _GetFieldCodecs(field, 'encoder'): result = encoder(field, value) value = result.value if result.complete: return value if isinstance(field, messages.EnumField): if field.repeate...
388,682
Give as input raw data and output a str in Python 3 and unicode in Python 2. Args: raw_data: Python 2 str, Python 3 bytes or str to porting encoding: string giving the name of an encoding errors: his specifies the treatment of characters which are invalid in the input encodi...
def ported_string(raw_data, encoding='utf-8', errors='ignore'): if not raw_data: return six.text_type() if isinstance(raw_data, six.text_type): return raw_data.strip() if six.PY2: try: return six.text_type(raw_data, encoding, errors).strip() except LookupE...
389,237
Given an raw header returns an decoded header Args: header (string): header to decode Returns: str (Python 3) or unicode (Python 2)
def decode_header_part(header): if not header: return six.text_type() output = six.text_type() try: for d, c in decode_header(header): c = c if c else 'utf-8' output += ported_string(d, c, 'ignore') # Header parsing failed, when header has charset Shift_JI...
389,238
This function return the fingerprints of data. Args: data (string): raw data Returns: namedtuple: fingerprints md5, sha1, sha256, sha512
def fingerprints(data): Hashes = namedtuple('Hashes', "md5 sha1 sha256 sha512") if six.PY2: if not isinstance(data, str): data = data.encode("utf-8") elif six.PY3: if not isinstance(data, bytes): data = data.encode("utf-8") # md5 md5 = hashlib.md5() ...
389,241
Exec msgconvert tool, to convert msg Outlook mail in eml mail format Args: email (string): file path of Outlook msg mail Returns: tuple with file path of mail converted and standard output data (unicode Python 2, str Python 3)
def msgconvert(email): log.debug("Started converting Outlook email") temph, temp = tempfile.mkstemp(prefix="outlook_") command = ["msgconvert", "--outfile", temp, email] try: if six.PY2: with open(os.devnull, "w") as devnull: out = subprocess.Popen( ...
389,242
Parse a single received header. Return a dictionary of values by clause. Arguments: received {str} -- single received header Raises: MailParserReceivedParsingError -- Raised when a received header cannot be parsed Returns: dict -- values by clause
def parse_received(received): values_by_clause = {} for pattern in RECEIVED_COMPILED_LIST: matches = [match for match in pattern.finditer(received)] if len(matches) == 0: # no matches for this clause, but it's ok! keep going! log.debug("No matches found for %s in %...
389,243
This function parses the receiveds headers. Args: receiveds (list): list of raw receiveds headers Returns: a list of parsed receiveds headers with first hop in first position
def receiveds_parsing(receiveds): parsed = [] receiveds = [re.sub(JUNK_PATTERN, " ", i).strip() for i in receiveds] n = len(receiveds) log.debug("Nr. of receiveds. {}".format(n)) for idx, received in enumerate(receiveds): log.debug("Parsing received {}/{}".format(idx + 1, n)) ...
389,244
If receiveds are not parsed, makes a new structure with raw field. It's useful to have the same structure of receiveds parsed. Args: receiveds (list): list of raw receiveds headers Returns: a list of not parsed receiveds headers with first hop in first position
def receiveds_not_parsed(receiveds): log.debug("Receiveds for this email are not parsed") output = [] counter = Counter() for i in receiveds[::-1]: j = {"raw": i.strip()} j["hop"] = counter["hop"] + 1 counter["hop"] += 1 output.append(j) else: return ou...
389,246
Given a list of receiveds hop, adds metadata and reformat field values Args: receiveds (list): list of receiveds hops already formatted Returns: list of receiveds reformated and with new fields
def receiveds_format(receiveds): log.debug("Receiveds for this email are parsed") output = [] counter = Counter() for i in receiveds[::-1]: # Clean strings j = {k: v.strip() for k, v in i.items() if v} # Add hop j["hop"] = counter["hop"] + 1 # Add UTC dat...
389,247
Gets an email.message.Message and a header name and returns the mail header decoded with the correct charset. Args: message (email.message.Message): email message object name (string): header to get Returns: decoded header
def get_header(message, name): header = message.get(name) log.debug("Getting header {!r}: {!r}".format(name, header)) if header: return decode_header_part(header) return six.text_type()
389,249
Given an email.message.Message, return a set with all email parts to get Args: message (email.message.Message): email message object complete (bool): if True returns all email headers Returns: set with all email parts
def get_mail_keys(message, complete=True): if complete: log.debug("Get all headers") all_headers_keys = {i.lower() for i in message.keys()} all_parts = ADDRESSES_HEADERS | OTHERS_PARTS | all_headers_keys else: log.debug("Get only mains headers") all_parts = ADDRESSE...
389,250
This function writes a sample on file system. Args: binary (bool): True if it's a binary file payload: payload of sample, in base64 if it's a binary path (string): path of file filename (string): name of file hash_ (string): file hash
def write_sample(binary, payload, path, filename): # pragma: no cover if not os.path.exists(path): os.makedirs(path) sample = os.path.join(path, filename) if binary: with open(sample, "wb") as f: f.write(base64.b64decode(payload)) else: with open(sample, "w") ...
389,254
Init a new object from a file-like object. Not for Outlook msg. Args: fp (file-like object): file-like object of raw email Returns: Instance of MailParser
def from_file_obj(cls, fp): log.debug("Parsing email from file object") try: fp.seek(0) except IOError: # When stdout is a TTY it's a character device # and it's not seekable, you cannot seek in a TTY. pass finally: s =...
389,258
Init a new object from a file path. Args: fp (string): file path of raw email is_outlook (boolean): if True is an Outlook email Returns: Instance of MailParser
def from_file(cls, fp, is_outlook=False): log.debug("Parsing email from file {!r}".format(fp)) with ported_open(fp) as f: message = email.message_from_file(f) if is_outlook: log.debug("Removing temp converted Outlook email {!r}".format(fp)) os.remov...
389,259
Init a new object from a Outlook message file, mime type: application/vnd.ms-outlook Args: fp (string): file path of raw Outlook email Returns: Instance of MailParser
def from_file_msg(cls, fp): log.debug("Parsing email from file Outlook") f, _ = msgconvert(fp) return cls.from_file(f, True)
389,260
Init a new object from a string. Args: s (string): raw email Returns: Instance of MailParser
def from_string(cls, s): log.debug("Parsing email from string") message = email.message_from_string(s) return cls(message)
389,261
Init a new object from bytes. Args: bt (bytes-like object): raw email as bytes-like object Returns: Instance of MailParser
def from_bytes(cls, bt): log.debug("Parsing email from bytes") if six.PY2: raise MailParserEnvironmentError( "Parsing from bytes is valid only for Python 3.x version") message = email.message_from_bytes(bt) return cls(message)
389,262
Add new defects and defects categories to object attributes. The defects are a list of all the problems found when parsing this message. Args: part (string): mail part part_content_type (string): content type of part
def _append_defects(self, part, part_content_type): part_defects = {} for e in part.defects: defects = "{}: {}".format(e.__class__.__name__, e.__doc__) self._defects_categories.add(e.__class__.__name__) part_defects.setdefault(part_content_type, []).append(...
389,264
Compute and factorize the covariance matrix. Args: x (ndarray[nsamples, ndim]): The independent coordinates of the data points. yerr (ndarray[nsamples] or float): The Gaussian uncertainties on the data points at coordinates ``x``. These values will be ...
def compute(self, x, yerr): # Compute the kernel matrix. K = self.kernel.get_value(x) K[np.diag_indices_from(K)] += yerr ** 2 # Factor the matrix and compute the log-determinant. self._factor = (cholesky(K, overwrite_a=True, lower=False), False) self.log_determi...
389,994
r""" Apply the inverse of the covariance matrix to the input by solving .. math:: K\,x = y Args: y (ndarray[nsamples] or ndadrray[nsamples, nrhs]): The vector or matrix :math:`y`. in_place (Optional[bool]): Should the data in ``y`` be overwr...
def apply_inverse(self, y, in_place=False): r return cho_solve(self._factor, y, overwrite_b=in_place)
389,995
r""" Compute the inner product of a vector with the inverse of the covariance matrix applied to itself: .. math:: y\,K^{-1}\,y Args: y (ndarray[nsamples]): The vector :math:`y`.
def dot_solve(self, y): r return np.dot(y.T, cho_solve(self._factor, y))
389,996
Get an ordered dictionary of the parameters Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``)
def get_parameter_dict(self, include_frozen=False): return OrderedDict(zip( self.get_parameter_names(include_frozen=include_frozen), self.get_parameter_vector(include_frozen=include_frozen), ))
390,004
Get a list of the parameter names Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``)
def get_parameter_names(self, include_frozen=False): if include_frozen: return self.parameter_names return tuple(p for p, f in zip(self.parameter_names, self.unfrozen_mask) if f)
390,005
Get a list of the parameter bounds Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``)
def get_parameter_bounds(self, include_frozen=False): if include_frozen: return self.parameter_bounds return list(p for p, f in zip(self.parameter_bounds, self.unfrozen_mask) if f)
390,006
Get an array of the parameter values in the correct order Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``)
def get_parameter_vector(self, include_frozen=False): if include_frozen: return self.parameter_vector return self.parameter_vector[self.unfrozen_mask]
390,007
Set the parameter values to the given vector Args: vector (array[vector_size] or array[full_size]): The target parameter vector. This must be in the same order as ``parameter_names`` and it should only include frozen parameters if ``include_frozen`` i...
def set_parameter_vector(self, vector, include_frozen=False): v = self.parameter_vector if include_frozen: v[:] = vector else: v[self.unfrozen_mask] = vector self.parameter_vector = v self.dirty = True
390,008
Freeze a parameter by name Args: name: The name of the parameter
def freeze_parameter(self, name): i = self.get_parameter_names(include_frozen=True).index(name) self.unfrozen_mask[i] = False
390,010
Thaw a parameter by name Args: name: The name of the parameter
def thaw_parameter(self, name): i = self.get_parameter_names(include_frozen=True).index(name) self.unfrozen_mask[i] = True
390,011
Get a parameter value by name Args: name: The name of the parameter
def get_parameter(self, name): i = self.get_parameter_names(include_frozen=True).index(name) return self.get_parameter_vector(include_frozen=True)[i]
390,012
Set a parameter value by name Args: name: The name of the parameter value (float): The new value for the parameter
def set_parameter(self, name, value): i = self.get_parameter_names(include_frozen=True).index(name) v = self.get_parameter_vector(include_frozen=True) v[i] = value self.set_parameter_vector(v, include_frozen=True)
390,013
Initialize the property. Args: get_media_files_func (callable): The function to call to generate the media files. media_cls (type): The Media class owning the property. extra_files (object): Files listed in the original ``css...
def __init__(self, get_media_files_func, media_cls, extra_files): self._get_media_files_func = get_media_files_func self._media_cls = media_cls self._extra_files = extra_files
390,117
Construct the class. Args: name (bytes): The name of the class. bases (tuple): The base classes for the class. attrs (dict): The attributes going into the class. Returns: type: The new class.
def __new__(cls, name, bases, attrs): new_class = super(PipelineFormMediaMetaClass, cls).__new__( cls, name, bases, attrs) # If we define any packages, we'll need to use our special # PipelineFormMediaProperty class. We use this instead of intercepting # in __getatt...
390,118
Return all CSS files from the Media class. Args: extra_files (dict): The contents of the Media class's original :py:attr:`css` attribute, if one was provided. Returns: dict: The CSS media types and files to return for the :py:attr:`cs...
def _get_css_files(cls, extra_files): packager = Packager() css_packages = getattr(cls, 'css_packages', {}) return dict( (media_target, cls._get_media_files(packager=packager, media_packages=media_packages, ...
390,119
Return all JavaScript files from the Media class. Args: extra_files (list): The contents of the Media class's original :py:attr:`js` attribute, if one was provided. Returns: list: The JavaScript files to return for the :py:attr:`js` a...
def _get_js_files(cls, extra_files): return cls._get_media_files( packager=Packager(), media_packages=getattr(cls, 'js_packages', {}), media_type='js', extra_files=extra_files)
390,120
Initializes a path specification. Note that the TSK path specification must have a parent. Args: data_stream (Optional[str]): data stream name, where None indicates the default data stream. inode (Optional[int]): inode. location (Optional[str]): location. parent (Optional[Pat...
def __init__( self, data_stream=None, inode=None, location=None, parent=None, **kwargs): # Note that pytsk/libtsk overloads inode and a value of 0 is valid in # contrast to an ext file system. if (inode is None and not location) or not parent: raise ValueError('Missing inode and location, o...
391,141
Initializes a volume scanner. Args: mediator (VolumeScannerMediator): a volume scanner mediator.
def __init__(self, mediator=None): super(VolumeScanner, self).__init__() self._mediator = mediator self._source_path = None self._source_scanner = source_scanner.SourceScanner() self._source_type = None
391,155
Determines the APFS volume identifiers. Args: scan_node (SourceScanNode): scan node. Returns: list[str]: APFS volume identifiers. Raises: ScannerError: if the format of or within the source is not supported or the the scan node is invalid. UserAbort: if the user requeste...
def _GetAPFSVolumeIdentifiers(self, scan_node): if not scan_node or not scan_node.path_spec: raise errors.ScannerError('Invalid scan node.') volume_system = apfs_volume_system.APFSVolumeSystem() volume_system.Open(scan_node.path_spec) volume_identifiers = self._source_scanner.GetVolumeIdent...
391,156
Determines the TSK partition identifiers. Args: scan_node (SourceScanNode): scan node. Returns: list[str]: TSK partition identifiers. Raises: ScannerError: if the format of or within the source is not supported or the scan node is invalid or if the volume for a specific identi...
def _GetTSKPartitionIdentifiers(self, scan_node): if not scan_node or not scan_node.path_spec: raise errors.ScannerError('Invalid scan node.') volume_system = tsk_volume_system.TSKVolumeSystem() volume_system.Open(scan_node.path_spec) volume_identifiers = self._source_scanner.GetVolumeIdent...
391,157
Determines the VSS store identifiers. Args: scan_node (SourceScanNode): scan node. Returns: list[str]: VSS store identifiers. Raises: ScannerError: if the format the scan node is invalid or no mediator is provided and VSS store identifiers are found. UserAbort: if the us...
def _GetVSSStoreIdentifiers(self, scan_node): if not scan_node or not scan_node.path_spec: raise errors.ScannerError('Invalid scan node.') volume_system = vshadow_volume_system.VShadowVolumeSystem() volume_system.Open(scan_node.path_spec) volume_identifiers = self._source_scanner.GetVolumeI...
391,158
Normalizes volume identifiers. Args: volume_system (VolumeSystem): volume system. volume_identifiers (list[int|str]): allowed volume identifiers, formatted as an integer or string with prefix. prefix (Optional[str]): volume identifier prefix. Returns: list[str]: volume identi...
def _NormalizedVolumeIdentifiers( self, volume_system, volume_identifiers, prefix='v'): normalized_volume_identifiers = [] for volume_identifier in volume_identifiers: if isinstance(volume_identifier, int): volume_identifier = '{0:s}{1:d}'.format(prefix, volume_identifier) elif n...
391,159
Scans an encrypted volume scan node for volume and file systems. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): volume scan node. Raises: ScannerError: if the format of or within the source is not supported, the scan node is invalid, ...
def _ScanEncryptedVolume(self, scan_context, scan_node): if not scan_node or not scan_node.path_spec: raise errors.ScannerError('Invalid or missing scan node.') credentials = credentials_manager.CredentialsManager.GetCredentials( scan_node.path_spec) if not credentials: raise error...
391,160