code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
ticket = AuthTicket(owner=self, service=service)
ticket.authorize()
return ticket | def create_ticket(self, service) | Create an AuthTicket for a given service. | 9.12354 | 5.64853 | 1.615206 |
return self.auth_tickets \
.filter(expires__gt=datetime.now(timezone.utc), service=service) \
.last() | def get_ticket(self, service) | Return an existing AuthTicket for a given service. | 6.73355 | 4.791505 | 1.40531 |
ticket = ticket or self.get_or_create_ticket('wsfe')
client = clients.get_client('wsfe', self.is_sandboxed)
response = client.service.FEParamGetPtosVenta(
serializers.serialize_ticket(ticket),
)
check_response(response)
results = []
for pos_... | def fetch_points_of_sales(self, ticket=None) | Fetch all point of sales objects.
Fetch all point of sales from the WS and store (or update) them
locally.
Returns a list of tuples with the format (pos, created,). | 6.009048 | 6.445576 | 0.932275 |
_, ext = os.path.splitext(self.logo.file.name)
with open(self.logo.file.name, 'rb') as f:
data = base64.b64encode(f.read())
return 'data:image/{};base64,{}'.format(
ext[1:], # Remove the leading dot.
data.decode()
) | def logo_as_data_uri(self) | This TaxPayer's logo as a data uri. | 2.412869 | 2.285553 | 1.055705 |
request = self.__create_request_xml()
request = self.__sign_request(request)
request = b64encode(request).decode()
client = clients.get_client('wsaa', self.owner.is_sandboxed)
try:
raw_response = client.service.loginCms(request)
except Fault as e:
... | def authorize(self) | Send this ticket to AFIP for authorization. | 4.423043 | 4.235937 | 1.044171 |
first = self.select_related('point_of_sales', 'receipt_type').first()
next_num = Receipt.objects.fetch_last_receipt_number(
first.point_of_sales,
first.receipt_type,
) + 1
for receipt in self.filter(receipt_number__isnull=True):
# Atomically... | def _assign_numbers(self) | Assign numbers in preparation for validating these receipts.
WARNING: Don't call the method manually unless you know what you're
doing! | 3.874098 | 3.502251 | 1.106174 |
types = self.aggregate(
poses=Count('point_of_sales_id', distinct=True),
types=Count('receipt_type', distinct=True),
)
if set(types.values()) > {1}:
raise exceptions.CannotValidateTogether()
return self | def check_groupable(self) | Checks that all receipts returned by this queryset are groupable.
"Groupable" means that they can be validated together: they have the
same POS and receipt type.
Returns the same queryset is all receipts are groupable, otherwise,
raises :class:`~.CannotValidateTogether`. | 10.453899 | 4.836886 | 2.161287 |
# Skip any already-validated ones:
qs = self.filter(validation__isnull=True).check_groupable()
if qs.count() == 0:
return []
qs.order_by('issued_date', 'id')._assign_numbers()
return qs._validate(ticket) | def validate(self, ticket=None) | Validates all receipts matching this queryset.
Note that, due to how AFIP implements its numbering, this method is not
thread-safe, or even multiprocess-safe.
Because of this, it is possible that not all instances matching this
queryset are validated properly. Obviously, only successfu... | 11.777112 | 9.81732 | 1.199626 |
client = clients.get_client('wsfe', point_of_sales.owner.is_sandboxed)
response_xml = client.service.FECompUltimoAutorizado(
serializers.serialize_ticket(
point_of_sales.owner.get_or_create_ticket('wsfe')
),
point_of_sales.number,
... | def fetch_last_receipt_number(self, point_of_sales, receipt_type) | Returns the number for the last validated receipt. | 8.52088 | 8.340909 | 1.021577 |
q = Vat.objects.filter(receipt=self).aggregate(total=Sum('amount'))
return q['total'] or 0 | def total_vat(self) | Returns the sum of all Vat objects. | 4.83715 | 4.032981 | 1.199398 |
q = Tax.objects.filter(receipt=self).aggregate(total=Sum('amount'))
return q['total'] or 0 | def total_tax(self) | Returns the sum of all Tax objects. | 4.763138 | 3.708553 | 1.284366 |
# Avoid the DB lookup if possible:
if not self.receipt_number:
return False
try:
return self.validation.result == ReceiptValidation.RESULT_APPROVED
except ReceiptValidation.DoesNotExist:
return False | def is_validated(self) | Returns True if this instance is validated.
Note that resolving this property requires a DB query, so if you've a
very large amount of receipts you should prefetch (see django's
``select_related``) the ``validation`` field. Even so, a DB query *may*
be triggered.
If you need a ... | 7.801475 | 4.381034 | 1.780738 |
# XXX: Maybe actually have this sortcut raise an exception?
rv = Receipt.objects.filter(pk=self.pk).validate(ticket)
# Since we're operating via a queryset, this instance isn't properly
# updated:
self.refresh_from_db()
if raise_ and rv:
raise excepti... | def validate(self, ticket=None, raise_=False) | Validates this receipt.
This is a shortcut to :class:`~.ReceiptQuerySet`'s method of the same
name. Calling this validates only this instance.
:param AuthTicket ticket: Use this ticket. If None, one will be loaded
or created automatically.
:param bool raise_: If True, an ex... | 12.496806 | 10.773953 | 1.159909 |
try:
profile = TaxPayerProfile.objects.get(
taxpayer__points_of_sales__receipts=receipt,
)
except TaxPayerProfile.DoesNotExist:
raise exceptions.DjangoAfipException(
'Cannot generate a PDF for taxpayer with no profile',
... | def create_for_receipt(self, receipt, **kwargs) | Creates a ReceiptPDF object for a given receipt. Does not actually
generate the related PDF file.
All attributes will be completed with the information for the relevant
``TaxPayerProfile`` instance.
:param Receipt receipt: The receipt for the PDF which will be
generated. | 3.951368 | 3.266359 | 1.209716 |
from django_afip.views import ReceiptPDFView
if not self.receipt.is_validated:
raise exceptions.DjangoAfipException(
_('Cannot generate pdf for non-authorized receipt')
)
self.pdf_file = File(BytesIO(), name='{}.pdf'.format(uuid.uuid4().hex))
... | def save_pdf(self, save_model=True) | Save the receipt as a PDF related to this model.
The related :class:`~.Receipt` should be validated first, of course.
:param bool save_model: If True, immediately save this model instance. | 5.457603 | 5.411795 | 1.008464 |
self.amount = self.base_amount * self.aliquot / 100
return self.amount | def compute_amount(self) | Auto-assign and return the total amount for this tax. | 6.212059 | 4.695302 | 1.323037 |
# Turn to sparse.csr_matrix format for faster row access.
rw_transition = sparse.csr_matrix(adjacency_matrix, dtype=np.float64)
# Sum along the two axes to get out-degree and in-degree, respectively
out_degree = rw_transition.sum(axis=1)
in_degree = rw_transition.sum(axis=0)
# Form the in... | def get_label_based_random_walk_matrix(adjacency_matrix, labelled_nodes, label_absorption_probability) | Returns the label-absorbing random walk transition probability matrix.
Input: - A: A sparse matrix that contains the adjacency matrix of the graph.
Output: - W: A sparse matrix that contains the natural random walk transition probability matrix. | 2.493118 | 2.54204 | 0.980755 |
# Turn to sparse.csr_matrix format for faster row access.
rw_transition = sparse.csr_matrix(adjacency_matrix, dtype=np.float64, copy=True)
# Sum along the two axes to get out-degree and in-degree, respectively
out_degree = rw_transition.sum(axis=1)
in_degree = rw_transition.sum(axis=0)
ou... | def get_natural_random_walk_matrix(adjacency_matrix, make_shared=False) | Returns the natural random walk transition probability matrix given the adjacency matrix.
Input: - A: A sparse matrix that contains the adjacency matrix of the graph.
Output: - W: A sparse matrix that contains the natural random walk transition probability matrix. | 1.647488 | 1.691793 | 0.973812 |
if inspect.isfunction(func):
_check = func
_name = func.__name__
else:
_check = func.__call__
_name = func.__class__.__name__
if not inspect.iscoroutinefunction(_check):
raise UnknownMiddlewareException("Middleware {} should be async function".format(_name))
... | def is_middleware(func) -> bool | test whether it is a middleware
:return: Boolean | 3.796602 | 3.808433 | 0.996894 |
divisor = 11
weight = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
if len(st_reg_number) != 9 and len(st_reg_number) != 14:
return False
if len(st_reg_number) == 9:
sum_total = 0
peso = 6
for i in range(3, len(st_reg_number)-1):
sum_total = sum_total + int... | def start(st_reg_number) | Checks the number valiaty for the Rondônia state | 1.741053 | 1.687309 | 1.031852 |
divisor = 11
verificador_one = int(st_reg_number[len(st_reg_number)-4])
verificador_two = int(st_reg_number[len(st_reg_number)-1])
weights_first = [1, 3, 4, 5, 6, 7, 8, 10]
weights_secund = [3, 2, 10, 9, 8, 7, 6, 5, 4, 3, 2]
if len(st_reg_number) > 13:
return False
if len(st... | def start(st_reg_number) | Checks the number valiaty for the São Paulo state | 1.976679 | 1.916402 | 1.031453 |
divisor = 11
if len(st_reg_number) > 9:
return False
if len(st_reg_number) < 9:
return False
sum_total = 0
peso = 8
for i in range(len(st_reg_number)-2):
sum_total = sum_total + int(st_reg_number[i]) * peso
peso = peso - 1
rest_division = sum_tota... | def start(st_reg_number) | Checks the number valiaty for the Pernanbuco state | 2.102669 | 2.056845 | 1.022279 |
self.headers[key] = value | def set_header(self, key: str, value: str) -> None | set response header
:param key: the key of header
:param value: the value of header | 14.26091 | 10.105751 | 1.411168 |
weights_second_digit = range(len(st_reg_number)-1, 1, -1)
weights_first_digit = range(len(st_reg_number), 1, -1)
second_digits = st_reg_number[-1:]
number_state_registration = st_reg_number[0:len(st_reg_number) - 2]
digits_state_registration = st_reg_number[-2:]
sum_second_digit = 0
su... | def start(st_reg_number) | Checks the number valiaty for the Bahia state | 1.677094 | 1.656297 | 1.012556 |
# generate response payload
if not http_status:
http_status = STATUS_CODES.get(http_code, 'Unknown')
response: bytes = f'HTTP/1.1 {http_code} {http_status}\r\n'.encode()
for k, v in headers:
response += f'{k}: {v}\r\n'.encode()
response += b'\r\n'
response += content
#... | async def send_http_response(writer,
http_code: int,
headers: List[Tuple[str, str]],
content: bytes,
http_status: str= None
) -> None | generate http response payload and send to writer | 2.120763 | 1.882132 | 1.126788 |
return await asyncio.start_server(SocketWrapper(http_handler, websocket_handler), address, port) | async def serve(http_handler: HTTP_WRAPPER_TYPE,
websocket_handler=None,
address: str='127.0.0.1',
port: int=8000) | start server | 6.801242 | 5.272893 | 1.28985 |
ctype, pdict = parse_header(self.content_type)
if ctype == 'application/json':
self.form = json.loads(body.decode())
elif ctype == 'application/x-www-form-urlencoded':
for key, value in parse_qs(body).items():
self.form[key.decode()] = [one_... | def __body_format(self, body) | format body into different type
:param body:
:return: | 2.264934 | 2.336614 | 0.969323 |
#st_reg_number = str(st_reg_number)
weights = [9, 8, 7, 6, 5, 4, 3, 2]
digit_state_registration = st_reg_number[-1]
if len(st_reg_number) != 9:
return False
sum_total = 0
for i in range(0, 8):
sum_total = sum_total + weights[i] * int(st_reg_number[i])
if sum_total % ... | def start(st_reg_number) | Checks the number valiaty for the Paraiba state | 2.476302 | 2.397934 | 1.032682 |
#st_reg_number = str(st_reg_number)
weights = [3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
digit_state_registration = st_reg_number[-1]
if len(st_reg_number) != 11:
return False
sum = 0
for i in range(0, 10):
sum = sum + weights[i] * int(st_reg_number[i])
if sum % 11 == 0:
... | def start(st_reg_number) | Checks the number valiaty for the Mato Grosso state | 2.534184 | 2.41766 | 1.048197 |
divisor = 11
if len(st_reg_number) > 9:
return False
if len(st_reg_number) < 9:
return False
sum_total = 0
peso = 9
for i in range(len(st_reg_number)-1):
sum_total = sum_total + int(st_reg_number[i]) * peso
peso = peso - 1
rest_division = sum_total %... | def start(st_reg_number) | Checks the number valiaty for the Sergipe state | 2.213376 | 2.073809 | 1.0673 |
weights = [9, 8, 7, 6, 5, 4, 3, 2]
number_state_registration = st_reg_number[0:len(st_reg_number) - 1]
digit_state_registration = st_reg_number[-1]
if st_reg_number[0:2] not in ['10', '11', '12']:
return False
if len(st_reg_number) != 9:
return False
sum_total = 0
f... | def start(st_reg_number) | Checks the number valiaty for the Espirito Santo state | 2.683563 | 2.603498 | 1.030753 |
#st_reg_number = str(st_reg_number)
weights = [4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
digits = st_reg_number[:len(st_reg_number) - 2]
check_digits = st_reg_number[-2:]
divisor = 11
if len(st_reg_number) > 13:
return False
sum_total = 0
for i in range(len(digits)):
sum_t... | def start(st_reg_number) | Checks the number valiaty for the Acre state | 1.927416 | 1.91613 | 1.00589 |
for key in dir(object_name):
if key.isupper():
self[key] = getattr(object_name, key) | def load_from_object(self, object_name) | load all upper parameters of object as config parameters
:param object_name: the object you wanna load
:return: | 3.19219 | 3.085518 | 1.034572 |
#st_reg_number = str(st_reg_number)
number_state_registration_first_digit = st_reg_number[0:3] + '0' + st_reg_number[3: len(st_reg_number)-2]
weights_first_digit = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
wights_second_digit = [3, 2, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
first_digit = st_reg_number[-2]
... | def start(st_reg_number) | Checks the number valiaty for the Minas Gerais state | 2.025321 | 2.038796 | 0.993391 |
for m in middleware:
if is_middleware(m):
self.middleware.append(m) | def use(self, *middleware: MiddlewareType) -> None | Register Middleware
:param middleware: The Middleware Function | 5.349461 | 5.89079 | 0.908106 |
response: 'Response' = Response()
handler: Callable = empty
chain_reverse = self.middleware[::-1]
for middleware in chain_reverse:
handler = map_context_to_middleware(middleware, self, request, response, handler)
try:
await handler()
ex... | async def handler(self, request: Request) -> Tuple[int, str, List[Tuple[str, str]], bytes] | The handler handling each request
:param request: the Request instance
:return: The Response instance | 5.257413 | 6.457061 | 0.814211 |
self.debug = debug
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(self.start_server(host, port))
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(self.signal_manager.activate('before_close'))
loop... | def run(self, host: str="localhost", port: int=8000, debug: bool=False) | start the http server
:param host: The listening host
:param port: The listening port
:param debug: whether it is in debug mod or not | 2.384396 | 2.345716 | 1.01649 |
weights = range(2, 10)
digits = st_reg_number[0:len(st_reg_number) - 1]
control_digit = 11
check_digit = st_reg_number[-1:]
if len(st_reg_number) != 9:
return False
sum_total = 0
for i in weights:
sum_total = sum_total +... | def start(st_reg_number) | Checks the number valiaty for the Amazonas state | 3.234271 | 3.199114 | 1.01099 |
state_abbreviation = state_abbreviation.upper()
states_validations = {
'AC': "ac.start(" + "\"" + state_registration_number + "\"" + ")",
'AL': "al.start(" + "\"" + state_registration_number + "\"" + ")",
'AM': "am.start(" + "\"" + state_registration_number + "\"" + ")",
'A... | def start(state_registration_number, state_abbreviation) | This function is like a Facade to another modules that
makes their own state validation.
state_registration_number - string brazilian state registration number
state_abbreviation - state abbreviation
AC (Acre)
AL (Alagoas)
AM (Amazonas)
AP (Amapá)
BA (B... | 1.221963 | 1.189868 | 1.026974 |
if len(st_reg_number) > 9:
return False
if len(st_reg_number) < 9:
return False
if st_reg_number[0:2] != "24":
return False
if st_reg_number[2] not in ['0', '3', '5', '7', '8']:
return False
aux = 9
sum_total = 0
for i in range(len(st_reg_number)-1):... | def start(st_reg_number) | Checks the number valiaty for the Alagoas state | 2.236732 | 2.189107 | 1.021755 |
divisor = 11
if len(st_reg_number) > 9:
return False
if len(st_reg_number) < 9:
return False
if st_reg_number[0:2] != "03":
return False
aux = int(st_reg_number[0:len(st_reg_number) - 1])
if 3000000 < aux and aux < 3017001:
control1 = 5
control2 ... | def start(st_reg_number) | Checks the number valiaty for the Alagoas state | 2.535645 | 2.404307 | 1.054626 |
def exception_to_dict(e):
try:
return e.to_dict()
except AttributeError:
return {
"type": e.__class__.__name__,
"error": str(e),
}
result = {
"errors": [exception_to_dict... | def to_dict(self) | Return a dictionary representation of the error.
:return: A dict with the keys:
- attr: Attribute which contains the error, or "<root>" if it refers to the schema root.
- errors: A list of dictionary representations of the errors. | 2.773843 | 2.42672 | 1.143042 |
for a in filter(lambda _: self.is_action(_, *a_types), self._actions):
yield a | def _filtered_actions(self, *a_types) | Get actions filtered on a list of action types.
:param a_type: argparse.Action instance name (e.g. count, append) | 5.51054 | 7.449682 | 0.739701 |
# if action of an argument that suppresses any other, just return
if a.dest == SUPPRESS or a.default == SUPPRESS:
return
# prepare the prompt
prompt = (a.help or a.dest).capitalize()
r = {'required': a.required}
# now handle each different action
... | def _input_arg(self, a) | Ask the user for input of a single argument.
:param a: argparse.Action instance
:return: the user input, asked according to the action | 3.4117 | 3.32493 | 1.026097 |
# if action of an argument that suppresses any other, just return
if a.dest is SUPPRESS or a.default is SUPPRESS:
return
# check if an option string is used for this action in sys.argv ;
# if so, simply return as it will be parsed normally
if any(o in sys.ar... | def _set_arg(self, a, s="main", c=False) | Set a single argument.
:param a: argparse.Action instance
:param s: config section title
:param c: use class' ConfigParser instance to get parameters | 3.380805 | 3.35633 | 1.007292 |
for a in filter(lambda _: not _.last and \
not self.is_action(_, 'parsers'), self._actions):
yield a
for a in filter(lambda _: _.last and \
not self.is_action(_, 'parsers'), self._actions):
yield a
for a in filter(l... | def _sorted_actions(self) | Generate the sorted list of actions based on the "last" attribute. | 3.665208 | 3.112807 | 1.177461 |
if self._config_parsed:
return
for a in self._filtered_actions("config"):
for o in a.option_strings:
try:
i = sys.argv.index(o)
sys.argv.pop(i) # remove the option string
sys.argv.pop(i) # remo... | def config_args(self, section="main") | Additional method for feeding input arguments from a config file.
:param section: current config section name | 4.157218 | 4.521864 | 0.919359 |
argv = random.choice(self.examples).replace("--demo", "")
self._reparse_args['pos'] = shlex.split(argv) | def demo_args(self) | Additional method for replacing input arguments by demo ones. | 20.647802 | 17.931467 | 1.151484 |
if not namespace: # use the new Namespace class for handling _config
namespace = Namespace(self)
namespace = super(ArgumentParser, self).parse_args(args, namespace)
if len(self._reparse_args['pos']) > 0 or \
len(self._reparse_args['opt']) > 0 or \
len(... | def parse_args(self, args=None, namespace=None) | Reparses new arguments when _DemoAction (triggering parser.demo_args())
or _WizardAction (triggering input_args()) was called. | 4.548356 | 4.600268 | 0.988715 |
if all(len(x) == 0 for x in self._reparse_args.values()):
# normal behavior with argparse
self.print_usage(sys.stderr)
self.exit(2, gt('%s: error: %s\n') % (self.prog, message)) | def error(self, message) | Prints a usage message incorporating the message to stderr and exits in
the case when no new arguments to be reparsed, that is when no special
action like _DemoAction (triggering parser.demo_args()) or
_WizardAction (triggering input_args()) was called. Otherwise, it
simply does not... | 6.612292 | 5.570944 | 1.186925 |
if value:
if not cls._config.has_section(section):
cls._config.add_section(section)
cls._config.set(section, name, str(value)) | def add_to_config(cls, section, name, value) | Add a parameter to the shared ConfigParser object.
:param section: parameter's section
:param name: parameter's name
:param value: parameter's value | 2.094609 | 2.386328 | 0.877754 |
def wrapper(self, *args, **kwargs):
try:
text = kwargs.get('text') or args[0]
except IndexError:
text = True
_ = f(self, *args, **kwargs)
if text:
return _
elif _ is not None and isinstance(_, string_types):
filename = "{}.... | def output(f) | This decorator allows to choose to return an output as text or to save
it to a file. | 3.035466 | 2.965698 | 1.023525 |
self.logger.debug("Generating the HTML report{}..."
.format(["", " (text only)"][text]))
html = []
for piece in self._pieces:
if isinstance(piece, string_types):
html.append(markdown2.markdown(piece, extras=["tables"]))
e... | def html(self, text=TEXT) | Generate an HTML file from the report data. | 4.654974 | 4.278094 | 1.088095 |
self.logger.debug("Generating the PDF report...")
html = HTML(string=self.html())
css_file = self.css or join(dirname(abspath(__file__)),
"{}.css".format(self.theme))
css = [css_file, CSS(string=PAGE_CSS % self.__dict__)]
html.write_pd... | def pdf(self, text=TEXT) | Generate a PDF file from the report data. | 5.229764 | 4.614387 | 1.133361 |
return self._data.to_csv(sep=sep, index=index, float_format=float_fmt) | def csv(self, text=TEXT, sep=',', index=True, float_fmt="%.2g") | Generate a CSV table from the table data. | 2.97894 | 2.682967 | 1.110316 |
cols = self._data.columns
hl = pd.DataFrame([["---"] * len(cols)], index=["---"], columns=cols)
df = pd.concat([hl, self._data])
return df.to_csv(sep='|', index=True, float_format=float_format) | def md(self, text=TEXT, float_format="%.2g") | Generate Markdown from the table data. | 4.652383 | 4.268964 | 1.089815 |
def convert(line):
xml = " <item>\n"
for f in line.index:
xml += " <field name=\"%s\">%s</field>\n" % (f, line[f])
xml += " </item>\n"
return xml
return "<items>\n" + '\n'.join(self._data.apply(convert, axis=1)) + \
... | def xml(self, text=TEXT) | Generate an XML output from the report data. | 3.533496 | 3.256049 | 1.08521 |
attributes = getattr(argspec, "args", []) + getattr(argspec, "keywords", [])
defaults = argspec.defaults or []
arguments, keywords = [], {}
attribute_list = (
attributes[: -len(defaults)] if len(defaults) != 0 else attributes[:]
)
for name in attrib... | def from_argspec(argspec) | retrieve a FunctionSignature object
from the argspec and the annotations passed. | 2.678117 | 2.568366 | 1.042732 |
pos_args = []
for arg in self.args:
pos_args.append(arg_dict[arg.name])
del arg_dict[arg.name]
return pos_args, arg_dict | def split_args(self, arg_dict) | given a dictionary of arguments, split them into
args and kwargs
note: this destroys the arg_dict passed. if you need it,
create a copy first. | 2.528807 | 2.656284 | 0.952009 |
p = ansi_wrap(prompt, **(style or {}))
try:
return raw_input(p).strip()
except NameError:
return input(p).strip() | def std_input(prompt="", style=None) | Very simple Python2/3-compatible input method.
:param prompt: prompt message
:param style: dictionary of ansi_wrap keyword-arguments | 3.809371 | 4.310887 | 0.883663 |
if type(choices) in [list, tuple, set]:
choices = list(map(str, choices))
choices_str = " {%s}" % (choices_str or \
'|'.join(list(map(str, choices))))
# consider choices of the form ["(Y)es", "(N)o"] ;
# in this case, we want the choices to be [... | def user_input(prompt="", choices=None, default=None, choices_str="",
required=False) | Python2/3-compatible input method handling choices and default value.
:param prompt: prompt message
:param choices: list of possible choices or lambda function
:param default: default value
:param required: make non-null user input mandatory
:return: handled user input | 4.262172 | 4.29945 | 0.99133 |
args = list([repr(a) for a in args])
for key, value in kwargs.items():
args.append("%s=%s" % (key, repr(value)))
return "(%s)" % ", ".join([a for a in args]) | def pretty_format_args(*args, **kwargs) | Take the args, and kwargs that are passed them and format in a
prototype style. | 2.391975 | 2.351429 | 1.017243 |
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
file_content = fp.read().decode(encoding)
parsed_xml = xml.dom.minidom.parseString(file_content)
return parsed_xml.toprettyxml(indent=' ', newl='') | def render(file) | Pretty print the XML file for rendering. | 3.01983 | 2.885026 | 1.046725 |
max_file_size = current_app.config.get(
'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024)
if file.size > max_file_size:
return False
with file.open() as fp:
try:
content = fp.read().decode('utf-8')
xml.dom.minidom.parseString(content)
return ... | def validate_xml(file) | Validate an XML file. | 2.678434 | 2.629837 | 1.018479 |
return render_template(
'invenio_previewer/xml_prismjs.html',
file=file,
content=render(file),
js_bundles=['previewer_prism_js'],
css_bundles=['previewer_prism_css'],
) | def preview(file) | Render appropiate template with embed flag. | 5.924716 | 5.967895 | 0.992765 |
if argspec.keywords is not None:
return kwargs
return dict((arg, kwargs[arg]) for arg in argspec.args if arg in kwargs) | def _get_context(argspec, kwargs) | Prepare a context for the serialization.
:param argspec: The argspec of the serialization function.
:param kwargs: Dict with context
:return: Keywords arguments that function can accept. | 3.319542 | 4.45874 | 0.744502 |
assert self.getter is not None, "Getter accessor is not specified."
if callable(self.getter):
return self.getter(obj, **_get_context(self._getter_argspec, kwargs))
assert isinstance(self.getter, string_types), "Accessor must be a function or a dot-separated string."
... | def get(self, obj, **kwargs) | Get an attribute from a value.
:param obj: Object to get the attribute value from.
:return: Value of object's attribute. | 3.564604 | 3.756475 | 0.948923 |
assert self.setter is not None, "Setter accessor is not specified."
if callable(self.setter):
return self.setter(obj, value)
assert isinstance(self.setter, string_types), "Accessor must be a function or a dot-separated string."
def _set(obj, attr, value):
... | def set(self, obj, value) | Set value for obj's attribute.
:param obj: Result object or dict to assign the attribute to.
:param value: Value to be assigned. | 2.747497 | 2.871955 | 0.956665 |
if isinstance(self.attr, Accessor):
return self.attr
if callable(self.attr):
return Accessor(getter=self.attr)
attr = self.attr or self.name
return Accessor(getter=attr, setter=attr) | def accessor(self) | Get an attribute's accessor with the getter and the setter.
:return: `Accessor` instance. | 3.471698 | 3.635225 | 0.955016 |
if types.Type.is_type(self.attr_type):
try:
value = self.accessor.get(value, **kwargs)
except (AttributeError, KeyError):
if not hasattr(self, "default") and self.required:
raise
value = self.default() if callab... | def serialize(self, value, **kwargs) | Serialize the attribute of the input data.
Gets the attribute value with accessor and converts it using the
type serialization. Schema will place this serialized value into
corresponding compartment of the HAL structure with the name of the
attribute as a key.
:param value: Val... | 4.248624 | 4.250924 | 0.999459 |
compartment = value
if self.compartment is not None:
compartment = value[self.compartment]
try:
value = self.accessor.get(compartment, **kwargs)
except (KeyError, AttributeError):
if not hasattr(self, "default") and self.required:
... | def deserialize(self, value, **kwargs) | Deserialize the attribute from a HAL structure.
Get the value from the HAL structure from the attribute's compartment
using the attribute's name as a key, convert it using the attribute's
type. Schema will either return it to parent schema or will assign
to the output value if specifie... | 3.640045 | 3.312705 | 1.098814 |
if self.curie is None:
return self.name
return ":".join((self.curie.name, self.name)) | def key(self) | Embedded supports curies. | 6.089116 | 3.507354 | 1.736099 |
errors = []
result = {}
for attr in cls.__attrs__.values():
try:
result[attr.name] = attr.deserialize(value, **kwargs)
except NotImplementedError:
# Links don't support deserialization
continue
except Va... | def deserialize(cls, value, output=None, **kwargs) | Deserialize the HAL structure into the output value.
:param value: Dict of already loaded json which will be deserialized by schema attributes.
:param output: If present, the output object will be updated instead of returning the deserialized data.
:returns: Dict of deserialized value for attr... | 2.727244 | 2.833427 | 0.962525 |
self.validate_packet(data)
id_ = self.dump_hex(data[4:6])
# channel = data[5] TBC
temperature = ((data[6] & 0x7f) * 256 + data[7]) / 10
signbit = data[6] & 0x80
if signbit != 0:
temperature = -temperature
sensor_specific = {
'i... | def parse(self, data) | Parse a 9 bytes packet in the Temperature format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 8,
'packet_type': 80,
... | 4.886889 | 4.344872 | 1.124749 |
try:
if isinstance(i, string_types):
i = int(i)
if not isinstance(i, int) or i > 0:
raise Exception()
except:
raise ValueError("Not a negative integer")
return i | def neg_int(i) | Simple negative integer validation. | 3.17935 | 2.973229 | 1.069326 |
try:
if isinstance(i, string_types):
i = int(i)
if not isinstance(i, int) or i < 0:
raise Exception()
except:
raise ValueError("Not a positive integer")
return i | def pos_int(i) | Simple positive integer validation. | 2.650979 | 2.497201 | 1.06158 |
if isinstance(l, string_types):
if l[0] == '[' and l[-1] == ']':
l = l[1:-1]
l = list(map(lambda x: x.strip(), l.split(',')))
try:
l = list(map(ifilter, list(map(int, l))))
except:
raise ValueError("Bad list of {}integers"
.format("" ... | def ints(l, ifilter=lambda x: x, idescr=None) | Parses a comma-separated list of ints. | 2.70005 | 2.602118 | 1.037635 |
# first, try it as a single IP address
try:
return ip_address(ips)
except ValueError:
pass
# then, consider it as an ipaddress.IPv[4|6]Network instance and expand it
return list(ipaddress.ip_network(u(ips)).hosts()) | def ip_address_list(ips) | IP address range validation and expansion. | 7.034766 | 6.267581 | 1.122405 |
try:
port = int(port)
except ValueError:
raise ValueError("Bad port number")
if not 0 <= port < 2 ** 16:
raise ValueError("Bad port number")
return port | def port_number(port) | Port number validation. | 2.449567 | 2.333208 | 1.049871 |
# first, try it as a normal port number
try:
return port_number(prange)
except ValueError:
pass
# then, consider it as a range with the format "x-y" and expand it
try:
bounds = list(map(int, re.match(r'^(\d+)\-(\d+)$', prange).groups()))
if bounds[0] > bounds[1]:... | def port_number_range(prange) | Port number range validation and expansion. | 3.254215 | 3.149298 | 1.033314 |
packet_length = data[0]
packet_type = data[1]
packet_subtype = data[2]
sequence_number = data[3]
return {
'packet_length': packet_length,
'packet_type': packet_type,
'packet_type_name': self.PACKET_TYPES.get(packet_type),
'... | def parse_header_part(self, data) | Extracts and converts the RFX common header part of all valid
packets to a plain dictionary. RFX header part is the 4 bytes prior
the sensor vendor specific data part.
The RFX common header part contains respectively:
- packet length
- packet type
- packet sub-type
... | 1.819249 | 1.635725 | 1.112197 |
self.loaded_at = datetime.utcnow()
self.raw = data
self.data = self.parse(data)
return self.data | def load(self, data) | This is the entrance method for all data which is used to store the
raw data and start parsing the data.
:param data: The raw untouched bytearray as recieved by the RFXtrx
:type data: bytearray
:return: The parsed data represented in a dictionary
:rtype: dict | 4.588898 | 5.095412 | 0.900594 |
# Validate length.
# The first byte in the packet should be equal to the number of
# remaining bytes (i.e. length excluding the first byte).
expected_length = data[0] + 1
if len(data) != expected_length:
raise InvalidPacketLength(
"Expected ... | def validate_packet(self, data) | Validate a packet against this packet handler and determine if it
meets the requirements. This is done by checking the following
conditions are true.
- The length of the packet is equal to the first byte.
- The second byte is in the set of defined PACKET_TYPES for this class.
- ... | 2.778435 | 2.6378 | 1.053316 |
if isinstance(model_or_class, type) and issubclass(model_or_class, BaseType):
return model_or_class()
return model_or_class | def _enforce_instance(model_or_class) | It's a common mistake to not initialize a
schematics class. We should handle that by just
calling the default constructor. | 2.368678 | 2.270432 | 1.043272 |
fp = file.open()
content = fp.read()
fp.close()
notebook = nbformat.reads(content.decode('utf-8'), as_version=4)
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
(body, resources) = html_exporter.from_notebook_node(notebook)
return body, resources | def render(file) | Generate the result HTML. | 2.269253 | 2.320253 | 0.97802 |
body, resources = render(file)
default_ipython_style = resources['inlining']['css'][1]
return render_template(
'invenio_previewer/ipynb.html',
file=file,
content=body,
style=default_ipython_style
) | def preview(file) | Render the IPython Notebook. | 8.629753 | 6.629087 | 1.301801 |
transmute_func = TransmuteFunction(fn)
routes, handler = create_routes_and_handler(transmute_func, context)
for r in routes:
if not hasattr(app, SWAGGER_ATTR_NAME):
setattr(app, SWAGGER_ATTR_NAME, SwaggerSpec())
swagger_obj = getattr(app, SWAGGER_ATTR_NAME)
... | def transmute_route(app, fn, context=default_context) | this is the main interface to transmute. It will handle
adding converting the python function into the a flask-compatible route,
and adding it to the application. | 3.370213 | 3.525247 | 0.956022 |
@wraps(transmute_func.raw_func)
def handler():
exc, result = None, None
try:
args, kwargs = ParamExtractorFlask().extract_params(
context, transmute_func, request.content_type
)
result = transmute_func(*args, **kwargs)
except Excep... | def create_routes_and_handler(transmute_func, context) | return back a handler that is the api generated
from the transmute_func, and a list of routes
it should be mounted to. | 3.716409 | 3.749003 | 0.991306 |
paths = []
for p in transmute_paths:
paths.append(p.replace("{", "<").replace("}", ">"))
return paths | def _convert_paths_to_flask(transmute_paths) | convert transmute-core's path syntax (which uses {var} as the
variable wildcard) into flask's <var>. | 3.092997 | 2.714115 | 1.139597 |
spec = getattr(app, SWAGGER_ATTR_NAME)
if spec:
spec = spec.swagger_definition(**kwargs)
else:
spec = {}
encoded_spec = json.dumps(spec).encode("UTF-8")
@app.route(json_route)
def swagger():
return Response(
encoded_spec,
# we allow CORS, so ... | def add_swagger(app, json_route, html_route, **kwargs) | add a swagger html page, and a swagger.json generated
from the routes added to the app. | 3.806879 | 3.891493 | 0.978257 |
enabled, disabled = [], []
for procol, flag in sorted(zip(protocols, flags)):
if flag == '1':
enabled.append(procol)
status = 'Enabled'
else:
disabled.append(procol)
status = 'Disabled'
messa... | def _log_enabled_protocols(self, flags, protocols) | Given a list of single character strings of 1's and 0's and a list
of protocol names. Log the status of each protocol where ``"1"`` is
enabled and ``"0"`` is disabled. The order of the lists here is
important as they need to be zipped together to create the mapping.
Then return a tuple o... | 3.666355 | 3.302732 | 1.110098 |
self.validate_packet(data)
packet_length = data[0]
packet_type = data[1]
sub_type = data[2]
sequence_number = data[3]
command_type = data[4]
transceiver_type = data[5]
transceiver_type_text = _MSG1_RECEIVER_TYPE.get(data[5])
firmware_ver... | def parse(self, data) | Parse a 13 byte packet in the Status format.
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict | 2.356496 | 2.256495 | 1.044317 |
a = glob['args']
l = glob['logger']
class __TimeManager(object):
def __init__(self):
c = a._collisions
self._stats = getattr(a, c.get("stats") or "stats", False)
self._timings = getattr(a, c.get("timings") or "timings", False)
self.enabled = self... | def set_time_items(glob) | This function prepares the benchmark items for inclusion in main script's
global scope.
:param glob: main script's global scope dictionary reference | 3.169451 | 3.222238 | 0.983618 |
a = glob['args']
l = glob['logger']
enabled = getattr(a, a._collisions.get("step") or "step", False)
# Step context manager, for defining a block of code that can be paused at
# its start and end
class Step(object):
def __init__(self, message=None, at_end=False):
self.m... | def set_step_items(glob) | This function prepares the stepping items for inclusion in main script's
global scope.
:param glob: main script's global scope dictionary reference | 3.963078 | 4.023189 | 0.985059 |
key = ""
next_c = next(iterator)
while next_c != "}":
key += next_c
next_c = next(iterator)
# remove the final "}"
next(iterator)
return parameters[key] | def _capture_variable(iterator, parameters) | return the replacement string.
this assumes the preceeding {{ has already been
popped off. | 4.181423 | 3.589547 | 1.164889 |
'''
Calculate the distance between two RGB sequences.
'''
return sum(map(lambda c: (c[0] - c[1]) ** 2,
zip(rgb1, rgb2))) | def rgb_distance(rgb1, rgb2) | Calculate the distance between two RGB sequences. | 4.157594 | 3.523275 | 1.180037 |
'''
Convert an RGB colour to 8 or 16 colour ANSI graphics.
'''
colours = ANSI_COLOURS[:mode]
matches = [(rgb_distance(c, map(int, [r, g, b])), i)
for i, c in enumerate(colours)]
matches.sort()
return sequence('m')(str(30 + matches[0][1])) | def rgb_reduce(r, g, b, mode=8) | Convert an RGB colour to 8 or 16 colour ANSI graphics. | 8.004457 | 5.161084 | 1.550926 |
'''
Convert an RGB colour to 256 colour ANSI graphics.
'''
grey = False
poss = True
step = 2.5
while poss: # As long as the colour could be grey scale
if r < step or g < step or b < step:
grey = r < step and g < step and b < step
poss = False
step +=... | def rgb256(r, g, b) | Convert an RGB colour to 256 colour ANSI graphics. | 6.557909 | 5.598864 | 1.171293 |
return url_for(
'.{0}_files'.format(self.pid.pid_type),
pid_value=self.pid.pid_value,
filename=self.file.key) | def uri(self) | Get file download link.
.. note::
The URI generation assumes that you can download the file using the
view ``invenio_records_ui.<pid_type>_files``. | 5.271282 | 3.868994 | 1.362442 |
file_ext = splitext(self.filename)[1]
file_ext = file_ext.lower()
for e in exts:
if file_ext == e:
return True
return False | def has_extensions(self, *exts) | Check if file has one of the extensions. | 2.963012 | 2.476238 | 1.196578 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.