Search is not available for this dataset
text
stringlengths
75
104k
def get_attachments_ids(self, ticket_id): """ Get IDs of attachments for given ticket. :param ticket_id: ID of ticket :returns: List of IDs (type int) of attachments belonging to given ticket. Returns None if ticket does not exist. """ attachments = self.get_at...
def get_attachment(self, ticket_id, attachment_id): """ Get attachment. :param ticket_id: ID of ticket :param attachment_id: ID of attachment for obtain :returns: Attachment as dictionary with these keys: * Transaction * ContentType ...
def get_attachment_content(self, ticket_id, attachment_id): """ Get content of attachment without headers. This function is necessary to use for binary attachment, as it can contain ``\\n`` chars, which would disrupt parsing of message if :py:meth:`~Rt.get_attachment` is used. ...
def get_user(self, user_id): """ Get user details. :param user_id: Identification of user by username (str) or user ID (int) :returns: User details as strings in dictionary with these keys for RT users: * Lang ...
def create_user(self, Name, EmailAddress, **kwargs): """ Create user (undocumented API feature). :param Name: User name (login for privileged, required) :param EmailAddress: Email address (required) :param kwargs: Optional fields to set (see edit_user) :returns: ID of new user o...
def edit_queue(self, queue_id, **kwargs): """ Edit queue (undocumented API feature). :param queue_id: Identification of queue by name (str) or ID (int) :param kwargs: Other fields to edit from the following list: * Name * Description ...
def create_queue(self, Name, **kwargs): """ Create queue (undocumented API feature). :param Name: Queue name (required) :param kwargs: Optional fields to set (see edit_queue) :returns: ID of new queue or False when create fails :raises BadRequest: When queue already exists ...
def get_links(self, ticket_id): """ Gets the ticket links for a single ticket. :param ticket_id: ticket ID :returns: Links as lists of strings in dictionary with these keys (just those which are defined): * id * Members ...
def edit_ticket_links(self, ticket_id, **kwargs): """ Edit ticket links. .. warning:: This method is deprecated in favour of edit_link method, because there exists bug in RT 3.8 REST API causing mapping created links to ticket/1. The only drawback is that edit_link cannot process ...
def edit_link(self, ticket_id, link_name, link_value, delete=False): """ Creates or deletes a link between the specified tickets (undocumented API feature). :param ticket_id: ID of ticket to edit :param link_name: Name of link to edit (DependsOn, DependedOnBy, RefersTo...
def merge_ticket(self, ticket_id, into_id): """ Merge ticket into another (undocumented API feature). :param ticket_id: ID of ticket to be merged :param into: ID of destination ticket :returns: ``True`` Operation was successful ``False`` ...
def untake(self, ticket_id): """ Untake ticket :param ticket_id: ID of ticket to be merged :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not own the ticket. ...
def split_header(line): """ Split a header line into field name and field value. Note that custom fields may contain colons inside the curly braces, so we need a special test for them. :param line: A message line to be split. :returns: (Field name, field value) tuple. ...
def PrivateKeyFromWIF(wif): """ Get the private key from a WIF key Args: wif (str): The wif key Returns: bytes: The private key """ if wif is None or len(wif) is not 52: raise ValueError('Please provide a wif with a length of 52 bytes...
def PrivateKeyFromNEP2(nep2_key, passphrase): """ Gets the private key from a NEP-2 encrypted private key Args: nep2_key (str): The nep-2 encrypted private key passphrase (str): The password to encrypt the private key with, as unicode string Returns: ...
def GetAddress(self): """ Returns the public NEO address for this KeyPair Returns: str: The private key """ script = b'21' + self.PublicKey.encode_point(True) + b'ac' script_hash = Crypto.ToScriptHash(script) address = Crypto.ToAddress(script_hash) ...
def Export(self): """ Export this KeyPair's private key in WIF format. Returns: str: The key in wif format """ data = bytearray(38) data[0] = 0x80 data[1:33] = self.PrivateKey[0:32] data[33] = 0x01 checksum = Crypto.Default().Hash256(...
def ExportNEP2(self, passphrase): """ Export the encrypted private key in NEP-2 format. Args: passphrase (str): The password to encrypt the private key with, as unicode string Returns: str: The NEP-2 encrypted private key """ if len(passphrase) <...
def unpack(self, fmt, length=1): """ Unpack the stream contents according to the specified format in `fmt`. For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html Args: fmt (str): format string. length (int): amount of byte...
def ReadByte(self, do_ord=True): """ Read a single byte. Args: do_ord (bool): (default True) convert the byte to an ordinal first. Returns: bytes: a single byte if successful. 0 (int) if an exception occurred. """ try: if do_ord: ...
def SafeReadBytes(self, length): """ Read exactly `length` number of bytes from the stream. Raises: ValueError is not enough data Returns: bytes: `length` number of bytes """ data = self.ReadBytes(length) if len(data) < length: ...
def ReadVarInt(self, max=sys.maxsize): """ Read a variable length integer from the stream. The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention Args: max (int): (Optional) maximum number of b...
def ReadVarBytes(self, max=sys.maxsize): """ Read a variable length of bytes from the stream. The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention Args: max (int): (Optional) maximum number o...
def ReadString(self): """ Read a string from the stream. Returns: str: """ length = self.ReadUInt8() return self.unpack(str(length) + 's', length)
def ReadVarString(self, max=sys.maxsize): """ Similar to `ReadString` but expects a variable length indicator instead of the fixed 1 byte indicator. Args: max (int): (Optional) maximum number of bytes to read. Returns: bytes: """ length = self.Re...
def ReadSerializableArray(self, class_name, max=sys.maxsize): """ Deserialize a stream into the object specific by `class_name`. Args: class_name (str): a full path to the class to be deserialized into. e.g. 'neo.Core.Block.Block' max (int): (Optional) maximum number of ...
def Read2000256List(self): """ Read 2000 times a 64 byte value from the stream. Returns: list: a list containing 2000 64 byte values in reversed form. """ items = [] for i in range(0, 2000): data = self.ReadBytes(64) ba = bytearray(bin...
def ReadHashes(self): """ Read Hash values from the stream. Returns: list: a list of hash values. Each value is of the bytearray type. """ len = self.ReadVarInt() items = [] for i in range(0, len): ba = bytearray(self.ReadBytes(32)) ...
def ToScriptHash(data, unhex=True): """ Get a script hash of the data. Args: data (bytes): data to hash. unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb' Returns: UInt160: script hash. ...
def Sign(message, private_key): """ Sign the message with the given private key. Args: message (str): message to be signed private_key (str): 32 byte key as a double digit hex string (e.g. having a length of 64) Returns: bytearray: the signature of th...
def VerifySignature(message, signature, public_key, unhex=True): """ Verify the integrity of the message. Args: message (str): the message to verify. signature (bytearray): the signature belonging to the message. public_key (ECPoint|bytes): the public key to ...
def VerifySignature(self, message, signature, public_key, unhex=True): """ Verify the integrity of the message. Args: message (str): the message to verify. signature (bytearray): the signature belonging to the message. public_key (ECPoint): the public key to ...
def _lucas_sequence(n, P, Q, k): """Return the modular Lucas sequence (U_k, V_k, Q_k). Given a Lucas sequence defined by P, Q, returns the kth values for U and V, along with Q^k, all modulo n. """ D = P * P - 4 * Q if n < 2: raise ValueError("n must be >= 2") if k < 0: raise ...
def sqrt(self, val, flag): """ calculate the square root modulus p """ if val.iszero(): return val sw = self.p % 8 if sw == 3 or sw == 7: res = val ** ((self.p + 1) / 4) elif sw == 5: x = val ** ((self.p + 1) / 4) if...
def value(self, x): """ converts an integer or FinitField.Value to a value of this FiniteField. """ return x if isinstance(x, FiniteField.Value) and x.field == self else FiniteField.Value(self, x)
def integer(self, x): """ returns a plain integer """ if type(x) is str: hex = binascii.unhexlify(x) return int.from_bytes(hex, 'big') return x.value if isinstance(x, FiniteField.Value) else x
def add(self, p, q): """ perform elliptic curve addition """ if p.iszero(): return q if q.iszero(): return p lft = 0 # calculate the slope of the intersection line if p == q: if p.y == 0: return self.zer...
def zero(self): """ Return the additive identity point ( aka '0' ) P + 0 = P """ return self.point(self.field.zero(), self.field.zero())
def point(self, x, y): """ construct a point from 2 values """ return EllipticCurve.ECPoint(self, self.field.value(x), self.field.value(y))
def isoncurve(self, p): """ verifies if a point is on the curve """ return p.iszero() or p.y ** 2 == p.x ** 3 + self.a * p.x + self.b
def decompress(self, x, flag): """ calculate the y coordinate given only the x value. there are 2 possible solutions, use 'flag' to select. """ x = self.field.value(x) ysquare = x ** 3 + self.a * x + self.b return self.point(x, ysquare.sqrt(flag))
def decompress_from_curve(self, x, flag): """ calculate the y coordinate given only the x value. there are 2 possible solutions, use 'flag' to select. """ cq = self.field.p x = self.field.value(x) ysquare = x ** 3 + self.a * x + self.b ysquare_root = sq...
def sign(self, message, privkey, secret): """ sign the message using private key and sign secret for signsecret k, message m, privatekey x return (G*k, (m+x*r)/k) """ m = self.GFn.value(message) x = self.GFn.value(privkey) k = self.GFn.value(secret) ...
def verify(self, message, pubkey, rnum, snum): """ Verify the signature for message m, pubkey Y, signature (r,s) r = xcoord(R) verify that : G*m+Y*r=R*s this is true because: { Y=G*x, and R=G*k, s=(m+x*r)/k } G*m+G*x*r = G*k*(m+x*r)/k -> G*(m+x*r) = G*(...
def findpk(self, message, rnum, snum, flag): """ find pubkey Y from message m, signature (r,s) Y = (R*s-G*m)/r note that there are 2 pubkeys related to a signature """ m = self.GFn.value(message) r = self.GFn.value(rnum) s = self.GFn.value(snum) R...
def findpk2(self, r1, s1, r2, s2, flag1, flag2): """ find pubkey Y from 2 different signature on the same message sigs: (r1,s1) and (r2,s2) returns (R1*s1-R2*s2)/(r1-r2) """ R1 = self.ec.decompress(r1, flag1) R2 = self.ec.decompress(r2, flag2) rdiff = se...
def crack2(self, r, s1, s2, m1, m2): """ find signsecret and privkey from duplicate 'r' signature (r,s1) for message m1 and signature (r,s2) for message m2 s1= (m1 + x*r)/k s2= (m2 + x*r)/k subtract -> (s1-s2) = (m1-m2)/k -> k = (m1-m2)/(s1-s2) -> privke...
def crack1(self, rnum, snum, message, signsecret): """ find privkey, given signsecret k, message m, signature (r,s) x= (s*k-m)/r """ m = self.GFn.value(message) r = self.GFn.value(rnum) s = self.GFn.value(snum) k = self.GFn.value(signsecret) return...
def secp256r1(): """ create the secp256r1 curve """ GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16)) ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948, 41058363725152142129326129780...
def decode_secp256r1(str, unhex=True, check_on_curve=True): """ decode a public key on the secp256r1 curve """ GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16)) ec = EllipticCurve(GFp, 1157920892103562487626974469494075735300861434152...
def secp256k1(): """ create the secp256k1 curve """ GFp = FiniteField(2 ** 256 - 2 ** 32 - 977) # This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F ec = EllipticCurve(GFp, 0, 7) return ECDSA(ec, ec.point(0x79BE667EF9DCBBAC55A062...
def GetHashCode(self): """uint32 identifier""" slice_length = 4 if len(self.Data) >= 4 else len(self.Data) return int.from_bytes(self.Data[:slice_length], 'little')
def isValidPublicAddress(address: str) -> bool: """Check if address is a valid NEO address""" valid = False if len(address) == 34 and address[0] == 'A': try: base58.b58decode_check(address.encode()) valid = True except ValueError: # checksum mismatch ...
def __Build(leaves): """ Build the merkle tree. Args: leaves (list): items are of type MerkleTreeNode. Returns: MerkleTreeNode: the root node. """ if len(leaves) < 1: raise Exception('Leaves must have length') if len(leaves) =...
def ComputeRoot(hashes): """ Compute the root hash. Args: hashes (list): the list of hashes to build the root from. Returns: bytes: the root hash. """ if not len(hashes): raise Exception('Hashes must have length') if len(hashe...
def __DepthFirstSearch(node, hashes): """ Internal helper method. Args: node (MerkleTreeNode): hashes (list): each item is a bytearray. """ if node.LeftChild is None: hashes.add(node.Hash) else: MerkleTree.__DepthFirstSearc...
def ToHashArray(self): """ Turn the tree into a list of hashes. Returns: list: """ hashes = set() MerkleTree.__DepthFirstSearch(self.Root, hashes) return list(hashes)
def Trim(self, flags): """ Trim the nodes from the tree keeping only the root hash. Args: flags: "0000" for trimming, any other value for keeping the nodes. """ logger.info("Trimming!") flags = bytearray(flags) length = 1 << self.Depth - 1 whi...
def _TrimNode(node, index, depth, flags): """ Internal helper method to trim a node. Args: node (MerkleTreeNode): index (int): flag index. depth (int): node tree depth to start trim from. flags (bytearray): of left/right pairs. 1 byte for the left...
def double_sha256(ba): """ Perform two SHA256 operations on the input. Args: ba (bytes): data to hash. Returns: str: hash as a double digit hex string. """ d1 = hashlib.sha256(ba) d2 = hashlib.sha256() d1.hexdigest() d2.update(d1.digest()) return d2.hexdigest()
def scripthash_to_address(scripthash): """ Convert a script hash to a public address. Args: scripthash (bytes): Returns: str: base58 encoded string representing the wallet address. """ sb = bytearray([ADDRESS_VERSION]) + scripthash c256 = bin_dbl_sha256(sb)[0:4] outb = ...
def bin_hash160Bytes(bts): """ Get a hash of the provided message using the ripemd160 algorithm. Args: bts (str): message to hash. Returns: bytes: hash. """ intermed = hashlib.sha256(bts).digest() return hashlib.new('ripemd160', intermed).digest()
def bin_hash160(string): """ Get a hash of the provided message using the ripemd160 algorithm. Args: string (str): message to hash. Returns: str: hash as a double digit hex string. """ intermed = hashlib.sha256(string).digest() return hashlib.new('ripemd160', intermed).hexd...
def base256_encode(n, minwidth=0): # int/long to byte array """ Encode the input with base256. Args: n (int): input value. minwidth: minimum return value length. Raises: ValueError: if a negative number is provided. Returns: bytearray: """ if n > 0: ...
def xor_bytes(a, b): """ XOR on two bytes objects Args: a (bytes): object 1 b (bytes): object 2 Returns: bytes: The XOR result """ assert isinstance(a, bytes) assert isinstance(b, bytes) assert len(a) == len(b) res = bytearray() for i in range(len(a)): ...
def WriteBytes(self, value, unhex=True): """ Write a `bytes` type to the stream. Args: value (bytes): array of bytes to write to the stream. unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb' Returns: ...
def pack(self, fmt, data): """ Write bytes by packing them according to the provided format `fmt`. For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html Args: fmt (str): format string. data (object): the data to write to t...
def WriteUInt160(self, value): """ Write a UInt160 type to the stream. Args: value (UInt160): Raises: Exception: when `value` is not of neocore.UInt160 type. """ if type(value) is UInt160: value.Serialize(self) else: ...
def WriteUInt256(self, value): """ Write a UInt256 type to the stream. Args: value (UInt256): Raises: Exception: when `value` is not of neocore.UInt256 type. """ if type(value) is UInt256: value.Serialize(self) else: ...
def WriteVarBytes(self, value, endian="<"): """ Write an integer value in a space saving way to the stream. Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention Args: value (bytes): endian (str): specify the...
def WriteVarString(self, value, encoding="utf-8"): """ Write a string value to the stream. Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention Args: value (string): value to write to the stream. encoding (s...
def WriteFixedString(self, value, length): """ Write a string value to the stream. Args: value (str): value to write to the stream. length (int): length of the string to write. """ towrite = value.encode('utf-8') slen = len(towrite) if sle...
def WriteSerializableArray(self, array): """ Write an array of serializable objects to the stream. Args: array(list): a list of serializable objects. i.e. extending neo.IO.Mixins.SerializableMixin """ if array is None: self.WriteByte(0) else: ...
def Write2000256List(self, arr): """ Write an array of 64 byte items to the stream. Args: arr (list): a list of 2000 items of 64 bytes in size. """ for item in arr: ba = bytearray(binascii.unhexlify(item)) ba.reverse() self.WriteBy...
def WriteHashes(self, arr): """ Write an array of hashes to the stream. Args: arr (list): a list of 32 byte hashes. """ length = len(arr) self.WriteVarInt(length) for item in arr: ba = bytearray(binascii.unhexlify(item)) ba.rev...
def get_user_id(self, user): """ Get identifier for a user. Take the one defined in settings.SAML_IDP_DJANGO_USERNAME_FIELD first, if not set use the USERNAME_FIELD property which is set on the user Model. This defaults to the user.username field. """ user_field = getattr(settings, '...
def create_identity(self, user, sp_mapping, **extra_config): """ Generate an identity dictionary of the user based on the given mapping of desired user attributes by the SP """ return { out_attr: getattr(user, user_attr) for user_attr, out_attr in sp_mapping.items() ...
def sso_entry(request): """ Entrypoint view for SSO. Gathers the parameters from the HTTP request, stores them in the session and redirects the requester to the login_process view. """ if request.method == 'POST': passed_data = request.POST binding = BINDING_HTTP_POST else: ...
def metadata(request): """ Returns an XML with the SAML 2.0 metadata for this Idp. The metadata is constructed on-the-fly based on the config dict in the django settings. """ conf = IdPConfig() conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG)) metadata = entity_descriptor(conf) return H...
def dispatch(self, request, *args, **kwargs): """ Construct IDP server with config from settings dict """ conf = IdPConfig() try: conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG)) self.IDP = Server(config=conf) except Exception as e: return se...
def get_processor(self, entity_id, sp_config): """ Instantiate user-specified processor or default to an all-access base processor. Raises an exception if the configured processor class can not be found or initialized. """ processor_string = sp_config.get('processor', None) i...
def get_identity(self, processor, user, sp_config): """ Create Identity dict (using SP-specific mapping) """ sp_mapping = sp_config.get('attribute_mapping', {'username': 'username'}) return processor.create_identity(user, sp_mapping, **sp_config.get('extra_config', {}))
def custom_update_user(sender, instance, attributes, user_modified, **kargs): """ Default behaviour does not play nice with booleans encoded in SAML as u'true'/u'false'. This will convert those attributes to real booleans when saving. """ for k, v in attributes.items(): u = set.intersection(...
def parse_time(s): """ Like datetime.datetime.strptime(s, "%w %Y/%m/%d %H:%M:%S") but 5x faster. """ result = None if "epoch" in s: epoch_time = float(s.rstrip().split(' ')[1][:-1]) result = datetime.datetime.utcfromtimestamp(epoch_time) else: _, date_part, time_part = s...
def _extract_prop_option(line): """ Extract the (key,value)-tuple from a string like: >>> "option foobar 123" :param line: :return: tuple (key, value) """ line = line[7:] pos = line.find(' ') return line[:pos], line[pos + 1:]
def _extract_prop_set(line): """ Extract the (key, value)-tuple from a string like: >>> 'set foo = "bar"' :param line: :return: tuple (key, value) """ token = ' = "' line = line[4:] pos = line.find(token) return line[:pos], line[pos + 4:-1]
def _extract_properties(config): """ Parse a line within a lease block The line should basically match the expression: >>> r"\s+(?P<key>(?:option|set)\s+\S+|\S+) (?P<value>[\s\S]+?);" For easier seperation of the cases and faster parsing this is done using substrings etc.. :param config: :re...
def get(self, include_backups=False): """ Parse the lease file and return a list of Lease instances. """ leases = [] with open(self.filename) if not self.gzip else gzip.open(self.filename) as lease_file: lease_data = lease_file.read() if self.gzip: ...
def get_current(self): """ Parse the lease file and return a dict of active and valid Lease instances. The key for this dict is the ethernet address of the lease. """ all_leases = self.get() leases = {} for lease in all_leases: if lease.valid and lease...
def valid(self): """ Checks if the lease is currently valid (not expired and not in the future) :return: bool: True if lease is valid """ if self.end is None: if self.start is not None: return self.start <= datetime.datetime.utcnow() else: ...
def valid(self): """ Checks if the lease is currently valid (not expired) :return: bool: True if lease is valid """ if self.end is None: return True else: return datetime.datetime.utcnow() <= self.end
def _padleft(width, s, has_invisible=True): """Flush right. >>> _padleft(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430' True """ def impl(val): iwidth = width + len(val) - len(_strip_invisible(val)) if has_invisible else width fmt = "{0:>%ds}" % iwidth retu...
def _visible_width(s): """Visible width of a printed string. ANSI color codes are removed. >>> _visible_width('\x1b[31mhello\x1b[0m'), _visible_width("world") (5, 5) """ if isinstance(s, _text_type) or isinstance(s, _binary_type): return _max_line_width(_strip_invisible(s)) else: ...
def _column_type(values, has_invisible=True): """The least generic type all column values are convertible to. >>> _column_type(["1", "2"]) is _int_type True >>> _column_type(["1", "2.3"]) is _float_type True >>> _column_type(["1", "2.3", "four"]) is _text_type True >>> _column_type(["fo...
def _normalize_tabular_data(tabular_data, headers): """Transform a supported data type to a list of lists, and a list of headers. Supported tabular data types: * list-of-lists or another iterable of iterables * list of named tuples (usually used with headers="keys") * list of dicts (usually used...
def tabulate(tabular_data, headers=(), tablefmt="simple", floatfmt="g", numalign="decimal", stralign="left", missingval=""): """Format a fixed width table for pretty printing. >>> print(tabulate([[1, 2.34], [-56, "8.999"], ["2", "10001"]])) --- --------- 1 2.34 -56...
def _format_table(fmt, headers, rows, colwidths, colaligns, is_multiline): """Produce a plain-text representation of the table.""" lines = [] hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else [] pad = fmt.padding headerrow = fmt.headerrow padded_widths = [(w + 2 * pad) fo...
def create_layout(lexer=None, reserve_space_for_menu=8, get_prompt_tokens=None, get_bottom_toolbar_tokens=None, extra_input_processors=None, multiline=False, wrap_lines=True): """ Creates a custom `Layout` for the Crash in...
def parse_config_path(args=sys.argv): """ Preprocess sys.argv and extract --config argument. """ config = CONFIG_PATH if '--config' in args: idx = args.index('--config') if len(args) > idx + 1: config = args.pop(idx + 1) args.pop(idx) return config
def get_parser(output_formats=[], conf=None): """ Create an argument parser that reads default values from a configuration file if provided. """ def _conf_or_default(key, value): return value if conf is None else conf.get_or_set(key, value) parser = ArgumentParser(description='crate sh...