repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
invoice-x/invoice2data | src/invoice2data/output/to_csv.py | write_to_file | python | def write_to_file(data, path):
if path.endswith('.csv'):
filename = path
else:
filename = path + '.csv'
if sys.version_info[0] < 3:
openfile = open(filename, "wb")
else:
openfile = open(filename, "w", newline='')
with openfile as csv_file:
writer = csv.write... | Export extracted fields to csv
Appends .csv to path if missing and generates csv file in specified directory, if not then in root
Parameters
----------
data : dict
Dictionary of extracted fields
path : str
directory to save generated csv file
Notes
----
Do give file na... | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/output/to_csv.py#L5-L54 | null | import csv
import sys
|
invoice-x/invoice2data | src/invoice2data/input/tesseract.py | to_text | python | def to_text(path):
import subprocess
from distutils import spawn
# Check for dependencies. Needs Tesseract and Imagemagick installed.
if not spawn.find_executable('tesseract'):
raise EnvironmentError('tesseract not installed.')
if not spawn.find_executable('convert'):
raise Environm... | Wraps Tesseract OCR.
Parameters
----------
path : str
path of electronic invoice in JPG or PNG format
Returns
-------
extracted_str : str
returns extracted text from image in JPG or PNG format | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/input/tesseract.py#L4-L38 | null | # -*- coding: utf-8 -*-
|
invoice-x/invoice2data | src/invoice2data/extract/plugins/tables.py | extract | python | def extract(self, content, output):
for table in self['tables']:
# First apply default options.
plugin_settings = DEFAULT_OPTIONS.copy()
plugin_settings.update(table)
table = plugin_settings
# Validate settings
assert 'start' in table, 'Table start regex missing'
... | Try to extract tables from an invoice | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/plugins/tables.py#L11-L56 | null | """
Plugin to extract tables from an invoice.
"""
import re
import logging as logger
DEFAULT_OPTIONS = {'field_separator': r'\s+', 'line_separator': r'\n'}
|
invoice-x/invoice2data | src/invoice2data/input/pdftotext.py | to_text | python | def to_text(path):
import subprocess
from distutils import spawn # py2 compat
if spawn.find_executable("pdftotext"): # shutil.which('pdftotext'):
out, err = subprocess.Popen(
["pdftotext", '-layout', '-enc', 'UTF-8', path, '-'], stdout=subprocess.PIPE
).communicate()
r... | Wrapper around Poppler pdftotext.
Parameters
----------
path : str
path of electronic invoice in PDF
Returns
-------
out : str
returns extracted text from pdf
Raises
------
EnvironmentError:
If pdftotext library is not found | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/input/pdftotext.py#L2-L31 | null | # -*- coding: utf-8 -*-
|
invoice-x/invoice2data | src/invoice2data/extract/invoice_template.py | InvoiceTemplate.prepare_input | python | def prepare_input(self, extracted_str):
# Remove withspace
if self.options['remove_whitespace']:
optimized_str = re.sub(' +', '', extracted_str)
else:
optimized_str = extracted_str
# Remove accents
if self.options['remove_accents']:
optimized... | Input raw string and do transformations, as set in template file. | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/invoice_template.py#L64-L88 | null | class InvoiceTemplate(OrderedDict):
"""
Represents single template files that live as .yml files on the disk.
Methods
-------
prepare_input(extracted_str)
Input raw string and do transformations, as set in template file.
matches_input(optimized_str)
See if string matches keyword... |
invoice-x/invoice2data | src/invoice2data/extract/invoice_template.py | InvoiceTemplate.matches_input | python | def matches_input(self, optimized_str):
if all([keyword in optimized_str for keyword in self['keywords']]):
logger.debug('Matched template %s', self['template_name'])
return True | See if string matches keywords set in template file | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/invoice_template.py#L90-L95 | null | class InvoiceTemplate(OrderedDict):
"""
Represents single template files that live as .yml files on the disk.
Methods
-------
prepare_input(extracted_str)
Input raw string and do transformations, as set in template file.
matches_input(optimized_str)
See if string matches keyword... |
invoice-x/invoice2data | src/invoice2data/extract/invoice_template.py | InvoiceTemplate.parse_date | python | def parse_date(self, value):
res = dateparser.parse(
value, date_formats=self.options['date_formats'], languages=self.options['languages']
)
logger.debug("result of date parsing=%s", res)
return res | Parses date and returns date after parsing | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/invoice_template.py#L108-L114 | null | class InvoiceTemplate(OrderedDict):
"""
Represents single template files that live as .yml files on the disk.
Methods
-------
prepare_input(extracted_str)
Input raw string and do transformations, as set in template file.
matches_input(optimized_str)
See if string matches keyword... |
invoice-x/invoice2data | src/invoice2data/extract/invoice_template.py | InvoiceTemplate.extract | python | def extract(self, optimized_str):
logger.debug('START optimized_str ========================')
logger.debug(optimized_str)
logger.debug('END optimized_str ==========================')
logger.debug(
'Date parsing: languages=%s date_formats=%s',
self.options['langu... | Given a template file and a string, extract matching data fields. | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/invoice_template.py#L129-L222 | null | class InvoiceTemplate(OrderedDict):
"""
Represents single template files that live as .yml files on the disk.
Methods
-------
prepare_input(extracted_str)
Input raw string and do transformations, as set in template file.
matches_input(optimized_str)
See if string matches keyword... |
invoice-x/invoice2data | src/invoice2data/output/to_json.py | write_to_file | python | def write_to_file(data, path):
if path.endswith('.json'):
filename = path
else:
filename = path + '.json'
with codecs.open(filename, "w", encoding='utf-8') as json_file:
for line in data:
line['date'] = line['date'].strftime('%d/%m/%Y')
print(type(json))
... | Export extracted fields to json
Appends .json to path if missing and generates json file in specified directory, if not then in root
Parameters
----------
data : dict
Dictionary of extracted fields
path : str
directory to save generated json file
Notes
----
Do give fil... | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/output/to_json.py#L12-L47 | null | import json
import datetime
import codecs
def myconverter(o):
"""function to serialise datetime"""
if isinstance(o, datetime.datetime):
return o.__str__()
|
invoice-x/invoice2data | src/invoice2data/main.py | extract_data | python | def extract_data(invoicefile, templates=None, input_module=pdftotext):
if templates is None:
templates = read_templates()
# print(templates[0])
extracted_str = input_module.to_text(invoicefile).decode('utf-8')
logger.debug('START pdftotext result ===========================')
logger.debug(... | Extracts structured data from PDF/image invoices.
This function uses the text extracted from a PDF file or image and
pre-defined regex templates to find structured data.
Reads template if no template assigned
Required fields are matches from templates
Parameters
----------
invoicefile : s... | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/main.py#L36-L96 | [
"def to_text(path):\n \"\"\"Wrapper around Poppler pdftotext.\n\n Parameters\n ----------\n path : str\n path of electronic invoice in PDF\n\n Returns\n -------\n out : str\n returns extracted text from pdf\n\n Raises\n ------\n EnvironmentError:\n If pdftotext lib... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import shutil
import os
from os.path import join
import logging
from .input import pdftotext
from .input import pdfminer_wrapper
from .input import tesseract
from .input import tesseract4
from .input import gvision
from invoice2data.extract.loader import ... |
invoice-x/invoice2data | src/invoice2data/main.py | create_parser | python | def create_parser():
parser = argparse.ArgumentParser(
description='Extract structured data from PDF files and save to CSV or JSON.'
)
parser.add_argument(
'--input-reader',
choices=input_mapping.keys(),
default='pdftotext',
help='Choose text extraction function. De... | Returns argument parser | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/main.py#L99-L167 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import shutil
import os
from os.path import join
import logging
from .input import pdftotext
from .input import pdfminer_wrapper
from .input import tesseract
from .input import tesseract4
from .input import gvision
from invoice2data.extract.loader import ... |
invoice-x/invoice2data | src/invoice2data/main.py | main | python | def main(args=None):
if args is None:
parser = create_parser()
args = parser.parse_args()
if args.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
input_module = input_mapping[args.input_reader]
output_module = output_map... | Take folder or single file and analyze each. | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/main.py#L170-L215 | [
"def extract_data(invoicefile, templates=None, input_module=pdftotext):\n \"\"\"Extracts structured data from PDF/image invoices.\n\n This function uses the text extracted from a PDF file or image and\n pre-defined regex templates to find structured data.\n\n Reads template if no template assigned\n ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import shutil
import os
from os.path import join
import logging
from .input import pdftotext
from .input import pdfminer_wrapper
from .input import tesseract
from .input import tesseract4
from .input import gvision
from invoice2data.extract.loader import ... |
invoice-x/invoice2data | src/invoice2data/output/to_xml.py | write_to_file | python | def write_to_file(data, path):
if path.endswith('.xml'):
filename = path
else:
filename = path + '.xml'
tag_data = ET.Element('data')
xml_file = open(filename, "w")
i = 0
for line in data:
i += 1
tag_item = ET.SubElement(tag_data, 'item')
tag_date = ET.S... | Export extracted fields to xml
Appends .xml to path if missing and generates xml file in specified directory, if not then in root
Parameters
----------
data : dict
Dictionary of extracted fields
path : str
directory to save generated xml file
Notes
----
Do give file na... | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/output/to_xml.py#L12-L59 | [
"def prettify(elem):\n \"\"\"Return a pretty-printed XML string for the Element.\"\"\"\n rough_string = ET.tostring(elem, 'utf-8')\n reparsed = minidom.parseString(rough_string)\n return reparsed.toprettyxml(indent=\" \")\n"
] | import xml.etree.ElementTree as ET
from xml.dom import minidom
def prettify(elem):
"""Return a pretty-printed XML string for the Element."""
rough_string = ET.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
|
invoice-x/invoice2data | src/invoice2data/extract/loader.py | read_templates | python | def read_templates(folder=None):
output = []
if folder is None:
folder = pkg_resources.resource_filename(__name__, 'templates')
for path, subdirs, files in os.walk(folder):
for name in sorted(files):
if name.endswith('.yml'):
with open(os.path.join(path, name),... | Load yaml templates from template folder. Return list of dicts.
Use built-in templates if no folder is set.
Parameters
----------
folder : str
user defined folder where they stores their files, if None uses built-in templates
Returns
-------
output : Instance of `InvoiceTemplate`
... | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/loader.py#L39-L99 | [
"def ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):\n \"\"\"load mappings and ordered mappings\n\n loader to load mappings and ordered mappings into the Python 2.7+ OrderedDict type,\n instead of the vanilla dict and the list of pairs it currently uses.\n \"\"\"\n\n class Or... | """
This module abstracts templates for invoice providers.
Templates are initially read from .yml files and then kept as class.
"""
import os
import yaml
import pkg_resources
from collections import OrderedDict
import logging as logger
from .invoice_template import InvoiceTemplate
import codecs
import chardet
logger... |
invoice-x/invoice2data | src/invoice2data/input/pdfminer_wrapper.py | to_text | python | def to_text(path):
try:
# python 2
from StringIO import StringIO
import sys
reload(sys) # noqa: F821
sys.setdefaultencoding('utf8')
except ImportError:
from io import StringIO
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from p... | Wrapper around `pdfminer`.
Parameters
----------
path : str
path of electronic invoice in PDF
Returns
-------
str : str
returns extracted text from pdf | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/input/pdfminer_wrapper.py#L2-L57 | null | # -*- coding: utf-8 -*-
|
invoice-x/invoice2data | src/invoice2data/extract/plugins/lines.py | extract | python | def extract(self, content, output):
# First apply default options.
plugin_settings = DEFAULT_OPTIONS.copy()
plugin_settings.update(self['lines'])
self['lines'] = plugin_settings
# Validate settings
assert 'start' in self['lines'], 'Lines start regex missing'
assert 'end' in self['lines'], ... | Try to extract lines from the invoice | train | https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/plugins/lines.py#L13-L87 | null | """
Plugin to extract individual lines from an invoice.
Initial work and maintenance by Holger Brunn @hbrunn
"""
import re
import logging as logger
DEFAULT_OPTIONS = {'field_separator': r'\s+', 'line_separator': r'\n'}
|
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords._create_session | python | def _create_session(
self,
alias,
url,
headers,
cookies,
auth,
timeout,
max_retries,
backoff_factor,
proxies,
verify,
debug,
disable_warnings):
self.builti... | Create Session: create a HTTP session to a server
``url`` Base url of the server
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of default headers
``cookies`` Dictionary of cookies
``auth`` List of username & password for HTTP Basic Auth
... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L57-L155 | null | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.create_session | python | def create_session(self, alias, url, headers={}, cookies={},
auth=None, timeout=None, proxies=None,
verify=False, debug=0, max_retries=3, backoff_factor=0.10, disable_warnings=0):
auth = requests.auth.HTTPBasicAuth(*auth) if auth else None
logger.info('Crea... | Create Session: create a HTTP session to a server
``url`` Base url of the server
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of default headers
``cookies`` Dictionary of cookies
``auth`` List of username & password for HTTP Basic Auth
... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L157-L207 | [
"def _create_session(\n self,\n alias,\n url,\n headers,\n cookies,\n auth,\n timeout,\n max_retries,\n backoff_factor,\n proxies,\n verify,\n debug,\n disable_warnings):\n \"\"\" Create Session: create a HTTP session to a... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.create_ntlm_session | python | def create_ntlm_session(
self,
alias,
url,
auth,
headers={},
cookies={},
timeout=None,
proxies=None,
verify=False,
debug=0,
max_retries=3,
backoff_factor=0.10,
disa... | Create Session: create a HTTP session to a server
``url`` Base url of the server
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of default headers
``cookies`` Dictionary of cookies
``auth`` ['DOMAIN', 'username', 'password'] for NTLM Authentic... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L272-L340 | [
"def _create_session(\n self,\n alias,\n url,\n headers,\n cookies,\n auth,\n timeout,\n max_retries,\n backoff_factor,\n proxies,\n verify,\n debug,\n disable_warnings):\n \"\"\" Create Session: create a HTTP session to a... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.create_digest_session | python | def create_digest_session(self, alias, url, auth, headers={}, cookies={},
timeout=None, proxies=None, verify=False,
debug=0, max_retries=3,backoff_factor=0.10, disable_warnings=0):
digest_auth = requests.auth.HTTPDigestAuth(*auth) if auth else None
... | Create Session: create a HTTP session to a server
``url`` Base url of the server
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of default headers
``cookies`` Dictionary of cookies
``auth`` ['DOMAIN', 'username', 'password'] for NTLM Authentic... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L342-L387 | [
"def _create_session(\n self,\n alias,\n url,\n headers,\n cookies,\n auth,\n timeout,\n max_retries,\n backoff_factor,\n proxies,\n verify,\n debug,\n disable_warnings):\n \"\"\" Create Session: create a HTTP session to a... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.create_client_cert_session | python | def create_client_cert_session(self, alias, url, headers={}, cookies={},
client_certs=None, timeout=None, proxies=None,
verify=False, debug=0, max_retries=3, backoff_factor=0.10, disable_warnings=0):
logger.info('Creating Session using : alias=%s, url=%s, headers=%... | Create Session: create a HTTP session to a server
``url`` Base url of the server
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of default headers
``cookies`` Dictionary of cookies
``client_certs`` ['client certificate', 'client key'] PEM file... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L389-L441 | [
"def _create_session(\n self,\n alias,\n url,\n headers,\n cookies,\n auth,\n timeout,\n max_retries,\n backoff_factor,\n proxies,\n verify,\n debug,\n disable_warnings):\n \"\"\" Create Session: create a HTTP session to a... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.update_session | python | def update_session(self, alias, headers=None, cookies=None):
session = self._cache.switch(alias)
session.headers = merge_setting(headers, session.headers)
session.cookies = merge_cookies(session.cookies, cookies) | Update Session Headers: update a HTTP Session Headers
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of headers merge into session | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L449-L458 | null | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.to_json | python | def to_json(self, content, pretty_print=False):
if PY3:
if isinstance(content, bytes):
content = content.decode(encoding='utf-8')
if pretty_print:
json_ = self._json_pretty_print(content)
else:
json_ = json.loads(content)
logger.info('T... | Convert a string to a JSON object
``content`` String content to convert into JSON
``pretty_print`` If defined, will output JSON is pretty print format | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L460-L477 | [
"def _json_pretty_print(self, content):\n \"\"\"\n Pretty print a JSON object\n\n ``content`` JSON object to pretty print\n \"\"\"\n temp = json.loads(content)\n return json.dumps(\n temp,\n sort_keys=True,\n indent=4,\n separators=(\n ',',\n ': '... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.get_request | python | def get_request(
self,
alias,
uri,
headers=None,
json=None,
params=None,
allow_redirects=None,
timeout=None):
session = self._cache.switch(alias)
redir = True if allow_redirects is None else allow_redirects
... | Send a GET request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the GET request to
``params`` url parameters to append to the uri
``headers`` a dictionary of headers to use with the... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L479-L515 | [
"def _get_request(\n self,\n session,\n uri,\n params,\n headers,\n json,\n allow_redirects,\n timeout):\n self._capture_output()\n\n resp = session.get(self._get_url(session, uri),\n headers=headers,\n json=js... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.post_request | python | def post_request(
self,
alias,
uri,
data=None,
json=None,
params=None,
headers=None,
files=None,
allow_redirects=None,
timeout=None):
session = self._cache.switch(alias)
if not files:
... | Send a POST request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the POST request to
``data`` a dictionary of key-value pairs that will be urlencoded
and sent as POST data
... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L550-L607 | [
"def _body_request(\n self,\n method_name,\n session,\n uri,\n data,\n json,\n params,\n files,\n headers,\n allow_redirects,\n timeout):\n self._capture_output()\n\n method = getattr(session, method_name)\n resp = method(self._ge... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.put | python | def put(
self,
alias,
uri,
data=None,
headers=None,
allow_redirects=None,
timeout=None):
logger.warn("Deprecation Warning: Use Put Request in the future")
session = self._cache.switch(alias)
data = self._utf8_url... | **Deprecated- See Put Request now**
Send a PUT request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the PUT request to
``headers`` a dictionary of headers to use with the request
... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L822-L862 | [
"def _body_request(\n self,\n method_name,\n session,\n uri,\n data,\n json,\n params,\n files,\n headers,\n allow_redirects,\n timeout):\n self._capture_output()\n\n method = getattr(session, method_name)\n resp = method(self._ge... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.delete_request | python | def delete_request(
self,
alias,
uri,
data=None,
json=None,
params=None,
headers=None,
allow_redirects=None,
timeout=None):
session = self._cache.switch(alias)
data = self._format_data_according_t... | Send a DELETE request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the DELETE request to
``json`` a value that will be json encoded
and sent as request data if data is not spe... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L864-L902 | [
"def _delete_request(\n self,\n session,\n uri,\n data,\n json,\n params,\n headers,\n allow_redirects,\n timeout):\n self._capture_output()\n\n resp = session.delete(self._get_url(session, uri),\n data=data,\n ... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.delete | python | def delete(
self,
alias,
uri,
data=(),
headers=None,
allow_redirects=None,
timeout=None):
logger.warn("Deprecation Warning: Use Delete Request in the future")
session = self._cache.switch(alias)
data = self._utf8... | * * * Deprecated- See Delete Request now * * *
Send a DELETE request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the DELETE request to
``headers`` a dictionary of headers to us... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L904-L935 | [
"def _delete_request(\n self,\n session,\n uri,\n data,\n json,\n params,\n headers,\n allow_redirects,\n timeout):\n self._capture_output()\n\n resp = session.delete(self._get_url(session, uri),\n data=data,\n ... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.head_request | python | def head_request(
self,
alias,
uri,
headers=None,
allow_redirects=None,
timeout=None):
session = self._cache.switch(alias)
redir = False if allow_redirects is None else allow_redirects
response = self._head_request(session, ... | Send a HEAD request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the HEAD request to
``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
``hea... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L937-L961 | [
"def _head_request(self, session, uri, headers, allow_redirects, timeout):\n self._capture_output()\n\n resp = session.head(self._get_url(session, uri),\n headers=headers,\n allow_redirects=allow_redirects,\n timeout=self._get_timeout(timeou... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.head | python | def head(
self,
alias,
uri,
headers=None,
allow_redirects=None,
timeout=None):
logger.warn("Deprecation Warning: Use Head Request in the future")
session = self._cache.switch(alias)
redir = False if allow_redirects is None e... | **Deprecated- See Head Request now**
Send a HEAD request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the HEAD request to
``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L963-L988 | [
"def _head_request(self, session, uri, headers, allow_redirects, timeout):\n self._capture_output()\n\n resp = session.head(self._get_url(session, uri),\n headers=headers,\n allow_redirects=allow_redirects,\n timeout=self._get_timeout(timeou... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.options_request | python | def options_request(
self,
alias,
uri,
headers=None,
allow_redirects=None,
timeout=None):
session = self._cache.switch(alias)
redir = True if allow_redirects is None else allow_redirects
response = self._options_request(sess... | Send an OPTIONS request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the OPTIONS request to
``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L990-L1015 | [
"def _options_request(\n self,\n session,\n uri,\n headers,\n allow_redirects,\n timeout):\n self._capture_output()\n\n resp = session.options(self._get_url(session, uri),\n headers=headers,\n cookies=self.cookies,\n... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.options | python | def options(
self,
alias,
uri,
headers=None,
allow_redirects=None,
timeout=None):
logger.warn("Deprecation Warning: Use Options Request in the future")
session = self._cache.switch(alias)
redir = True if allow_redirects is N... | **Deprecated- See Options Request now**
Send an OPTIONS request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the OPTIONS request to
``allow_redirects`` Boolean. Set to True if POST/... | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L1017-L1042 | [
"def _options_request(\n self,\n session,\n uri,\n headers,\n allow_redirects,\n timeout):\n self._capture_output()\n\n resp = session.options(self._get_url(session, uri),\n headers=headers,\n cookies=self.cookies,\n... | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords._get_url | python | def _get_url(self, session, uri):
url = session.url
if uri:
slash = '' if uri.startswith('/') else '/'
url = "%s%s%s" % (session.url, slash, uri)
return url | Helper method to get the full url | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L1174-L1182 | null | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords._json_pretty_print | python | def _json_pretty_print(self, content):
temp = json.loads(content)
return json.dumps(
temp,
sort_keys=True,
indent=4,
separators=(
',',
': ')) | Pretty print a JSON object
``content`` JSON object to pretty print | train | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L1215-L1228 | null | class RequestsKeywords(object):
"""``RequestsLibrary`` is a [http://code.google.com/p/robotframework/|Robot Framework] test library that uses the [https://github.com/kennethreitz/requests|Requests] HTTP client.
Here is an example testcase
| ***** Settings ***** | | ... |
utiasSTARS/pykitti | pykitti/tracking.py | to_array_list | python | def to_array_list(df, length=None, by_id=True):
if by_id:
assert 'id' in df.columns
# if `id` is the only column, don't sort it (and don't remove it)
if len(df.columns) == 1:
by_id = False
idx = df.index.unique()
if length is None:
length = max(idx) + 1
l ... | Converts a dataframe to a list of arrays, with one array for every unique index entry.
Index is assumed to be 0-based contiguous. If there is a missing index entry, an empty
numpy array is returned for it.
Elements in the arrays are sorted by their id.
:param df:
:param length:
:return: | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/tracking.py#L181-L212 | null | """Provides 'tracking', which loads and parses tracking benchmark data."""
import datetime as dt
import glob
import os
from collections import namedtuple
import pandas as pd
import numpy as np
import pykitti.utils as utils
import cv2
try:
xrange
except NameError:
xrange = range
__author__ = "Sidney zhang"
... |
utiasSTARS/pykitti | pykitti/tracking.py | KittiTrackingLabels.bbox | python | def bbox(self):
bbox = self._df[['id', 'x1', 'y1', 'x2', 'y2']].copy()
# TODO: Fix this to become x, y, w, h
if self.bbox_with_size:
bbox['y2'] -= bbox['y1']
bbox['x2'] -= bbox['x1']
return to_array_list(bbox) | Converts a dataframe to a list of arrays
:param df:
:param length:
:return: | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/tracking.py#L291-L304 | [
"def to_array_list(df, length=None, by_id=True):\n \"\"\"Converts a dataframe to a list of arrays, with one array for every unique index entry.\n Index is assumed to be 0-based contiguous. If there is a missing index entry, an empty\n numpy array is returned for it.\n Elements in the arrays are sorted b... | class KittiTrackingLabels(object):
"""Kitt Tracking Label parser. It can limit the maximum number of objects per track,
filter out objects with class "DontCare", or retain only those objects present
in a given frame.
"""
columns = 'id class truncated occluded alpha x1 y1 x2 y2 xd yd zd x y z roty s... |
utiasSTARS/pykitti | pykitti/tracking.py | KittiTrackingLabels._split_on_reappear | python | def _split_on_reappear(cls, df, p, id_offset):
next_id = id_offset + 1
added_ids = []
nt = p.sum(0)
start = np.argmax(p, 0)
end = np.argmax(np.cumsum(p, 0), 0)
diff = end - start + 1
is_contiguous = np.equal(nt, diff)
for id, contiguous in enumerate(is_co... | Assign a new identity to an objects that appears after disappearing previously.
Works on `df` in-place.
:param df: data frame
:param p: presence
:param id_offset: offset added to new ids
:return: | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/tracking.py#L342-L372 | null | class KittiTrackingLabels(object):
"""Kitt Tracking Label parser. It can limit the maximum number of objects per track,
filter out objects with class "DontCare", or retain only those objects present
in a given frame.
"""
columns = 'id class truncated occluded alpha x1 y1 x2 y2 xd yd zd x y z roty s... |
utiasSTARS/pykitti | pykitti/odometry.py | odometry._get_file_lists | python | def _get_file_lists(self):
self.cam0_files = sorted(glob.glob(
os.path.join(self.sequence_path, 'image_0',
'*.{}'.format(self.imtype))))
self.cam1_files = sorted(glob.glob(
os.path.join(self.sequence_path, 'image_1',
'*.{}'.format... | Find and list data files for each sensor. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/odometry.py#L114-L143 | [
"def subselect_files(files, indices):\n try:\n files = [files[i] for i in indices]\n except:\n pass\n return files\n"
] | class odometry:
"""Load and parse odometry benchmark data into a usable format."""
def __init__(self, base_path, sequence, **kwargs):
"""Set the path."""
self.sequence = sequence
self.sequence_path = os.path.join(base_path, 'sequences', sequence)
self.pose_path = os.path.join(ba... |
utiasSTARS/pykitti | pykitti/odometry.py | odometry._load_calib | python | def _load_calib(self):
# We'll build the calibration parameters as a dictionary, then
# convert it to a namedtuple to prevent it from being modified later
data = {}
# Load the calibration file
calib_filepath = os.path.join(self.sequence_path, 'calib.txt')
filedata = util... | Load and compute intrinsic and extrinsic calibration parameters. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/odometry.py#L145-L199 | [
"def read_calib_file(filepath):\n \"\"\"Read in a calibration file and parse into a dictionary.\"\"\"\n data = {}\n\n with open(filepath, 'r') as f:\n for line in f.readlines():\n key, value = line.split(':', 1)\n # The only non-float values in these files are dates, which\n ... | class odometry:
"""Load and parse odometry benchmark data into a usable format."""
def __init__(self, base_path, sequence, **kwargs):
"""Set the path."""
self.sequence = sequence
self.sequence_path = os.path.join(base_path, 'sequences', sequence)
self.pose_path = os.path.join(ba... |
utiasSTARS/pykitti | pykitti/odometry.py | odometry._load_timestamps | python | def _load_timestamps(self):
timestamp_file = os.path.join(self.sequence_path, 'times.txt')
# Read and parse the timestamps
self.timestamps = []
with open(timestamp_file, 'r') as f:
for line in f.readlines():
t = dt.timedelta(seconds=float(line))
... | Load timestamps from file. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/odometry.py#L201-L214 | null | class odometry:
"""Load and parse odometry benchmark data into a usable format."""
def __init__(self, base_path, sequence, **kwargs):
"""Set the path."""
self.sequence = sequence
self.sequence_path = os.path.join(base_path, 'sequences', sequence)
self.pose_path = os.path.join(ba... |
utiasSTARS/pykitti | pykitti/odometry.py | odometry._load_poses | python | def _load_poses(self):
pose_file = os.path.join(self.pose_path, self.sequence + '.txt')
# Read and parse the poses
poses = []
try:
with open(pose_file, 'r') as f:
lines = f.readlines()
if self.frames is not None:
lines = [l... | Load ground truth poses (T_w_cam0) from file. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/odometry.py#L216-L238 | null | class odometry:
"""Load and parse odometry benchmark data into a usable format."""
def __init__(self, base_path, sequence, **kwargs):
"""Set the path."""
self.sequence = sequence
self.sequence_path = os.path.join(base_path, 'sequences', sequence)
self.pose_path = os.path.join(ba... |
utiasSTARS/pykitti | pykitti/utils.py | rotx | python | def rotx(t):
c = np.cos(t)
s = np.sin(t)
return np.array([[1, 0, 0],
[0, c, -s],
[0, s, c]]) | Rotation about the x-axis. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/utils.py#L34-L40 | null | """Provides helper methods for loading and parsing KITTI data."""
from collections import namedtuple
import numpy as np
from PIL import Image
__author__ = "Lee Clement"
__email__ = "lee.clement@robotics.utias.utoronto.ca"
# Per dataformat.txt
OxtsPacket = namedtuple('OxtsPacket',
'lat, lon, ... |
utiasSTARS/pykitti | pykitti/utils.py | roty | python | def roty(t):
c = np.cos(t)
s = np.sin(t)
return np.array([[c, 0, s],
[0, 1, 0],
[-s, 0, c]]) | Rotation about the y-axis. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/utils.py#L43-L49 | null | """Provides helper methods for loading and parsing KITTI data."""
from collections import namedtuple
import numpy as np
from PIL import Image
__author__ = "Lee Clement"
__email__ = "lee.clement@robotics.utias.utoronto.ca"
# Per dataformat.txt
OxtsPacket = namedtuple('OxtsPacket',
'lat, lon, ... |
utiasSTARS/pykitti | pykitti/utils.py | rotz | python | def rotz(t):
c = np.cos(t)
s = np.sin(t)
return np.array([[c, -s, 0],
[s, c, 0],
[0, 0, 1]]) | Rotation about the z-axis. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/utils.py#L52-L58 | null | """Provides helper methods for loading and parsing KITTI data."""
from collections import namedtuple
import numpy as np
from PIL import Image
__author__ = "Lee Clement"
__email__ = "lee.clement@robotics.utias.utoronto.ca"
# Per dataformat.txt
OxtsPacket = namedtuple('OxtsPacket',
'lat, lon, ... |
utiasSTARS/pykitti | pykitti/utils.py | transform_from_rot_trans | python | def transform_from_rot_trans(R, t):
R = R.reshape(3, 3)
t = t.reshape(3, 1)
return np.vstack((np.hstack([R, t]), [0, 0, 0, 1])) | Transforation matrix from rotation matrix and translation vector. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/utils.py#L61-L65 | null | """Provides helper methods for loading and parsing KITTI data."""
from collections import namedtuple
import numpy as np
from PIL import Image
__author__ = "Lee Clement"
__email__ = "lee.clement@robotics.utias.utoronto.ca"
# Per dataformat.txt
OxtsPacket = namedtuple('OxtsPacket',
'lat, lon, ... |
utiasSTARS/pykitti | pykitti/utils.py | read_calib_file | python | def read_calib_file(filepath):
data = {}
with open(filepath, 'r') as f:
for line in f.readlines():
key, value = line.split(':', 1)
# The only non-float values in these files are dates, which
# we don't care about anyway
try:
data[key] = np... | Read in a calibration file and parse into a dictionary. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/utils.py#L68-L82 | null | """Provides helper methods for loading and parsing KITTI data."""
from collections import namedtuple
import numpy as np
from PIL import Image
__author__ = "Lee Clement"
__email__ = "lee.clement@robotics.utias.utoronto.ca"
# Per dataformat.txt
OxtsPacket = namedtuple('OxtsPacket',
'lat, lon, ... |
utiasSTARS/pykitti | pykitti/utils.py | pose_from_oxts_packet | python | def pose_from_oxts_packet(packet, scale):
er = 6378137. # earth radius (approx.) in meters
# Use a Mercator projection to get the translation vector
tx = scale * packet.lon * np.pi * er / 180.
ty = scale * er * \
np.log(np.tan((90. + packet.lat) * np.pi / 360.))
tz = packet.alt
t = np.... | Helper method to compute a SE(3) pose matrix from an OXTS packet. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/utils.py#L85-L104 | [
"def rotx(t):\n \"\"\"Rotation about the x-axis.\"\"\"\n c = np.cos(t)\n s = np.sin(t)\n return np.array([[1, 0, 0],\n [0, c, -s],\n [0, s, c]])\n",
"def roty(t):\n \"\"\"Rotation about the y-axis.\"\"\"\n c = np.cos(t)\n s = np.sin(t)\n return ... | """Provides helper methods for loading and parsing KITTI data."""
from collections import namedtuple
import numpy as np
from PIL import Image
__author__ = "Lee Clement"
__email__ = "lee.clement@robotics.utias.utoronto.ca"
# Per dataformat.txt
OxtsPacket = namedtuple('OxtsPacket',
'lat, lon, ... |
utiasSTARS/pykitti | pykitti/utils.py | load_oxts_packets_and_poses | python | def load_oxts_packets_and_poses(oxts_files):
# Scale for Mercator projection (from first lat value)
scale = None
# Origin of the global coordinate system (first GPS position)
origin = None
oxts = []
for filename in oxts_files:
with open(filename, 'r') as f:
for line in f.re... | Generator to read OXTS ground truth data.
Poses are given in an East-North-Up coordinate system
whose origin is the first GPS position. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/utils.py#L107-L142 | [
"def transform_from_rot_trans(R, t):\n \"\"\"Transforation matrix from rotation matrix and translation vector.\"\"\"\n R = R.reshape(3, 3)\n t = t.reshape(3, 1)\n return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))\n",
"def pose_from_oxts_packet(packet, scale):\n \"\"\"Helper method to compute a SE... | """Provides helper methods for loading and parsing KITTI data."""
from collections import namedtuple
import numpy as np
from PIL import Image
__author__ = "Lee Clement"
__email__ = "lee.clement@robotics.utias.utoronto.ca"
# Per dataformat.txt
OxtsPacket = namedtuple('OxtsPacket',
'lat, lon, ... |
utiasSTARS/pykitti | pykitti/utils.py | load_velo_scan | python | def load_velo_scan(file):
scan = np.fromfile(file, dtype=np.float32)
return scan.reshape((-1, 4)) | Load and parse a velodyne binary file. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/utils.py#L156-L159 | null | """Provides helper methods for loading and parsing KITTI data."""
from collections import namedtuple
import numpy as np
from PIL import Image
__author__ = "Lee Clement"
__email__ = "lee.clement@robotics.utias.utoronto.ca"
# Per dataformat.txt
OxtsPacket = namedtuple('OxtsPacket',
'lat, lon, ... |
utiasSTARS/pykitti | pykitti/raw.py | raw._load_calib_rigid | python | def _load_calib_rigid(self, filename):
filepath = os.path.join(self.calib_path, filename)
data = utils.read_calib_file(filepath)
return utils.transform_from_rot_trans(data['R'], data['T']) | Read a rigid transform calibration file as a numpy.array. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/raw.py#L144-L148 | null | class raw:
"""Load and parse raw data into a usable format."""
def __init__(self, base_path, date, drive, **kwargs):
"""Set the path and pre-load calibration data and timestamps."""
self.dataset = kwargs.get('dataset', 'sync')
self.drive = date + '_drive_' + drive + '_' + self.dataset
... |
utiasSTARS/pykitti | pykitti/raw.py | raw._load_calib | python | def _load_calib(self):
# We'll build the calibration parameters as a dictionary, then
# convert it to a namedtuple to prevent it from being modified later
data = {}
# Load the rigid transformation from IMU to velodyne
data['T_velo_imu'] = self._load_calib_rigid('calib_imu_to_vel... | Load and compute intrinsic and extrinsic calibration parameters. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/raw.py#L225-L244 | [
"def _load_calib_rigid(self, filename):\n \"\"\"Read a rigid transform calibration file as a numpy.array.\"\"\"\n filepath = os.path.join(self.calib_path, filename)\n data = utils.read_calib_file(filepath)\n return utils.transform_from_rot_trans(data['R'], data['T'])\n",
"def _load_calib_cam_to_cam(se... | class raw:
"""Load and parse raw data into a usable format."""
def __init__(self, base_path, date, drive, **kwargs):
"""Set the path and pre-load calibration data and timestamps."""
self.dataset = kwargs.get('dataset', 'sync')
self.drive = date + '_drive_' + drive + '_' + self.dataset
... |
utiasSTARS/pykitti | pykitti/raw.py | raw._load_timestamps | python | def _load_timestamps(self):
timestamp_file = os.path.join(
self.data_path, 'oxts', 'timestamps.txt')
# Read and parse the timestamps
self.timestamps = []
with open(timestamp_file, 'r') as f:
for line in f.readlines():
# NB: datetime only supports ... | Load timestamps from file. | train | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/raw.py#L246-L263 | null | class raw:
"""Load and parse raw data into a usable format."""
def __init__(self, base_path, date, drive, **kwargs):
"""Set the path and pre-load calibration data and timestamps."""
self.dataset = kwargs.get('dataset', 'sync')
self.drive = date + '_drive_' + drive + '_' + self.dataset
... |
C4ptainCrunch/ics.py | ics/utils.py | arrow_get | python | def arrow_get(string):
'''this function exists because ICS uses ISO 8601 without dashes or
colons, i.e. not ISO 8601 at all.'''
# replace slashes with dashes
if '/' in string:
string = string.replace('/', '-')
# if string contains dashes, assume it to be proper ISO 8601
if '-' in strin... | this function exists because ICS uses ISO 8601 without dashes or
colons, i.e. not ISO 8601 at all. | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/utils.py#L35-L48 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from arrow.arrow import Arrow
from datetime import timedelta
from six import StringIO, string_types, text_type, integer_types
from uuid import uuid4
from dateutil.tz import gettz
import arrow
import re
from . impo... |
C4ptainCrunch/ics.py | ics/utils.py | parse_duration | python | def parse_duration(line):
DAYS, SECS = {'D': 1, 'W': 7}, {'S': 1, 'M': 60, 'H': 3600}
sign, i = 1, 0
if line[i] in '-+':
if line[i] == '-':
sign = -1
i += 1
if line[i] != 'P':
raise parse.ParseError()
i += 1
days, secs = 0, 0
while i < len(line):
i... | Return a timedelta object from a string in the DURATION property format | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/utils.py#L109-L143 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from arrow.arrow import Arrow
from datetime import timedelta
from six import StringIO, string_types, text_type, integer_types
from uuid import uuid4
from dateutil.tz import gettz
import arrow
import re
from . impo... |
C4ptainCrunch/ics.py | ics/utils.py | timedelta_to_duration | python | def timedelta_to_duration(dt):
days, secs = dt.days, dt.seconds
res = 'P'
if days // 7:
res += str(days // 7) + 'W'
days %= 7
if days:
res += str(days) + 'D'
if secs:
res += 'T'
if secs // 3600:
res += str(secs // 3600) + 'H'
secs %= 36... | Return a string according to the DURATION property format
from a timedelta object | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/utils.py#L146-L168 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from arrow.arrow import Arrow
from datetime import timedelta
from six import StringIO, string_types, text_type, integer_types
from uuid import uuid4
from dateutil.tz import gettz
import arrow
import re
from . impo... |
C4ptainCrunch/ics.py | ics/alarm.py | Alarm.clone | python | def clone(self):
clone = copy.copy(self)
clone._unused = clone._unused.clone()
return clone | Returns:
Alarm: an exact copy of self | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/alarm.py#L171-L177 | null | class Alarm(Component):
"""
A calendar event VALARM base class
"""
_TYPE = 'VALARM'
_EXTRACTORS = []
_OUTPUTS = []
def __init__(self,
trigger=None,
repeat=None,
duration=None):
"""
Instantiates a new :class:`ics.alarm.Alarm... |
C4ptainCrunch/ics.py | ics/timeline.py | Timeline.included | python | def included(self, start, stop):
for event in self:
if (start <= event.begin <= stop # if start is between the bonds
and start <= event.end <= stop): # and stop is between the bonds
yield event | Iterates (in chronological order) over every event that is included
in the timespan between `start` and `stop`
Args:
start : (Arrow object)
stop : (Arrow object) | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/timeline.py#L42-L53 | null | class Timeline(object):
def __init__(self, calendar):
"""Instanciates a new Timeline.
(You should not have to instanciate a new timeline by yourself)
Args:
calendar : :class:`ics.icalendar.Calendar`
"""
self._calendar = calendar
def __iter__(self):
... |
C4ptainCrunch/ics.py | ics/timeline.py | Timeline.overlapping | python | def overlapping(self, start, stop):
for event in self:
if ((start <= event.begin <= stop # if start is between the bonds
or start <= event.end <= stop) # or stop is between the bonds
or event.begin <= start and event.end >= stop): # or event is a superset of [start,stop]
... | Iterates (in chronological order) over every event that has an intersection
with the timespan between `start` and `stop`
Args:
start : (Arrow object)
stop : (Arrow object) | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/timeline.py#L55-L67 | null | class Timeline(object):
def __init__(self, calendar):
"""Instanciates a new Timeline.
(You should not have to instanciate a new timeline by yourself)
Args:
calendar : :class:`ics.icalendar.Calendar`
"""
self._calendar = calendar
def __iter__(self):
... |
C4ptainCrunch/ics.py | ics/timeline.py | Timeline.at | python | def at(self, instant):
for event in self:
if event.begin <= instant <= event.end:
yield event | Iterates (in chronological order) over all events that are occuring during `instant`.
Args:
instant (Arrow object) | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/timeline.py#L80-L89 | null | class Timeline(object):
def __init__(self, calendar):
"""Instanciates a new Timeline.
(You should not have to instanciate a new timeline by yourself)
Args:
calendar : :class:`ics.icalendar.Calendar`
"""
self._calendar = calendar
def __iter__(self):
... |
C4ptainCrunch/ics.py | ics/timeline.py | Timeline.on | python | def on(self, day, strict=False):
day_start, day_stop = day.floor('day').span('day')
if strict:
return self.included(day_start, day_stop)
else:
return self.overlapping(day_start, day_stop) | Iterates (in chronological order) over all events that occurs on `day`
Args:
day (Arrow object)
strict (bool): if True events will be returned only if they are\
strictly *included* in `day`. | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/timeline.py#L91-L103 | [
"def included(self, start, stop):\n \"\"\"Iterates (in chronological order) over every event that is included\n in the timespan between `start` and `stop`\n\n Args:\n start : (Arrow object)\n stop : (Arrow object)\n \"\"\"\n for event in self:\n if (start <= event.begin <= stop #... | class Timeline(object):
def __init__(self, calendar):
"""Instanciates a new Timeline.
(You should not have to instanciate a new timeline by yourself)
Args:
calendar : :class:`ics.icalendar.Calendar`
"""
self._calendar = calendar
def __iter__(self):
... |
C4ptainCrunch/ics.py | ics/timeline.py | Timeline.today | python | def today(self, strict=False):
return self.on(arrow.now(), strict=strict) | Iterates (in chronological order) over all events that occurs today
Args:
strict (bool): if True events will be returned only if they are\
strictly *included* in `day`. | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/timeline.py#L105-L112 | [
"def on(self, day, strict=False):\n \"\"\"Iterates (in chronological order) over all events that occurs on `day`\n\n Args:\n day (Arrow object)\n strict (bool): if True events will be returned only if they are\\\n strictly *included* in `day`.\n \"\"\"\n day_start, day_stop = day.fl... | class Timeline(object):
def __init__(self, calendar):
"""Instanciates a new Timeline.
(You should not have to instanciate a new timeline by yourself)
Args:
calendar : :class:`ics.icalendar.Calendar`
"""
self._calendar = calendar
def __iter__(self):
... |
C4ptainCrunch/ics.py | ics/event.py | Event.end | python | def end(self):
if self._duration: # if end is duration defined
# return the beginning + duration
return self.begin + self._duration
elif self._end_time: # if end is time defined
if self.all_day:
return self._end_time
else:
... | Get or set the end of the event.
| Will return an :class:`Arrow` object.
| May be set to anything that :func:`Arrow.get` understands.
| If set to a non null value, removes any already
existing duration.
| Setting to None will have unexpected behavior if
begin... | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/event.py#L139-L166 | [
"def get_arrow(value):\n if value is None:\n return None\n elif isinstance(value, Arrow):\n return value\n elif isinstance(value, tuple):\n return arrow.get(*value)\n elif isinstance(value, dict):\n return arrow.get(**value)\n else:\n return arrow.get(value)\n"
] | class Event(Component):
"""A calendar event.
Can be full-day or between two instants.
Can be defined by a beginning instant and
a duration *or* end instant.
"""
_TYPE = "VEVENT"
_EXTRACTORS = []
_OUTPUTS = []
def __init__(self,
name=None,
begin=N... |
C4ptainCrunch/ics.py | ics/event.py | Event.duration | python | def duration(self):
if self._duration:
return self._duration
elif self.end:
# because of the clever getter for end, this also takes care of all_day events
return self.end - self.begin
else:
# event has neither start, nor end, nor duration
... | Get or set the duration of the event.
| Will return a timedelta object.
| May be set to anything that timedelta() understands.
| May be set with a dict ({"days":2, "hours":6}).
| If set to a non null value, removes any already
existing end time. | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/event.py#L179-L195 | null | class Event(Component):
"""A calendar event.
Can be full-day or between two instants.
Can be defined by a beginning instant and
a duration *or* end instant.
"""
_TYPE = "VEVENT"
_EXTRACTORS = []
_OUTPUTS = []
def __init__(self,
name=None,
begin=N... |
C4ptainCrunch/ics.py | ics/event.py | Event.make_all_day | python | def make_all_day(self):
if self.all_day:
# Do nothing if we already are a all day event
return
begin_day = self.begin.floor('day')
end_day = self.end.floor('day')
self._begin = begin_day
# for a one day event, we don't need a _end_time
if begin_... | Transforms self to an all-day event.
The event will span all the days from the begin to the end day. | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/event.py#L220-L241 | null | class Event(Component):
"""A calendar event.
Can be full-day or between two instants.
Can be defined by a beginning instant and
a duration *or* end instant.
"""
_TYPE = "VEVENT"
_EXTRACTORS = []
_OUTPUTS = []
def __init__(self,
name=None,
begin=N... |
C4ptainCrunch/ics.py | ics/event.py | Event.join | python | def join(self, other, *args, **kwarg):
event = Event(*args, **kwarg)
if self.intersects(other):
if self.starts_within(other):
event.begin = other.begin
else:
event.begin = self.begin
if self.ends_within(other):
event.en... | Create a new event which covers the time range of two intersecting events
All extra parameters are passed to the Event constructor.
Args:
other: the other event
Returns:
a new Event instance | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/event.py#L387-L411 | [
"def intersects(self, other):\n if not isinstance(other, Event):\n raise NotImplementedError(\n 'Cannot compare Event and {}'.format(type(other)))\n return (self.starts_within(other)\n or self.ends_within(other)\n or other.starts_within(self)\n or other.ends_... | class Event(Component):
"""A calendar event.
Can be full-day or between two instants.
Can be defined by a beginning instant and
a duration *or* end instant.
"""
_TYPE = "VEVENT"
_EXTRACTORS = []
_OUTPUTS = []
def __init__(self,
name=None,
begin=N... |
C4ptainCrunch/ics.py | ics/icalendar.py | timezone | python | def timezone(calendar, vtimezones):
for vtimezone in vtimezones:
remove_x(vtimezone) # Remove non standard lines from the block
fake_file = StringIO()
fake_file.write(str(vtimezone)) # Represent the block as a string
fake_file.seek(0)
timezones = tzical(fake_file) # tzical... | Receives a list of VTIMEZONE blocks.
Parses them and adds them to calendar._timezones. | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/icalendar.py#L184-L197 | [
"def remove_x(container):\n for i in reversed(range(len(container))):\n item = container[i]\n if item.name.startswith('X-'):\n del container[i]\n"
] | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from six import StringIO, string_types, text_type, integer_types
from dateutil.tz import tzical
import copy
import collections
from .component import Component
from .timeline import Timeline
from .event import Eve... |
C4ptainCrunch/ics.py | ics/icalendar.py | Calendar.clone | python | def clone(self):
clone = copy.copy(self)
clone._unused = clone._unused.clone()
clone.events = copy.copy(self.events)
clone.todos = copy.copy(self.todos)
clone._timezones = copy.copy(self._timezones)
return clone | Returns:
Calendar: an exact deep copy of self | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/icalendar.py#L126-L136 | null | class Calendar(Component):
"""Represents an unique rfc5545 iCalendar."""
_TYPE = 'VCALENDAR'
_EXTRACTORS = []
_OUTPUTS = []
def __init__(self, imports=None, events=None, todos=None, creator=None):
"""Instantiates a new Calendar.
Args:
imports (string or list of lines/... |
C4ptainCrunch/ics.py | ics/todo.py | Todo.due | python | def due(self):
if self._duration:
# if due is duration defined return the beginning + duration
return self.begin + self._duration
elif self._due_time:
# if due is time defined
return self._due_time
else:
return None | Get or set the end of the todo.
| Will return an :class:`Arrow` object.
| May be set to anything that :func:`Arrow.get` understands.
| If set to a non null value, removes any already
existing duration.
| Setting to None will have unexpected behavior if
begin ... | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/todo.py#L158-L177 | [
"def get_arrow(value):\n if value is None:\n return None\n elif isinstance(value, Arrow):\n return value\n elif isinstance(value, tuple):\n return arrow.get(*value)\n elif isinstance(value, dict):\n return arrow.get(**value)\n else:\n return arrow.get(value)\n"
] | class Todo(Component):
"""A todo list entry.
Can have a start time and duration, or start and due time,
or only start/due time.
"""
_TYPE = "VTODO"
_EXTRACTORS = []
_OUTPUTS = []
def __init__(self,
dtstamp=None,
uid=None,
completed=N... |
C4ptainCrunch/ics.py | ics/todo.py | Todo.duration | python | def duration(self):
if self._duration:
return self._duration
elif self.due:
return self.due - self.begin
else:
# todo has neither due, nor start and duration
return None | Get or set the duration of the todo.
| Will return a timedelta object.
| May be set to anything that timedelta() understands.
| May be set with a dict ({"days":2, "hours":6}).
| If set to a non null value, removes any already
existing end time. | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/todo.py#L191-L206 | null | class Todo(Component):
"""A todo list entry.
Can have a start time and duration, or start and due time,
or only start/due time.
"""
_TYPE = "VTODO"
_EXTRACTORS = []
_OUTPUTS = []
def __init__(self,
dtstamp=None,
uid=None,
completed=N... |
C4ptainCrunch/ics.py | ics/todo.py | Todo.clone | python | def clone(self):
clone = copy.copy(self)
clone._unused = clone._unused.clone()
clone.alarms = copy.copy(self.alarms)
return clone | Returns:
Todo: an exact copy of self | train | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/todo.py#L332-L339 | null | class Todo(Component):
"""A todo list entry.
Can have a start time and duration, or start and due time,
or only start/due time.
"""
_TYPE = "VTODO"
_EXTRACTORS = []
_OUTPUTS = []
def __init__(self,
dtstamp=None,
uid=None,
completed=N... |
moble/quaternion | quaternion_time_series.py | slerp | python | def slerp(R1, R2, t1, t2, t_out):
tau = (t_out-t1)/(t2-t1)
return np.slerp_vectorized(R1, R2, tau) | Spherical linear interpolation of rotors
This function uses a simpler interface than the more fundamental
`slerp_evaluate` and `slerp_vectorized` functions. The latter
are fast, being implemented at the C level, but take input `tau`
instead of time. This function adjusts the time accordingly.
Pa... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/quaternion_time_series.py#L11-L35 | null | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import print_function, division, absolute_import
import numpy as np
import quaternion
from quaternion.numba_wrapper import njit
def squad(R_in, t_in, t_out):
"""Spherica... |
moble/quaternion | quaternion_time_series.py | squad | python | def squad(R_in, t_in, t_out):
if R_in.size == 0 or t_out.size == 0:
return np.array((), dtype=np.quaternion)
# This list contains an index for each `t_out` such that
# t_in[i-1] <= t_out < t_in[i]
# Note that `side='right'` is much faster in my tests
# i_in_for_out = t_in.searchsorted(t_out... | Spherical "quadrangular" interpolation of rotors with a cubic spline
This is the best way to interpolate rotations. It uses the analog
of a cubic spline, except that the interpolant is confined to the
rotor manifold in a natural way. Alternative methods involving
interpolation of other coordinates on... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/quaternion_time_series.py#L38-L154 | null | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import print_function, division, absolute_import
import numpy as np
import quaternion
from quaternion.numba_wrapper import njit
def slerp(R1, R2, t1, t2, t_out):
"""Spher... |
moble/quaternion | quaternion_time_series.py | integrate_angular_velocity | python | def integrate_angular_velocity(Omega, t0, t1, R0=None, tolerance=1e-12):
import warnings
from scipy.integrate import ode
if R0 is None:
R0 = quaternion.one
input_is_tabulated = False
try:
t_Omega, v = Omega
from scipy.interpolate import InterpolatedUnivariateSpline
... | Compute frame with given angular velocity
Parameters
==========
Omega: tuple or callable
Angular velocity from which to compute frame. Can be
1) a 2-tuple of float arrays (t, v) giving the angular velocity vector at a series of times,
2) a function of time that returns the 3-ve... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/quaternion_time_series.py#L203-L291 | [
"def as_quat_array(a):\n \"\"\"View a float array as an array of quaternions\n\n The input array must have a final dimension whose size is\n divisible by four (or better yet *is* 4), because successive\n indices in that last dimension will be considered successive\n components of the output quaternio... | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import print_function, division, absolute_import
import numpy as np
import quaternion
from quaternion.numba_wrapper import njit
def slerp(R1, R2, t1, t2, t_out):
"""Spher... |
moble/quaternion | quaternion_time_series.py | minimal_rotation | python | def minimal_rotation(R, t, iterations=2):
from scipy.interpolate import InterpolatedUnivariateSpline as spline
if iterations == 0:
return R
R = quaternion.as_float_array(R)
Rdot = np.empty_like(R)
for i in range(4):
Rdot[:, i] = spline(t, R[:, i]).derivative()(t)
R = quaternion.f... | Adjust frame so that there is no rotation about z' axis
The output of this function is a frame that rotates the z axis onto the same z' axis as the
input frame, but with minimal rotation about that axis. This is done by pre-composing the input
rotation with a rotation about the z axis through an angle gam... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/quaternion_time_series.py#L294-L332 | [
"def minimal_rotation(R, t, iterations=2):\n \"\"\"Adjust frame so that there is no rotation about z' axis\n\n The output of this function is a frame that rotates the z axis onto the same z' axis as the\n input frame, but with minimal rotation about that axis. This is done by pre-composing the input\n ... | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import print_function, division, absolute_import
import numpy as np
import quaternion
from quaternion.numba_wrapper import njit
def slerp(R1, R2, t1, t2, t_out):
"""Spher... |
moble/quaternion | means.py | mean_rotor_in_chordal_metric | python | def mean_rotor_in_chordal_metric(R, t=None):
if not t:
return np.quaternion(*(np.sum(as_float_array(R)))).normalized()
mean = np.empty((4,), dtype=float)
definite_integral(as_float_array(R), t, mean)
return np.quaternion(*mean).normalized() | Return rotor that is closest to all R in the least-squares sense
This can be done (quasi-)analytically because of the simplicity of
the chordal metric function. The only approximation is the simple
2nd-order discrete formula for the definite integral of the input
rotor function.
Note that the `t`... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/means.py#L11-L29 | [
"def _identity_decorator_inner(fn):\n return fn\n"
] | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .calculus import definite_integral
def optimal_alignment_in_chordal_metric(Ra, Rb, t=None):
"""... |
moble/quaternion | __init__.py | as_float_array | python | def as_float_array(a):
return np.asarray(a, dtype=np.quaternion).view((np.double, 4)) | View the quaternion array as an array of floats
This function is fast (of order 1 microsecond) because no data is
copied; the returned quantity is just a "view" of the original.
The output view has one more dimension (of size 4) than the input
array, but is otherwise the same shape. | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L53-L63 | null | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .numpy_quaternion import (quaternion, _eps,
slerp_evaluate, squad_evalu... |
moble/quaternion | __init__.py | as_quat_array | python | def as_quat_array(a):
a = np.asarray(a, dtype=np.double)
# fast path
if a.shape == (4,):
return quaternion(a[0], a[1], a[2], a[3])
# view only works if the last axis is C-contiguous
if not a.flags['C_CONTIGUOUS'] or a.strides[-1] != a.itemsize:
a = a.copy(order='C')
try:
... | View a float array as an array of quaternions
The input array must have a final dimension whose size is
divisible by four (or better yet *is* 4), because successive
indices in that last dimension will be considered successive
components of the output quaternion.
This function is usually fast (of o... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L66-L113 | null | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .numpy_quaternion import (quaternion, _eps,
slerp_evaluate, squad_evalu... |
moble/quaternion | __init__.py | as_spinor_array | python | def as_spinor_array(a):
a = np.atleast_1d(a)
assert a.dtype == np.dtype(np.quaternion)
# I'm not sure why it has to be so complicated, but all of these steps
# appear to be necessary in this case.
return a.view(np.float).reshape(a.shape + (4,))[..., [0, 3, 2, 1]].ravel().view(np.complex).reshape(a.s... | View a quaternion array as spinors in two-complex representation
This function is relatively slow and scales poorly, because memory
copying is apparently involved -- I think it's due to the
"advanced indexing" required to swap the columns. | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L120-L132 | null | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .numpy_quaternion import (quaternion, _eps,
slerp_evaluate, squad_evalu... |
moble/quaternion | __init__.py | as_rotation_matrix | python | def as_rotation_matrix(q):
if q.shape == () and not isinstance(q, np.ndarray): # This is just a single quaternion
n = q.norm()
if n == 0.0:
raise ZeroDivisionError("Input to `as_rotation_matrix({0})` has zero norm".format(q))
elif abs(n-1.0) < _eps: # Input q is basically norma... | Convert input quaternion to 3x3 rotation matrix
Parameters
----------
q: quaternion or array of quaternions
The quaternion(s) need not be normalized, but must all be nonzero
Returns
-------
rot: float array
Output shape is q.shape+(3,3). This matrix should multiply (from
... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L135-L187 | [
"def as_float_array(a):\n \"\"\"View the quaternion array as an array of floats\n\n This function is fast (of order 1 microsecond) because no data is\n copied; the returned quantity is just a \"view\" of the original.\n\n The output view has one more dimension (of size 4) than the input\n array, but ... | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .numpy_quaternion import (quaternion, _eps,
slerp_evaluate, squad_evalu... |
moble/quaternion | __init__.py | from_rotation_matrix | python | def from_rotation_matrix(rot, nonorthogonal=True):
try:
from scipy import linalg
except ImportError:
linalg = False
rot = np.array(rot, copy=False)
shape = rot.shape[:-2]
if linalg and nonorthogonal:
from operator import mul
from functools import reduce
K3 ... | Convert input 3x3 rotation matrix to unit quaternion
By default, if scipy.linalg is available, this function uses
Bar-Itzhack's algorithm to allow for non-orthogonal matrices.
[J. Guidance, Vol. 23, No. 6, p. 1085 <http://dx.doi.org/10.2514/2.4654>]
This will almost certainly be quite a bit slower than... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L190-L326 | [
"def as_quat_array(a):\n \"\"\"View a float array as an array of quaternions\n\n The input array must have a final dimension whose size is\n divisible by four (or better yet *is* 4), because successive\n indices in that last dimension will be considered successive\n components of the output quaternio... | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .numpy_quaternion import (quaternion, _eps,
slerp_evaluate, squad_evalu... |
moble/quaternion | __init__.py | from_rotation_vector | python | def from_rotation_vector(rot):
rot = np.array(rot, copy=False)
quats = np.zeros(rot.shape[:-1]+(4,))
quats[..., 1:] = rot[...]/2
quats = as_quat_array(quats)
return np.exp(quats) | Convert input 3-vector in axis-angle representation to unit quaternion
Parameters
----------
rot: (Nx3) float array
Each vector represents the axis of the rotation, with norm
proportional to the angle of the rotation in radians.
Returns
-------
q: array of quaternions
U... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L351-L371 | [
"def as_quat_array(a):\n \"\"\"View a float array as an array of quaternions\n\n The input array must have a final dimension whose size is\n divisible by four (or better yet *is* 4), because successive\n indices in that last dimension will be considered successive\n components of the output quaternio... | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .numpy_quaternion import (quaternion, _eps,
slerp_evaluate, squad_evalu... |
moble/quaternion | __init__.py | as_euler_angles | python | def as_euler_angles(q):
alpha_beta_gamma = np.empty(q.shape + (3,), dtype=np.float)
n = np.norm(q)
q = as_float_array(q)
alpha_beta_gamma[..., 0] = np.arctan2(q[..., 3], q[..., 0]) + np.arctan2(-q[..., 1], q[..., 2])
alpha_beta_gamma[..., 1] = 2*np.arccos(np.sqrt((q[..., 0]**2 + q[..., 3]**2)/n))
... | Open Pandora's Box
If somebody is trying to make you use Euler angles, tell them no, and
walk away, and go and tell your mum.
You don't want to use Euler angles. They are awful. Stay away. It's
one thing to convert from Euler angles to quaternions; at least you're
moving in the right direction.... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L374-L421 | [
"def as_float_array(a):\n \"\"\"View the quaternion array as an array of floats\n\n This function is fast (of order 1 microsecond) because no data is\n copied; the returned quantity is just a \"view\" of the original.\n\n The output view has one more dimension (of size 4) than the input\n array, but ... | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .numpy_quaternion import (quaternion, _eps,
slerp_evaluate, squad_evalu... |
moble/quaternion | __init__.py | from_euler_angles | python | def from_euler_angles(alpha_beta_gamma, beta=None, gamma=None):
# Figure out the input angles from either type of input
if gamma is None:
alpha_beta_gamma = np.asarray(alpha_beta_gamma, dtype=np.double)
alpha = alpha_beta_gamma[..., 0]
beta = alpha_beta_gamma[..., 1]
gamma = alp... | Improve your life drastically
Assumes the Euler angles correspond to the quaternion R via
R = exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)
The angles naturally must be in radians for this to make any sense.
NOTE: Before opening an issue reporting something "wrong" with this
function, be s... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L424-L479 | [
"def as_quat_array(a):\n \"\"\"View a float array as an array of quaternions\n\n The input array must have a final dimension whose size is\n divisible by four (or better yet *is* 4), because successive\n indices in that last dimension will be considered successive\n components of the output quaternio... | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .numpy_quaternion import (quaternion, _eps,
slerp_evaluate, squad_evalu... |
moble/quaternion | __init__.py | from_spherical_coords | python | def from_spherical_coords(theta_phi, phi=None):
# Figure out the input angles from either type of input
if phi is None:
theta_phi = np.asarray(theta_phi, dtype=np.double)
theta = theta_phi[..., 0]
phi = theta_phi[..., 1]
else:
theta = np.asarray(theta_phi, dtype=np.double)
... | Return the quaternion corresponding to these spherical coordinates
Assumes the spherical coordinates correspond to the quaternion R via
R = exp(phi*z/2) * exp(theta*y/2)
The angles naturally must be in radians for this to make any sense.
Note that this quaternion rotates `z` onto the point with ... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L507-L559 | [
"def as_quat_array(a):\n \"\"\"View a float array as an array of quaternions\n\n The input array must have a final dimension whose size is\n divisible by four (or better yet *is* 4), because successive\n indices in that last dimension will be considered successive\n components of the output quaternio... | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .numpy_quaternion import (quaternion, _eps,
slerp_evaluate, squad_evalu... |
moble/quaternion | __init__.py | rotate_vectors | python | def rotate_vectors(R, v, axis=-1):
R = np.asarray(R, dtype=np.quaternion)
v = np.asarray(v, dtype=float)
if v.ndim < 1 or 3 not in v.shape:
raise ValueError("Input `v` does not have at least one dimension of length 3")
if v.shape[axis] != 3:
raise ValueError("Input `v` axis {0} has lengt... | Rotate vectors by given quaternions
For simplicity, this function simply converts the input
quaternion(s) to a matrix, and rotates the input vector(s) by the
usual matrix multiplication. However, it should be noted that if
each input quaternion is only used to rotate a single vector, it
is more ef... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L562-L612 | [
"def as_rotation_matrix(q):\n \"\"\"Convert input quaternion to 3x3 rotation matrix\n\n Parameters\n ----------\n q: quaternion or array of quaternions\n The quaternion(s) need not be normalized, but must all be nonzero\n\n Returns\n -------\n rot: float array\n Output shape is q.... | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .numpy_quaternion import (quaternion, _eps,
slerp_evaluate, squad_evalu... |
moble/quaternion | __init__.py | isclose | python | def isclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False):
def within_tol(x, y, atol, rtol):
with np.errstate(invalid='ignore'):
result = np.less_equal(abs(x-y), atol + rtol * abs(y))
if np.isscalar(a) and np.isscalar(b):
result = bool(result)
return re... | Returns a boolean array where two arrays are element-wise equal within a
tolerance.
This function is essentially a copy of the `numpy.isclose` function,
with different default tolerances and one minor changes necessary to
deal correctly with quaternions.
The tolerance values are positive, typicall... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L615-L722 | [
"def within_tol(x, y, atol, rtol):\n with np.errstate(invalid='ignore'):\n result = np.less_equal(abs(x-y), atol + rtol * abs(y))\n if np.isscalar(a) and np.isscalar(b):\n result = bool(result)\n return result\n"
] | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .numpy_quaternion import (quaternion, _eps,
slerp_evaluate, squad_evalu... |
moble/quaternion | __init__.py | allclose | python | def allclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False, verbose=False):
close = isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
result = np.all(close)
if verbose and not result:
print('Non-close values:')
for i in np.argwhere(close == False):
i = tuple(... | Returns True if two arrays are element-wise equal within a tolerance.
This function is essentially a wrapper for the `quaternion.isclose`
function, but returns a single boolean value of True if all elements
of the output from `quaternion.isclose` are True, and False otherwise.
This function also adds t... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/__init__.py#L725-L786 | [
"def isclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False):\n \"\"\"\n Returns a boolean array where two arrays are element-wise equal within a\n tolerance.\n\n This function is essentially a copy of the `numpy.isclose` function,\n with different default tolerances and one minor change... | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from .numpy_quaternion import (quaternion, _eps,
slerp_evaluate, squad_evalu... |
moble/quaternion | calculus.py | derivative | python | def derivative(f, t):
dfdt = np.empty_like(f)
if (f.ndim == 1):
_derivative(f, t, dfdt)
elif (f.ndim == 2):
_derivative_2d(f, t, dfdt)
elif (f.ndim == 3):
_derivative_3d(f, t, dfdt)
else:
raise NotImplementedError("Taking derivatives of {0}-dimensional arrays is not y... | Fourth-order finite-differencing with non-uniform time steps
The formula for this finite difference comes from Eq. (A 5b) of "Derivative formulas and errors for non-uniformly
spaced points" by M. K. Bowen and Ronald Smith. As explained in their Eqs. (B 9b) and (B 10b), this is a
fourth-order formula -- th... | train | https://github.com/moble/quaternion/blob/7a323e81b391d6892e2874073e495e0beb057e85/calculus.py#L9-L28 | [
"def _identity_decorator_inner(fn):\n return fn\n"
] | # Copyright (c) 2017, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
from __future__ import division, print_function, absolute_import
import numpy as np
from quaternion.numba_wrapper import njit, jit, xrange
@njit
def _derivative(f, t, dfdt):
for i in xra... |
ethereum/eth-account | eth_account/signers/local.py | LocalAccount.encrypt | python | def encrypt(self, password, kdf=None, iterations=None):
'''
Generate a string with the encrypted key, as in
:meth:`~eth_account.account.Account.encrypt`, but without a private key argument.
'''
return self._publicapi.encrypt(self.privateKey, password, kdf=kdf, iterations=iteratio... | Generate a string with the encrypted key, as in
:meth:`~eth_account.account.Account.encrypt`, but without a private key argument. | train | https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/signers/local.py#L51-L56 | null | class LocalAccount(BaseAccount):
'''
A collection of convenience methods to sign and encrypt, with an embedded private key.
:var bytes privateKey: the 32-byte private key data
.. code-block:: python
>>> my_local_account.address
"0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"
>>> ... |
ethereum/eth-account | eth_account/messages.py | defunct_hash_message | python | def defunct_hash_message(
primitive=None,
*,
hexstr=None,
text=None,
signature_version=b'E',
version_specific_data=None):
'''
Convert the provided message into a message hash, to be signed.
This provides the same prefix and hashing approach as
:meth:`w3.et... | Convert the provided message into a message hash, to be signed.
This provides the same prefix and hashing approach as
:meth:`w3.eth.sign() <web3.eth.Eth.sign>`.
Currently you can only specify the ``signature_version`` as following.
* **Version** ``0x45`` (version ``E``): ``b'\\x19Ethereum Signed Messa... | train | https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/messages.py#L17-L90 | null | from cytoolz import (
compose,
)
from eth_utils import (
keccak,
to_bytes,
)
from hexbytes import (
HexBytes,
)
from eth_account._utils.signing import (
signature_wrapper,
)
|
ethereum/eth-account | eth_account/account.py | Account.create | python | def create(self, extra_entropy=''):
'''
Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`.
:param extra_entropy: Add extra randomness to whatever randomness your OS can provide
:type extra_entropy: str or bytes or int
:returns: an object wit... | Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`.
:param extra_entropy: Add extra randomness to whatever randomness your OS can provide
:type extra_entropy: str or bytes or int
:returns: an object with private key and convenience methods
.. code-b... | train | https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/account.py#L69-L92 | null | class Account(object):
'''
This is the primary entry point for working with Ethereum private keys.
It does **not** require a connection to an Ethereum node.
'''
_keys = keys
default_kdf = os.getenv('ETH_ACCOUNT_KDF', 'scrypt')
'''
The default key deriviation function (KDF) to use when ... |
ethereum/eth-account | eth_account/account.py | Account.decrypt | python | def decrypt(keyfile_json, password):
'''
Decrypts a private key that was encrypted using an Ethereum client or
:meth:`~Account.encrypt`.
:param keyfile_json: The encrypted key
:type keyfile_json: dict or str
:param str password: The password that was used to encrypt the ... | Decrypts a private key that was encrypted using an Ethereum client or
:meth:`~Account.encrypt`.
:param keyfile_json: The encrypted key
:type keyfile_json: dict or str
:param str password: The password that was used to encrypt the key
:returns: the raw private key
:rtype:... | train | https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/account.py#L95-L134 | null | class Account(object):
'''
This is the primary entry point for working with Ethereum private keys.
It does **not** require a connection to an Ethereum node.
'''
_keys = keys
default_kdf = os.getenv('ETH_ACCOUNT_KDF', 'scrypt')
'''
The default key deriviation function (KDF) to use when ... |
ethereum/eth-account | eth_account/account.py | Account.encrypt | python | def encrypt(cls, private_key, password, kdf=None, iterations=None):
'''
Creates a dictionary with an encrypted version of your private key.
To import this keyfile into Ethereum clients like geth and parity:
encode this dictionary with :func:`json.dumps` and save it to disk where your
... | Creates a dictionary with an encrypted version of your private key.
To import this keyfile into Ethereum clients like geth and parity:
encode this dictionary with :func:`json.dumps` and save it to disk where your
client keeps key files.
:param private_key: The raw private key
:t... | train | https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/account.py#L137-L196 | null | class Account(object):
'''
This is the primary entry point for working with Ethereum private keys.
It does **not** require a connection to an Ethereum node.
'''
_keys = keys
default_kdf = os.getenv('ETH_ACCOUNT_KDF', 'scrypt')
'''
The default key deriviation function (KDF) to use when ... |
ethereum/eth-account | eth_account/account.py | Account.privateKeyToAccount | python | def privateKeyToAccount(self, private_key):
'''
Returns a convenient object for working with the given private key.
:param private_key: The raw private key
:type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey`
:return: object with methods for signing a... | Returns a convenient object for working with the given private key.
:param private_key: The raw private key
:type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey`
:return: object with methods for signing and encrypting
:rtype: LocalAccount
.. code-bloc... | train | https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/account.py#L199-L222 | null | class Account(object):
'''
This is the primary entry point for working with Ethereum private keys.
It does **not** require a connection to an Ethereum node.
'''
_keys = keys
default_kdf = os.getenv('ETH_ACCOUNT_KDF', 'scrypt')
'''
The default key deriviation function (KDF) to use when ... |
ethereum/eth-account | eth_account/account.py | Account.recoverHash | python | def recoverHash(self, message_hash, vrs=None, signature=None):
'''
Get the address of the account that signed the message with the given hash.
You must specify exactly one of: vrs or signature
:param message_hash: the hash of the message that you want to verify
:type message_has... | Get the address of the account that signed the message with the given hash.
You must specify exactly one of: vrs or signature
:param message_hash: the hash of the message that you want to verify
:type message_hash: hex str or bytes or int
:param vrs: the three pieces generated by an ell... | train | https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/account.py#L225-L297 | [
"def to_standard_signature_bytes(ethereum_signature_bytes):\n rs = ethereum_signature_bytes[:-1]\n v = to_int(ethereum_signature_bytes[-1])\n standard_v = to_standard_v(v)\n return rs + to_bytes(standard_v)\n",
"def to_standard_v(enhanced_v):\n (_chain, chain_naive_v) = extract_chain_id(enhanced_v)... | class Account(object):
'''
This is the primary entry point for working with Ethereum private keys.
It does **not** require a connection to an Ethereum node.
'''
_keys = keys
default_kdf = os.getenv('ETH_ACCOUNT_KDF', 'scrypt')
'''
The default key deriviation function (KDF) to use when ... |
ethereum/eth-account | eth_account/account.py | Account.recoverTransaction | python | def recoverTransaction(self, serialized_transaction):
'''
Get the address of the account that signed this transaction.
:param serialized_transaction: the complete signed transaction
:type serialized_transaction: hex str, bytes or int
:returns: address of signer, hex-encoded & ch... | Get the address of the account that signed this transaction.
:param serialized_transaction: the complete signed transaction
:type serialized_transaction: hex str, bytes or int
:returns: address of signer, hex-encoded & checksummed
:rtype: str
.. code-block:: python
... | train | https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/account.py#L300-L318 | [
"def hash_of_signed_transaction(txn_obj):\n '''\n Regenerate the hash of the signed transaction object.\n\n 1. Infer the chain ID from the signature\n 2. Strip out signature from transaction\n 3. Annotate the transaction with that ID, if available\n 4. Take the hash of the serialized, unsigned, ch... | class Account(object):
'''
This is the primary entry point for working with Ethereum private keys.
It does **not** require a connection to an Ethereum node.
'''
_keys = keys
default_kdf = os.getenv('ETH_ACCOUNT_KDF', 'scrypt')
'''
The default key deriviation function (KDF) to use when ... |
ethereum/eth-account | eth_account/account.py | Account.signHash | python | def signHash(self, message_hash, private_key):
'''
Sign the hash provided.
.. WARNING:: *Never* sign a hash that you didn't generate,
it can be an arbitrary transaction. For example, it might
send all of your account's ether to an attacker.
If you would like com... | Sign the hash provided.
.. WARNING:: *Never* sign a hash that you didn't generate,
it can be an arbitrary transaction. For example, it might
send all of your account's ether to an attacker.
If you would like compatibility with
:meth:`w3.eth.sign() <web3.eth.Eth.sign>`
... | train | https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/account.py#L333-L393 | [
"def sign_message_hash(key, msg_hash):\n signature = key.sign_msg_hash(msg_hash)\n (v_raw, r, s) = signature.vrs\n v = to_eth_v(v_raw)\n eth_signature_bytes = to_bytes32(r) + to_bytes32(s) + to_bytes(v)\n return (v, r, s, eth_signature_bytes)\n"
] | class Account(object):
'''
This is the primary entry point for working with Ethereum private keys.
It does **not** require a connection to an Ethereum node.
'''
_keys = keys
default_kdf = os.getenv('ETH_ACCOUNT_KDF', 'scrypt')
'''
The default key deriviation function (KDF) to use when ... |
ethereum/eth-account | eth_account/account.py | Account.signTransaction | python | def signTransaction(self, transaction_dict, private_key):
'''
Sign a transaction using a local private key. Produces signature details
and the hex-encoded transaction suitable for broadcast using
:meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`.
Create the t... | Sign a transaction using a local private key. Produces signature details
and the hex-encoded transaction suitable for broadcast using
:meth:`w3.eth.sendRawTransaction() <web3.eth.Eth.sendRawTransaction>`.
Create the transaction dict for a contract method with
`my_contract.functions.my_f... | train | https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/account.py#L396-L467 | null | class Account(object):
'''
This is the primary entry point for working with Ethereum private keys.
It does **not** require a connection to an Ethereum node.
'''
_keys = keys
default_kdf = os.getenv('ETH_ACCOUNT_KDF', 'scrypt')
'''
The default key deriviation function (KDF) to use when ... |
ethereum/eth-account | eth_account/account.py | Account._parsePrivateKey | python | def _parsePrivateKey(self, key):
'''
Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the
key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key.
:param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey`
... | Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the
key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key.
:param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey`
will be generated
:type key: hex str... | train | https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/account.py#L470-L489 | null | class Account(object):
'''
This is the primary entry point for working with Ethereum private keys.
It does **not** require a connection to an Ethereum node.
'''
_keys = keys
default_kdf = os.getenv('ETH_ACCOUNT_KDF', 'scrypt')
'''
The default key deriviation function (KDF) to use when ... |
ethereum/eth-account | eth_account/_utils/structured_data/hashing.py | get_dependencies | python | def get_dependencies(primary_type, types):
deps = set()
struct_names_yet_to_be_expanded = [primary_type]
while len(struct_names_yet_to_be_expanded) > 0:
struct_name = struct_names_yet_to_be_expanded.pop()
deps.add(struct_name)
fields = types[struct_name]
for field in fields... | Perform DFS to get all the dependencies of the primary_type | train | https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/_utils/structured_data/hashing.py#L28-L54 | null | from itertools import (
groupby,
)
import json
from operator import (
itemgetter,
)
from eth_abi import (
encode_abi,
is_encodable,
)
from eth_abi.grammar import (
parse,
)
from eth_utils import (
ValidationError,
keccak,
to_tuple,
toolz,
)
from .validation import (
validate_st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.