id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
231,300 | ultrabug/py3status | py3status/docstrings.py | update_readme_for_modules | def update_readme_for_modules(modules):
"""
Update README.md updating the sections for the module names listed.
"""
readme = parse_readme()
module_docstrings = core_module_docstrings()
if modules == ["__all__"]:
modules = core_module_docstrings().keys()
for module in modules:
if module in module_docstrings:
print_stderr("Updating README.md for module {}".format(module))
readme[module] = module_docstrings[module]
else:
print_stderr("Module {} not in core modules".format(module))
# write the file
readme_file = os.path.join(modules_directory(), "README.md")
with open(readme_file, "w") as f:
f.write(create_readme(readme)) | python | def update_readme_for_modules(modules):
readme = parse_readme()
module_docstrings = core_module_docstrings()
if modules == ["__all__"]:
modules = core_module_docstrings().keys()
for module in modules:
if module in module_docstrings:
print_stderr("Updating README.md for module {}".format(module))
readme[module] = module_docstrings[module]
else:
print_stderr("Module {} not in core modules".format(module))
# write the file
readme_file = os.path.join(modules_directory(), "README.md")
with open(readme_file, "w") as f:
f.write(create_readme(readme)) | [
"def",
"update_readme_for_modules",
"(",
"modules",
")",
":",
"readme",
"=",
"parse_readme",
"(",
")",
"module_docstrings",
"=",
"core_module_docstrings",
"(",
")",
"if",
"modules",
"==",
"[",
"\"__all__\"",
"]",
":",
"modules",
"=",
"core_module_docstrings",
"(",... | Update README.md updating the sections for the module names listed. | [
"Update",
"README",
".",
"md",
"updating",
"the",
"sections",
"for",
"the",
"module",
"names",
"listed",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/docstrings.py#L383-L401 |
231,301 | ultrabug/py3status | py3status/docstrings.py | show_modules | def show_modules(config, modules_list):
"""
List modules available optionally with details.
"""
details = config["full"]
core_mods = not config["user"]
user_mods = not config["core"]
modules = core_module_docstrings(
include_core=core_mods, include_user=user_mods, config=config
)
new_modules = []
if modules_list:
from fnmatch import fnmatch
for _filter in modules_list:
for name in modules.keys():
if fnmatch(name, _filter):
if name not in new_modules:
new_modules.append(name)
else:
new_modules = modules.keys()
for name in sorted(new_modules):
module = _to_docstring(modules[name])
desc = module[0][:-1]
if details:
dash_len = len(name) + 4
print("#" * dash_len)
print("# {} #".format(name))
print("#" * dash_len)
for description in module:
print(description[:-1])
else:
print("%-22s %s" % (name, desc)) | python | def show_modules(config, modules_list):
details = config["full"]
core_mods = not config["user"]
user_mods = not config["core"]
modules = core_module_docstrings(
include_core=core_mods, include_user=user_mods, config=config
)
new_modules = []
if modules_list:
from fnmatch import fnmatch
for _filter in modules_list:
for name in modules.keys():
if fnmatch(name, _filter):
if name not in new_modules:
new_modules.append(name)
else:
new_modules = modules.keys()
for name in sorted(new_modules):
module = _to_docstring(modules[name])
desc = module[0][:-1]
if details:
dash_len = len(name) + 4
print("#" * dash_len)
print("# {} #".format(name))
print("#" * dash_len)
for description in module:
print(description[:-1])
else:
print("%-22s %s" % (name, desc)) | [
"def",
"show_modules",
"(",
"config",
",",
"modules_list",
")",
":",
"details",
"=",
"config",
"[",
"\"full\"",
"]",
"core_mods",
"=",
"not",
"config",
"[",
"\"user\"",
"]",
"user_mods",
"=",
"not",
"config",
"[",
"\"core\"",
"]",
"modules",
"=",
"core_mod... | List modules available optionally with details. | [
"List",
"modules",
"available",
"optionally",
"with",
"details",
"."
] | 4c105f1b44f7384ca4f7da5f821a47e468c7dee2 | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/docstrings.py#L404-L439 |
231,302 | google/pinject | pinject/injection_contexts.py | InjectionContextFactory.new | def new(self, injection_site_fn):
"""Creates a _InjectionContext.
Args:
injection_site_fn: the initial function being injected into
Returns:
a new empty _InjectionContext in the default scope
"""
return _InjectionContext(
injection_site_fn, binding_stack=[], scope_id=scoping.UNSCOPED,
is_scope_usable_from_scope_fn=self._is_scope_usable_from_scope_fn) | python | def new(self, injection_site_fn):
return _InjectionContext(
injection_site_fn, binding_stack=[], scope_id=scoping.UNSCOPED,
is_scope_usable_from_scope_fn=self._is_scope_usable_from_scope_fn) | [
"def",
"new",
"(",
"self",
",",
"injection_site_fn",
")",
":",
"return",
"_InjectionContext",
"(",
"injection_site_fn",
",",
"binding_stack",
"=",
"[",
"]",
",",
"scope_id",
"=",
"scoping",
".",
"UNSCOPED",
",",
"is_scope_usable_from_scope_fn",
"=",
"self",
".",... | Creates a _InjectionContext.
Args:
injection_site_fn: the initial function being injected into
Returns:
a new empty _InjectionContext in the default scope | [
"Creates",
"a",
"_InjectionContext",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/injection_contexts.py#L35-L45 |
231,303 | google/pinject | pinject/injection_contexts.py | _InjectionContext.get_child | def get_child(self, injection_site_fn, binding):
"""Creates a child injection context.
A "child" injection context is a context for a binding used to
inject something into the current binding's provided value.
Args:
injection_site_fn: the child function being injected into
binding: a Binding
Returns:
a new _InjectionContext
"""
child_scope_id = binding.scope_id
new_binding_stack = self._binding_stack + [binding]
if binding in self._binding_stack:
raise errors.CyclicInjectionError(new_binding_stack)
if not self._is_scope_usable_from_scope_fn(
child_scope_id, self._scope_id):
raise errors.BadDependencyScopeError(
self.get_injection_site_desc(),
self._scope_id, child_scope_id, binding.binding_key)
return _InjectionContext(
injection_site_fn, new_binding_stack, child_scope_id,
self._is_scope_usable_from_scope_fn) | python | def get_child(self, injection_site_fn, binding):
child_scope_id = binding.scope_id
new_binding_stack = self._binding_stack + [binding]
if binding in self._binding_stack:
raise errors.CyclicInjectionError(new_binding_stack)
if not self._is_scope_usable_from_scope_fn(
child_scope_id, self._scope_id):
raise errors.BadDependencyScopeError(
self.get_injection_site_desc(),
self._scope_id, child_scope_id, binding.binding_key)
return _InjectionContext(
injection_site_fn, new_binding_stack, child_scope_id,
self._is_scope_usable_from_scope_fn) | [
"def",
"get_child",
"(",
"self",
",",
"injection_site_fn",
",",
"binding",
")",
":",
"child_scope_id",
"=",
"binding",
".",
"scope_id",
"new_binding_stack",
"=",
"self",
".",
"_binding_stack",
"+",
"[",
"binding",
"]",
"if",
"binding",
"in",
"self",
".",
"_b... | Creates a child injection context.
A "child" injection context is a context for a binding used to
inject something into the current binding's provided value.
Args:
injection_site_fn: the child function being injected into
binding: a Binding
Returns:
a new _InjectionContext | [
"Creates",
"a",
"child",
"injection",
"context",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/injection_contexts.py#L70-L93 |
231,304 | google/pinject | pinject/object_graph.py | ObjectGraph.provide | def provide(self, cls):
"""Provides an instance of the given class.
Args:
cls: a class (not an instance)
Returns:
an instance of cls
Raises:
Error: an instance of cls is not providable
"""
support.verify_class_type(cls, 'cls')
if not self._is_injectable_fn(cls):
provide_loc = locations.get_back_frame_loc()
raise errors.NonExplicitlyBoundClassError(provide_loc, cls)
try:
return self._obj_provider.provide_class(
cls, self._injection_context_factory.new(cls.__init__),
direct_init_pargs=[], direct_init_kwargs={})
except errors.Error as e:
if self._use_short_stack_traces:
raise e
else:
raise | python | def provide(self, cls):
support.verify_class_type(cls, 'cls')
if not self._is_injectable_fn(cls):
provide_loc = locations.get_back_frame_loc()
raise errors.NonExplicitlyBoundClassError(provide_loc, cls)
try:
return self._obj_provider.provide_class(
cls, self._injection_context_factory.new(cls.__init__),
direct_init_pargs=[], direct_init_kwargs={})
except errors.Error as e:
if self._use_short_stack_traces:
raise e
else:
raise | [
"def",
"provide",
"(",
"self",
",",
"cls",
")",
":",
"support",
".",
"verify_class_type",
"(",
"cls",
",",
"'cls'",
")",
"if",
"not",
"self",
".",
"_is_injectable_fn",
"(",
"cls",
")",
":",
"provide_loc",
"=",
"locations",
".",
"get_back_frame_loc",
"(",
... | Provides an instance of the given class.
Args:
cls: a class (not an instance)
Returns:
an instance of cls
Raises:
Error: an instance of cls is not providable | [
"Provides",
"an",
"instance",
"of",
"the",
"given",
"class",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/object_graph.py#L183-L205 |
231,305 | google/pinject | pinject/locations.py | _get_type_name | def _get_type_name(target_thing):
"""
Functions, bound methods and unbound methods change significantly in Python 3.
For instance:
class SomeObject(object):
def method():
pass
In Python 2:
- Unbound method inspect.ismethod(SomeObject.method) returns True
- Unbound inspect.isfunction(SomeObject.method) returns False
- Unbound hasattr(SomeObject.method, 'im_class') returns True
- Bound method inspect.ismethod(SomeObject().method) returns True
- Bound method inspect.isfunction(SomeObject().method) returns False
- Bound hasattr(SomeObject().method, 'im_class') returns True
In Python 3:
- Unbound method inspect.ismethod(SomeObject.method) returns False
- Unbound inspect.isfunction(SomeObject.method) returns True
- Unbound hasattr(SomeObject.method, 'im_class') returns False
- Bound method inspect.ismethod(SomeObject().method) returns True
- Bound method inspect.isfunction(SomeObject().method) returns False
- Bound hasattr(SomeObject().method, 'im_class') returns False
This method tries to consolidate the approach for retrieving the
enclosing type of a bound/unbound method and functions.
"""
thing = target_thing
if hasattr(thing, 'im_class'):
# only works in Python 2
return thing.im_class.__name__
if inspect.ismethod(thing):
for cls in inspect.getmro(thing.__self__.__class__):
if cls.__dict__.get(thing.__name__) is thing:
return cls.__name__
thing = thing.__func__
if inspect.isfunction(thing) and hasattr(thing, '__qualname__'):
qualifier = thing.__qualname__
if LOCALS_TOKEN in qualifier:
return _get_local_type_name(thing)
return _get_external_type_name(thing)
return inspect.getmodule(target_thing).__name__ | python | def _get_type_name(target_thing):
thing = target_thing
if hasattr(thing, 'im_class'):
# only works in Python 2
return thing.im_class.__name__
if inspect.ismethod(thing):
for cls in inspect.getmro(thing.__self__.__class__):
if cls.__dict__.get(thing.__name__) is thing:
return cls.__name__
thing = thing.__func__
if inspect.isfunction(thing) and hasattr(thing, '__qualname__'):
qualifier = thing.__qualname__
if LOCALS_TOKEN in qualifier:
return _get_local_type_name(thing)
return _get_external_type_name(thing)
return inspect.getmodule(target_thing).__name__ | [
"def",
"_get_type_name",
"(",
"target_thing",
")",
":",
"thing",
"=",
"target_thing",
"if",
"hasattr",
"(",
"thing",
",",
"'im_class'",
")",
":",
"# only works in Python 2",
"return",
"thing",
".",
"im_class",
".",
"__name__",
"if",
"inspect",
".",
"ismethod",
... | Functions, bound methods and unbound methods change significantly in Python 3.
For instance:
class SomeObject(object):
def method():
pass
In Python 2:
- Unbound method inspect.ismethod(SomeObject.method) returns True
- Unbound inspect.isfunction(SomeObject.method) returns False
- Unbound hasattr(SomeObject.method, 'im_class') returns True
- Bound method inspect.ismethod(SomeObject().method) returns True
- Bound method inspect.isfunction(SomeObject().method) returns False
- Bound hasattr(SomeObject().method, 'im_class') returns True
In Python 3:
- Unbound method inspect.ismethod(SomeObject.method) returns False
- Unbound inspect.isfunction(SomeObject.method) returns True
- Unbound hasattr(SomeObject.method, 'im_class') returns False
- Bound method inspect.ismethod(SomeObject().method) returns True
- Bound method inspect.isfunction(SomeObject().method) returns False
- Bound hasattr(SomeObject().method, 'im_class') returns False
This method tries to consolidate the approach for retrieving the
enclosing type of a bound/unbound method and functions. | [
"Functions",
"bound",
"methods",
"and",
"unbound",
"methods",
"change",
"significantly",
"in",
"Python",
"3",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/locations.py#L50-L93 |
231,306 | google/pinject | pinject/arg_binding_keys.py | get_unbound_arg_names | def get_unbound_arg_names(arg_names, arg_binding_keys):
"""Determines which args have no arg binding keys.
Args:
arg_names: a sequence of the names of possibly bound args
arg_binding_keys: a sequence of ArgBindingKey each of whose arg names is
in arg_names
Returns:
a sequence of arg names that is a (possibly empty, possibly non-proper)
subset of arg_names
"""
bound_arg_names = [abk._arg_name for abk in arg_binding_keys]
return [arg_name for arg_name in arg_names
if arg_name not in bound_arg_names] | python | def get_unbound_arg_names(arg_names, arg_binding_keys):
bound_arg_names = [abk._arg_name for abk in arg_binding_keys]
return [arg_name for arg_name in arg_names
if arg_name not in bound_arg_names] | [
"def",
"get_unbound_arg_names",
"(",
"arg_names",
",",
"arg_binding_keys",
")",
":",
"bound_arg_names",
"=",
"[",
"abk",
".",
"_arg_name",
"for",
"abk",
"in",
"arg_binding_keys",
"]",
"return",
"[",
"arg_name",
"for",
"arg_name",
"in",
"arg_names",
"if",
"arg_na... | Determines which args have no arg binding keys.
Args:
arg_names: a sequence of the names of possibly bound args
arg_binding_keys: a sequence of ArgBindingKey each of whose arg names is
in arg_names
Returns:
a sequence of arg names that is a (possibly empty, possibly non-proper)
subset of arg_names | [
"Determines",
"which",
"args",
"have",
"no",
"arg",
"binding",
"keys",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/arg_binding_keys.py#L80-L94 |
231,307 | google/pinject | pinject/arg_binding_keys.py | new | def new(arg_name, annotated_with=None):
"""Creates an ArgBindingKey.
Args:
arg_name: the name of the bound arg
annotation: an Annotation, or None to create an unannotated arg binding
key
Returns:
a new ArgBindingKey
"""
if arg_name.startswith(_PROVIDE_PREFIX):
binding_key_name = arg_name[_PROVIDE_PREFIX_LEN:]
provider_indirection = provider_indirections.INDIRECTION
else:
binding_key_name = arg_name
provider_indirection = provider_indirections.NO_INDIRECTION
binding_key = binding_keys.new(binding_key_name, annotated_with)
return ArgBindingKey(arg_name, binding_key, provider_indirection) | python | def new(arg_name, annotated_with=None):
if arg_name.startswith(_PROVIDE_PREFIX):
binding_key_name = arg_name[_PROVIDE_PREFIX_LEN:]
provider_indirection = provider_indirections.INDIRECTION
else:
binding_key_name = arg_name
provider_indirection = provider_indirections.NO_INDIRECTION
binding_key = binding_keys.new(binding_key_name, annotated_with)
return ArgBindingKey(arg_name, binding_key, provider_indirection) | [
"def",
"new",
"(",
"arg_name",
",",
"annotated_with",
"=",
"None",
")",
":",
"if",
"arg_name",
".",
"startswith",
"(",
"_PROVIDE_PREFIX",
")",
":",
"binding_key_name",
"=",
"arg_name",
"[",
"_PROVIDE_PREFIX_LEN",
":",
"]",
"provider_indirection",
"=",
"provider_... | Creates an ArgBindingKey.
Args:
arg_name: the name of the bound arg
annotation: an Annotation, or None to create an unannotated arg binding
key
Returns:
a new ArgBindingKey | [
"Creates",
"an",
"ArgBindingKey",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/arg_binding_keys.py#L115-L132 |
231,308 | google/pinject | pinject/bindings.py | get_overall_binding_key_to_binding_maps | def get_overall_binding_key_to_binding_maps(bindings_lists):
"""bindings_lists from lowest to highest priority. Last item in
bindings_lists is assumed explicit.
"""
binding_key_to_binding = {}
collided_binding_key_to_bindings = {}
for index, bindings in enumerate(bindings_lists):
is_final_index = (index == (len(bindings_lists) - 1))
handle_binding_collision_fn = {
True: _handle_explicit_binding_collision,
False: _handle_implicit_binding_collision}[is_final_index]
this_binding_key_to_binding, this_collided_binding_key_to_bindings = (
_get_binding_key_to_binding_maps(
bindings, handle_binding_collision_fn))
for good_binding_key in this_binding_key_to_binding:
collided_binding_key_to_bindings.pop(good_binding_key, None)
binding_key_to_binding.update(this_binding_key_to_binding)
collided_binding_key_to_bindings.update(
this_collided_binding_key_to_bindings)
return binding_key_to_binding, collided_binding_key_to_bindings | python | def get_overall_binding_key_to_binding_maps(bindings_lists):
binding_key_to_binding = {}
collided_binding_key_to_bindings = {}
for index, bindings in enumerate(bindings_lists):
is_final_index = (index == (len(bindings_lists) - 1))
handle_binding_collision_fn = {
True: _handle_explicit_binding_collision,
False: _handle_implicit_binding_collision}[is_final_index]
this_binding_key_to_binding, this_collided_binding_key_to_bindings = (
_get_binding_key_to_binding_maps(
bindings, handle_binding_collision_fn))
for good_binding_key in this_binding_key_to_binding:
collided_binding_key_to_bindings.pop(good_binding_key, None)
binding_key_to_binding.update(this_binding_key_to_binding)
collided_binding_key_to_bindings.update(
this_collided_binding_key_to_bindings)
return binding_key_to_binding, collided_binding_key_to_bindings | [
"def",
"get_overall_binding_key_to_binding_maps",
"(",
"bindings_lists",
")",
":",
"binding_key_to_binding",
"=",
"{",
"}",
"collided_binding_key_to_bindings",
"=",
"{",
"}",
"for",
"index",
",",
"bindings",
"in",
"enumerate",
"(",
"bindings_lists",
")",
":",
"is_fina... | bindings_lists from lowest to highest priority. Last item in
bindings_lists is assumed explicit. | [
"bindings_lists",
"from",
"lowest",
"to",
"highest",
"priority",
".",
"Last",
"item",
"in",
"bindings_lists",
"is",
"assumed",
"explicit",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/bindings.py#L78-L101 |
231,309 | google/pinject | pinject/bindings.py | default_get_arg_names_from_class_name | def default_get_arg_names_from_class_name(class_name):
"""Converts normal class names into normal arg names.
Normal class names are assumed to be CamelCase with an optional leading
underscore. Normal arg names are assumed to be lower_with_underscores.
Args:
class_name: a class name, e.g., "FooBar" or "_FooBar"
Returns:
all likely corresponding arg names, e.g., ["foo_bar"]
"""
parts = []
rest = class_name
if rest.startswith('_'):
rest = rest[1:]
while True:
m = re.match(r'([A-Z][a-z]+)(.*)', rest)
if m is None:
break
parts.append(m.group(1))
rest = m.group(2)
if not parts:
return []
return ['_'.join(part.lower() for part in parts)] | python | def default_get_arg_names_from_class_name(class_name):
parts = []
rest = class_name
if rest.startswith('_'):
rest = rest[1:]
while True:
m = re.match(r'([A-Z][a-z]+)(.*)', rest)
if m is None:
break
parts.append(m.group(1))
rest = m.group(2)
if not parts:
return []
return ['_'.join(part.lower() for part in parts)] | [
"def",
"default_get_arg_names_from_class_name",
"(",
"class_name",
")",
":",
"parts",
"=",
"[",
"]",
"rest",
"=",
"class_name",
"if",
"rest",
".",
"startswith",
"(",
"'_'",
")",
":",
"rest",
"=",
"rest",
"[",
"1",
":",
"]",
"while",
"True",
":",
"m",
"... | Converts normal class names into normal arg names.
Normal class names are assumed to be CamelCase with an optional leading
underscore. Normal arg names are assumed to be lower_with_underscores.
Args:
class_name: a class name, e.g., "FooBar" or "_FooBar"
Returns:
all likely corresponding arg names, e.g., ["foo_bar"] | [
"Converts",
"normal",
"class",
"names",
"into",
"normal",
"arg",
"names",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/bindings.py#L137-L160 |
231,310 | google/pinject | pinject/decorators.py | annotate_arg | def annotate_arg(arg_name, with_annotation):
"""Adds an annotation to an injected arg.
arg_name must be one of the named args of the decorated function, i.e.,
@annotate_arg('foo', with_annotation='something')
def a_function(foo): # ...
is OK, but
@annotate_arg('foo', with_annotation='something')
def a_function(bar, **kwargs): # ...
is not.
The same arg (on the same function) may not be annotated twice.
Args:
arg_name: the name of the arg to annotate on the decorated function
with_annotation: an annotation object
Returns:
a function that will decorate functions passed to it
"""
arg_binding_key = arg_binding_keys.new(arg_name, with_annotation)
return _get_pinject_wrapper(locations.get_back_frame_loc(),
arg_binding_key=arg_binding_key) | python | def annotate_arg(arg_name, with_annotation):
arg_binding_key = arg_binding_keys.new(arg_name, with_annotation)
return _get_pinject_wrapper(locations.get_back_frame_loc(),
arg_binding_key=arg_binding_key) | [
"def",
"annotate_arg",
"(",
"arg_name",
",",
"with_annotation",
")",
":",
"arg_binding_key",
"=",
"arg_binding_keys",
".",
"new",
"(",
"arg_name",
",",
"with_annotation",
")",
"return",
"_get_pinject_wrapper",
"(",
"locations",
".",
"get_back_frame_loc",
"(",
")",
... | Adds an annotation to an injected arg.
arg_name must be one of the named args of the decorated function, i.e.,
@annotate_arg('foo', with_annotation='something')
def a_function(foo): # ...
is OK, but
@annotate_arg('foo', with_annotation='something')
def a_function(bar, **kwargs): # ...
is not.
The same arg (on the same function) may not be annotated twice.
Args:
arg_name: the name of the arg to annotate on the decorated function
with_annotation: an annotation object
Returns:
a function that will decorate functions passed to it | [
"Adds",
"an",
"annotation",
"to",
"an",
"injected",
"arg",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/decorators.py#L32-L53 |
231,311 | google/pinject | pinject/decorators.py | inject | def inject(arg_names=None, all_except=None):
"""Marks an initializer explicitly as injectable.
An initializer marked with @inject will be usable even when setting
only_use_explicit_bindings=True when calling new_object_graph().
This decorator can be used on an initializer or provider method to
separate the injectable args from the args that will be passed directly.
If arg_names is specified, then it must be a sequence, and only those args
are injected (and the rest must be passed directly). If all_except is
specified, then it must be a sequence, and only those args are passed
directly (and the rest must be specified). If neither arg_names nor
all_except are specified, then all args are injected (and none may be
passed directly).
arg_names or all_except, when specified, must not be empty and must
contain a (possibly empty, possibly non-proper) subset of the named args
of the decorated function. all_except may not be all args of the
decorated function (because then why call that provider method or
initialzer via Pinject?). At most one of arg_names and all_except may be
specified. A function may be decorated by @inject at most once.
"""
back_frame_loc = locations.get_back_frame_loc()
if arg_names is not None and all_except is not None:
raise errors.TooManyArgsToInjectDecoratorError(back_frame_loc)
for arg, arg_value in [('arg_names', arg_names), ('all_except', all_except)]:
if arg_value is not None:
if not arg_value:
raise errors.EmptySequenceArgError(back_frame_loc, arg)
if (not support.is_sequence(arg_value) or
support.is_string(arg_value)):
raise errors.WrongArgTypeError(
arg, 'sequence (of arg names)', type(arg_value).__name__)
if arg_names is None and all_except is None:
all_except = []
return _get_pinject_wrapper(
back_frame_loc, inject_arg_names=arg_names,
inject_all_except_arg_names=all_except) | python | def inject(arg_names=None, all_except=None):
back_frame_loc = locations.get_back_frame_loc()
if arg_names is not None and all_except is not None:
raise errors.TooManyArgsToInjectDecoratorError(back_frame_loc)
for arg, arg_value in [('arg_names', arg_names), ('all_except', all_except)]:
if arg_value is not None:
if not arg_value:
raise errors.EmptySequenceArgError(back_frame_loc, arg)
if (not support.is_sequence(arg_value) or
support.is_string(arg_value)):
raise errors.WrongArgTypeError(
arg, 'sequence (of arg names)', type(arg_value).__name__)
if arg_names is None and all_except is None:
all_except = []
return _get_pinject_wrapper(
back_frame_loc, inject_arg_names=arg_names,
inject_all_except_arg_names=all_except) | [
"def",
"inject",
"(",
"arg_names",
"=",
"None",
",",
"all_except",
"=",
"None",
")",
":",
"back_frame_loc",
"=",
"locations",
".",
"get_back_frame_loc",
"(",
")",
"if",
"arg_names",
"is",
"not",
"None",
"and",
"all_except",
"is",
"not",
"None",
":",
"raise... | Marks an initializer explicitly as injectable.
An initializer marked with @inject will be usable even when setting
only_use_explicit_bindings=True when calling new_object_graph().
This decorator can be used on an initializer or provider method to
separate the injectable args from the args that will be passed directly.
If arg_names is specified, then it must be a sequence, and only those args
are injected (and the rest must be passed directly). If all_except is
specified, then it must be a sequence, and only those args are passed
directly (and the rest must be specified). If neither arg_names nor
all_except are specified, then all args are injected (and none may be
passed directly).
arg_names or all_except, when specified, must not be empty and must
contain a (possibly empty, possibly non-proper) subset of the named args
of the decorated function. all_except may not be all args of the
decorated function (because then why call that provider method or
initialzer via Pinject?). At most one of arg_names and all_except may be
specified. A function may be decorated by @inject at most once. | [
"Marks",
"an",
"initializer",
"explicitly",
"as",
"injectable",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/decorators.py#L56-L94 |
231,312 | google/pinject | pinject/decorators.py | provides | def provides(arg_name=None, annotated_with=None, in_scope=None):
"""Modifies the binding of a provider method.
If arg_name is specified, then the created binding is for that arg name
instead of the one gotten from the provider method name (e.g., 'foo' from
'provide_foo').
If annotated_with is specified, then the created binding includes that
annotation object.
If in_scope is specified, then the created binding is in the scope with
that scope ID.
At least one of the args must be specified. A provider method may not be
decorated with @provides() twice.
Args:
arg_name: the name of the arg to annotate on the decorated function
annotated_with: an annotation object
in_scope: a scope ID
Returns:
a function that will decorate functions passed to it
"""
if arg_name is None and annotated_with is None and in_scope is None:
raise errors.EmptyProvidesDecoratorError(locations.get_back_frame_loc())
return _get_pinject_wrapper(locations.get_back_frame_loc(),
provider_arg_name=arg_name,
provider_annotated_with=annotated_with,
provider_in_scope_id=in_scope) | python | def provides(arg_name=None, annotated_with=None, in_scope=None):
if arg_name is None and annotated_with is None and in_scope is None:
raise errors.EmptyProvidesDecoratorError(locations.get_back_frame_loc())
return _get_pinject_wrapper(locations.get_back_frame_loc(),
provider_arg_name=arg_name,
provider_annotated_with=annotated_with,
provider_in_scope_id=in_scope) | [
"def",
"provides",
"(",
"arg_name",
"=",
"None",
",",
"annotated_with",
"=",
"None",
",",
"in_scope",
"=",
"None",
")",
":",
"if",
"arg_name",
"is",
"None",
"and",
"annotated_with",
"is",
"None",
"and",
"in_scope",
"is",
"None",
":",
"raise",
"errors",
"... | Modifies the binding of a provider method.
If arg_name is specified, then the created binding is for that arg name
instead of the one gotten from the provider method name (e.g., 'foo' from
'provide_foo').
If annotated_with is specified, then the created binding includes that
annotation object.
If in_scope is specified, then the created binding is in the scope with
that scope ID.
At least one of the args must be specified. A provider method may not be
decorated with @provides() twice.
Args:
arg_name: the name of the arg to annotate on the decorated function
annotated_with: an annotation object
in_scope: a scope ID
Returns:
a function that will decorate functions passed to it | [
"Modifies",
"the",
"binding",
"of",
"a",
"provider",
"method",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/decorators.py#L105-L133 |
231,313 | google/pinject | pinject/decorators.py | get_provider_fn_decorations | def get_provider_fn_decorations(provider_fn, default_arg_names):
"""Retrieves the provider method-relevant info set by decorators.
If any info wasn't set by decorators, then defaults are returned.
Args:
provider_fn: a (possibly decorated) provider function
default_arg_names: the (possibly empty) arg names to use if none were
specified via @provides()
Returns:
a sequence of ProviderDecoration
"""
if hasattr(provider_fn, _IS_WRAPPER_ATTR):
provider_decorations = getattr(provider_fn, _PROVIDER_DECORATIONS_ATTR)
if provider_decorations:
expanded_provider_decorations = []
for provider_decoration in provider_decorations:
# TODO(kurts): seems like default scope should be done at
# ProviderDecoration instantiation time.
if provider_decoration.in_scope_id is None:
provider_decoration.in_scope_id = scoping.DEFAULT_SCOPE
if provider_decoration.arg_name is not None:
expanded_provider_decorations.append(provider_decoration)
else:
expanded_provider_decorations.extend(
[ProviderDecoration(default_arg_name,
provider_decoration.annotated_with,
provider_decoration.in_scope_id)
for default_arg_name in default_arg_names])
return expanded_provider_decorations
return [ProviderDecoration(default_arg_name,
annotated_with=None,
in_scope_id=scoping.DEFAULT_SCOPE)
for default_arg_name in default_arg_names] | python | def get_provider_fn_decorations(provider_fn, default_arg_names):
if hasattr(provider_fn, _IS_WRAPPER_ATTR):
provider_decorations = getattr(provider_fn, _PROVIDER_DECORATIONS_ATTR)
if provider_decorations:
expanded_provider_decorations = []
for provider_decoration in provider_decorations:
# TODO(kurts): seems like default scope should be done at
# ProviderDecoration instantiation time.
if provider_decoration.in_scope_id is None:
provider_decoration.in_scope_id = scoping.DEFAULT_SCOPE
if provider_decoration.arg_name is not None:
expanded_provider_decorations.append(provider_decoration)
else:
expanded_provider_decorations.extend(
[ProviderDecoration(default_arg_name,
provider_decoration.annotated_with,
provider_decoration.in_scope_id)
for default_arg_name in default_arg_names])
return expanded_provider_decorations
return [ProviderDecoration(default_arg_name,
annotated_with=None,
in_scope_id=scoping.DEFAULT_SCOPE)
for default_arg_name in default_arg_names] | [
"def",
"get_provider_fn_decorations",
"(",
"provider_fn",
",",
"default_arg_names",
")",
":",
"if",
"hasattr",
"(",
"provider_fn",
",",
"_IS_WRAPPER_ATTR",
")",
":",
"provider_decorations",
"=",
"getattr",
"(",
"provider_fn",
",",
"_PROVIDER_DECORATIONS_ATTR",
")",
"i... | Retrieves the provider method-relevant info set by decorators.
If any info wasn't set by decorators, then defaults are returned.
Args:
provider_fn: a (possibly decorated) provider function
default_arg_names: the (possibly empty) arg names to use if none were
specified via @provides()
Returns:
a sequence of ProviderDecoration | [
"Retrieves",
"the",
"provider",
"method",
"-",
"relevant",
"info",
"set",
"by",
"decorators",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/decorators.py#L163-L196 |
231,314 | google/pinject | pinject/binding_keys.py | new | def new(arg_name, annotated_with=None):
"""Creates a BindingKey.
Args:
arg_name: the name of the bound arg
annotation: an Annotation, or None to create an unannotated binding key
Returns:
a new BindingKey
"""
if annotated_with is not None:
annotation = annotations.Annotation(annotated_with)
else:
annotation = annotations.NO_ANNOTATION
return BindingKey(arg_name, annotation) | python | def new(arg_name, annotated_with=None):
if annotated_with is not None:
annotation = annotations.Annotation(annotated_with)
else:
annotation = annotations.NO_ANNOTATION
return BindingKey(arg_name, annotation) | [
"def",
"new",
"(",
"arg_name",
",",
"annotated_with",
"=",
"None",
")",
":",
"if",
"annotated_with",
"is",
"not",
"None",
":",
"annotation",
"=",
"annotations",
".",
"Annotation",
"(",
"annotated_with",
")",
"else",
":",
"annotation",
"=",
"annotations",
"."... | Creates a BindingKey.
Args:
arg_name: the name of the bound arg
annotation: an Annotation, or None to create an unannotated binding key
Returns:
a new BindingKey | [
"Creates",
"a",
"BindingKey",
"."
] | 888acf1ccaaeeeba28a668ef9158c9dcc94405e1 | https://github.com/google/pinject/blob/888acf1ccaaeeeba28a668ef9158c9dcc94405e1/pinject/binding_keys.py#L55-L68 |
231,315 | vertica/vertica-python | vertica_python/vertica/messages/frontend_messages/crypt_windows.py | __setkey | def __setkey(key):
"""
Set up the key schedule from the encryption key.
"""
global C, D, KS, E
shifts = (1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1)
# First, generate C and D by permuting the key. The lower order bit of each
# 8-bit char is not used, so C and D are only 28 bits apiece.
for i in range(28):
C[i] = key[PC1_C[i] - 1]
D[i] = key[PC1_D[i] - 1]
for i in range(16):
# rotate
for k in range(shifts[i]):
temp = C[0]
for j in range(27):
C[j] = C[j + 1]
C[27] = temp
temp = D[0]
for j in range(27):
D[j] = D[j + 1]
D[27] = temp
# get Ki. Note C and D are concatenated
for j in range(24):
KS[i][j] = C[PC2_C[j] - 1]
KS[i][j + 24] = D[PC2_D[j] - 28 - 1]
# load E with the initial E bit selections
for i in range(48):
E[i] = e2[i] | python | def __setkey(key):
global C, D, KS, E
shifts = (1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1)
# First, generate C and D by permuting the key. The lower order bit of each
# 8-bit char is not used, so C and D are only 28 bits apiece.
for i in range(28):
C[i] = key[PC1_C[i] - 1]
D[i] = key[PC1_D[i] - 1]
for i in range(16):
# rotate
for k in range(shifts[i]):
temp = C[0]
for j in range(27):
C[j] = C[j + 1]
C[27] = temp
temp = D[0]
for j in range(27):
D[j] = D[j + 1]
D[27] = temp
# get Ki. Note C and D are concatenated
for j in range(24):
KS[i][j] = C[PC2_C[j] - 1]
KS[i][j + 24] = D[PC2_D[j] - 28 - 1]
# load E with the initial E bit selections
for i in range(48):
E[i] = e2[i] | [
"def",
"__setkey",
"(",
"key",
")",
":",
"global",
"C",
",",
"D",
",",
"KS",
",",
"E",
"shifts",
"=",
"(",
"1",
",",
"1",
",",
"2",
",",
"2",
",",
"2",
",",
"2",
",",
"2",
",",
"2",
",",
"1",
",",
"2",
",",
"2",
",",
"2",
",",
"2",
... | Set up the key schedule from the encryption key. | [
"Set",
"up",
"the",
"key",
"schedule",
"from",
"the",
"encryption",
"key",
"."
] | 5619c1b2b2eb5ea751c684b28648fc376b5be29c | https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/vertica/messages/frontend_messages/crypt_windows.py#L182-L218 |
231,316 | vertica/vertica-python | vertica_python/vertica/cursor.py | Cursor.nextset | def nextset(self):
"""
Skip to the next available result set, discarding any remaining rows
from the current result set.
If there are no more result sets, this method returns False. Otherwise,
it returns a True and subsequent calls to the fetch*() methods will
return rows from the next result set.
"""
# skip any data for this set if exists
self.flush_to_end_of_result()
if self._message is None:
return False
elif isinstance(self._message, END_OF_RESULT_RESPONSES):
# there might be another set, read next message to find out
self._message = self.connection.read_message()
if isinstance(self._message, messages.RowDescription):
self.description = [Column(fd, self.unicode_error) for fd in self._message.fields]
self._message = self.connection.read_message()
return True
elif isinstance(self._message, messages.BindComplete):
self._message = self.connection.read_message()
return True
elif isinstance(self._message, messages.ReadyForQuery):
return False
elif isinstance(self._message, END_OF_RESULT_RESPONSES):
# result of a DDL/transaction
return True
elif isinstance(self._message, messages.ErrorResponse):
raise errors.QueryError.from_error_response(self._message, self.operation)
else:
raise errors.MessageError(
'Unexpected nextset() state after END_OF_RESULT_RESPONSES: {0}'.format(self._message))
elif isinstance(self._message, messages.ReadyForQuery):
# no more sets left to be read
return False
else:
raise errors.MessageError('Unexpected nextset() state: {0}'.format(self._message)) | python | def nextset(self):
# skip any data for this set if exists
self.flush_to_end_of_result()
if self._message is None:
return False
elif isinstance(self._message, END_OF_RESULT_RESPONSES):
# there might be another set, read next message to find out
self._message = self.connection.read_message()
if isinstance(self._message, messages.RowDescription):
self.description = [Column(fd, self.unicode_error) for fd in self._message.fields]
self._message = self.connection.read_message()
return True
elif isinstance(self._message, messages.BindComplete):
self._message = self.connection.read_message()
return True
elif isinstance(self._message, messages.ReadyForQuery):
return False
elif isinstance(self._message, END_OF_RESULT_RESPONSES):
# result of a DDL/transaction
return True
elif isinstance(self._message, messages.ErrorResponse):
raise errors.QueryError.from_error_response(self._message, self.operation)
else:
raise errors.MessageError(
'Unexpected nextset() state after END_OF_RESULT_RESPONSES: {0}'.format(self._message))
elif isinstance(self._message, messages.ReadyForQuery):
# no more sets left to be read
return False
else:
raise errors.MessageError('Unexpected nextset() state: {0}'.format(self._message)) | [
"def",
"nextset",
"(",
"self",
")",
":",
"# skip any data for this set if exists",
"self",
".",
"flush_to_end_of_result",
"(",
")",
"if",
"self",
".",
"_message",
"is",
"None",
":",
"return",
"False",
"elif",
"isinstance",
"(",
"self",
".",
"_message",
",",
"E... | Skip to the next available result set, discarding any remaining rows
from the current result set.
If there are no more result sets, this method returns False. Otherwise,
it returns a True and subsequent calls to the fetch*() methods will
return rows from the next result set. | [
"Skip",
"to",
"the",
"next",
"available",
"result",
"set",
"discarding",
"any",
"remaining",
"rows",
"from",
"the",
"current",
"result",
"set",
"."
] | 5619c1b2b2eb5ea751c684b28648fc376b5be29c | https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/vertica/cursor.py#L261-L299 |
231,317 | vertica/vertica-python | vertica_python/vertica/cursor.py | Cursor._prepare | def _prepare(self, query):
"""
Send the query to be prepared to the server. The server will parse the
query and return some metadata.
"""
self._logger.info(u'Prepare a statement: [{}]'.format(query))
# Send Parse message to server
# We don't need to tell the server the parameter types yet
self.connection.write(messages.Parse(self.prepared_name, query, param_types=()))
# Send Describe message to server
self.connection.write(messages.Describe('prepared_statement', self.prepared_name))
self.connection.write(messages.Flush())
# Read expected message: ParseComplete
self._message = self.connection.read_expected_message(messages.ParseComplete, self._error_handler)
# Read expected message: ParameterDescription
self._message = self.connection.read_expected_message(messages.ParameterDescription, self._error_handler)
self._param_metadata = self._message.parameters
# Read expected message: RowDescription or NoData
self._message = self.connection.read_expected_message(
(messages.RowDescription, messages.NoData), self._error_handler)
if isinstance(self._message, messages.NoData):
self.description = None # response was NoData for a DDL/transaction PreparedStatement
else:
self.description = [Column(fd, self.unicode_error) for fd in self._message.fields]
# Read expected message: CommandDescription
self._message = self.connection.read_expected_message(messages.CommandDescription, self._error_handler)
if len(self._message.command_tag) == 0:
msg = 'The statement being prepared is empty'
self._logger.error(msg)
self.connection.write(messages.Sync())
raise errors.EmptyQueryError(msg)
self._logger.info('Finish preparing the statement') | python | def _prepare(self, query):
self._logger.info(u'Prepare a statement: [{}]'.format(query))
# Send Parse message to server
# We don't need to tell the server the parameter types yet
self.connection.write(messages.Parse(self.prepared_name, query, param_types=()))
# Send Describe message to server
self.connection.write(messages.Describe('prepared_statement', self.prepared_name))
self.connection.write(messages.Flush())
# Read expected message: ParseComplete
self._message = self.connection.read_expected_message(messages.ParseComplete, self._error_handler)
# Read expected message: ParameterDescription
self._message = self.connection.read_expected_message(messages.ParameterDescription, self._error_handler)
self._param_metadata = self._message.parameters
# Read expected message: RowDescription or NoData
self._message = self.connection.read_expected_message(
(messages.RowDescription, messages.NoData), self._error_handler)
if isinstance(self._message, messages.NoData):
self.description = None # response was NoData for a DDL/transaction PreparedStatement
else:
self.description = [Column(fd, self.unicode_error) for fd in self._message.fields]
# Read expected message: CommandDescription
self._message = self.connection.read_expected_message(messages.CommandDescription, self._error_handler)
if len(self._message.command_tag) == 0:
msg = 'The statement being prepared is empty'
self._logger.error(msg)
self.connection.write(messages.Sync())
raise errors.EmptyQueryError(msg)
self._logger.info('Finish preparing the statement') | [
"def",
"_prepare",
"(",
"self",
",",
"query",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"u'Prepare a statement: [{}]'",
".",
"format",
"(",
"query",
")",
")",
"# Send Parse message to server",
"# We don't need to tell the server the parameter types yet",
"self... | Send the query to be prepared to the server. The server will parse the
query and return some metadata. | [
"Send",
"the",
"query",
"to",
"be",
"prepared",
"to",
"the",
"server",
".",
"The",
"server",
"will",
"parse",
"the",
"query",
"and",
"return",
"some",
"metadata",
"."
] | 5619c1b2b2eb5ea751c684b28648fc376b5be29c | https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/vertica/cursor.py#L489-L526 |
231,318 | vertica/vertica-python | vertica_python/vertica/cursor.py | Cursor._execute_prepared_statement | def _execute_prepared_statement(self, list_of_parameter_values):
"""
Send multiple statement parameter sets to the server using the extended
query protocol. The server would bind and execute each set of parameter
values.
This function should not be called without first calling _prepare() to
prepare a statement.
"""
portal_name = ""
parameter_type_oids = [metadata['data_type_oid'] for metadata in self._param_metadata]
parameter_count = len(self._param_metadata)
try:
if len(list_of_parameter_values) == 0:
raise ValueError("Empty list/tuple, nothing to execute")
for parameter_values in list_of_parameter_values:
if parameter_values is None:
parameter_values = ()
self._logger.info(u'Bind parameters: {}'.format(parameter_values))
if len(parameter_values) != parameter_count:
msg = ("Invalid number of parameters for {}: {} given, {} expected"
.format(parameter_values, len(parameter_values), parameter_count))
raise ValueError(msg)
self.connection.write(messages.Bind(portal_name, self.prepared_name,
parameter_values, parameter_type_oids))
self.connection.write(messages.Execute(portal_name, 0))
self.connection.write(messages.Sync())
except Exception as e:
self._logger.error(str(e))
# the server will not send anything until we issue a sync
self.connection.write(messages.Sync())
self._message = self.connection.read_message()
raise
self.connection.write(messages.Flush())
# Read expected message: BindComplete
self.connection.read_expected_message(messages.BindComplete)
self._message = self.connection.read_message()
if isinstance(self._message, messages.ErrorResponse):
raise errors.QueryError.from_error_response(self._message, self.prepared_sql) | python | def _execute_prepared_statement(self, list_of_parameter_values):
portal_name = ""
parameter_type_oids = [metadata['data_type_oid'] for metadata in self._param_metadata]
parameter_count = len(self._param_metadata)
try:
if len(list_of_parameter_values) == 0:
raise ValueError("Empty list/tuple, nothing to execute")
for parameter_values in list_of_parameter_values:
if parameter_values is None:
parameter_values = ()
self._logger.info(u'Bind parameters: {}'.format(parameter_values))
if len(parameter_values) != parameter_count:
msg = ("Invalid number of parameters for {}: {} given, {} expected"
.format(parameter_values, len(parameter_values), parameter_count))
raise ValueError(msg)
self.connection.write(messages.Bind(portal_name, self.prepared_name,
parameter_values, parameter_type_oids))
self.connection.write(messages.Execute(portal_name, 0))
self.connection.write(messages.Sync())
except Exception as e:
self._logger.error(str(e))
# the server will not send anything until we issue a sync
self.connection.write(messages.Sync())
self._message = self.connection.read_message()
raise
self.connection.write(messages.Flush())
# Read expected message: BindComplete
self.connection.read_expected_message(messages.BindComplete)
self._message = self.connection.read_message()
if isinstance(self._message, messages.ErrorResponse):
raise errors.QueryError.from_error_response(self._message, self.prepared_sql) | [
"def",
"_execute_prepared_statement",
"(",
"self",
",",
"list_of_parameter_values",
")",
":",
"portal_name",
"=",
"\"\"",
"parameter_type_oids",
"=",
"[",
"metadata",
"[",
"'data_type_oid'",
"]",
"for",
"metadata",
"in",
"self",
".",
"_param_metadata",
"]",
"paramet... | Send multiple statement parameter sets to the server using the extended
query protocol. The server would bind and execute each set of parameter
values.
This function should not be called without first calling _prepare() to
prepare a statement. | [
"Send",
"multiple",
"statement",
"parameter",
"sets",
"to",
"the",
"server",
"using",
"the",
"extended",
"query",
"protocol",
".",
"The",
"server",
"would",
"bind",
"and",
"execute",
"each",
"set",
"of",
"parameter",
"values",
"."
] | 5619c1b2b2eb5ea751c684b28648fc376b5be29c | https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/vertica/cursor.py#L528-L570 |
231,319 | vertica/vertica-python | vertica_python/vertica/cursor.py | Cursor._close_prepared_statement | def _close_prepared_statement(self):
"""
Close the prepared statement on the server.
"""
self.prepared_sql = None
self.flush_to_query_ready()
self.connection.write(messages.Close('prepared_statement', self.prepared_name))
self.connection.write(messages.Flush())
self._message = self.connection.read_expected_message(messages.CloseComplete)
self.connection.write(messages.Sync()) | python | def _close_prepared_statement(self):
self.prepared_sql = None
self.flush_to_query_ready()
self.connection.write(messages.Close('prepared_statement', self.prepared_name))
self.connection.write(messages.Flush())
self._message = self.connection.read_expected_message(messages.CloseComplete)
self.connection.write(messages.Sync()) | [
"def",
"_close_prepared_statement",
"(",
"self",
")",
":",
"self",
".",
"prepared_sql",
"=",
"None",
"self",
".",
"flush_to_query_ready",
"(",
")",
"self",
".",
"connection",
".",
"write",
"(",
"messages",
".",
"Close",
"(",
"'prepared_statement'",
",",
"self"... | Close the prepared statement on the server. | [
"Close",
"the",
"prepared",
"statement",
"on",
"the",
"server",
"."
] | 5619c1b2b2eb5ea751c684b28648fc376b5be29c | https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/vertica/cursor.py#L572-L581 |
231,320 | vertica/vertica-python | vertica_python/vertica/log.py | VerticaLogging.ensure_dir_exists | def ensure_dir_exists(cls, filepath):
"""Ensure that a directory exists
If it doesn't exist, try to create it and protect against a race condition
if another process is doing the same.
"""
directory = os.path.dirname(filepath)
if directory != '' and not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise | python | def ensure_dir_exists(cls, filepath):
directory = os.path.dirname(filepath)
if directory != '' and not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise | [
"def",
"ensure_dir_exists",
"(",
"cls",
",",
"filepath",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filepath",
")",
"if",
"directory",
"!=",
"''",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"... | Ensure that a directory exists
If it doesn't exist, try to create it and protect against a race condition
if another process is doing the same. | [
"Ensure",
"that",
"a",
"directory",
"exists"
] | 5619c1b2b2eb5ea751c684b28648fc376b5be29c | https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/vertica/log.py#L59-L71 |
231,321 | vertica/vertica-python | vertica_python/datatypes.py | getTypeName | def getTypeName(data_type_oid, type_modifier):
"""Returns the base type name according to data_type_oid and type_modifier"""
if data_type_oid == VerticaType.BOOL:
return "Boolean"
elif data_type_oid == VerticaType.INT8:
return "Integer"
elif data_type_oid == VerticaType.FLOAT8:
return "Float"
elif data_type_oid == VerticaType.CHAR:
return "Char"
elif data_type_oid in (VerticaType.VARCHAR, VerticaType.UNKNOWN):
return "Varchar"
elif data_type_oid == VerticaType.LONGVARCHAR:
return "Long Varchar"
elif data_type_oid == VerticaType.DATE:
return "Date"
elif data_type_oid == VerticaType.TIME:
return "Time"
elif data_type_oid == VerticaType.TIMETZ:
return "TimeTz"
elif data_type_oid == VerticaType.TIMESTAMP:
return "Timestamp"
elif data_type_oid == VerticaType.TIMESTAMPTZ:
return "TimestampTz"
elif data_type_oid in (VerticaType.INTERVAL, VerticaType.INTERVALYM):
return "Interval " + getIntervalRange(data_type_oid, type_modifier)
elif data_type_oid == VerticaType.BINARY:
return "Binary"
elif data_type_oid == VerticaType.VARBINARY:
return "Varbinary"
elif data_type_oid == VerticaType.LONGVARBINARY:
return "Long Varbinary"
elif data_type_oid == VerticaType.NUMERIC:
return "Numeric"
elif data_type_oid == VerticaType.UUID:
return "Uuid"
else:
return "Unknown" | python | def getTypeName(data_type_oid, type_modifier):
if data_type_oid == VerticaType.BOOL:
return "Boolean"
elif data_type_oid == VerticaType.INT8:
return "Integer"
elif data_type_oid == VerticaType.FLOAT8:
return "Float"
elif data_type_oid == VerticaType.CHAR:
return "Char"
elif data_type_oid in (VerticaType.VARCHAR, VerticaType.UNKNOWN):
return "Varchar"
elif data_type_oid == VerticaType.LONGVARCHAR:
return "Long Varchar"
elif data_type_oid == VerticaType.DATE:
return "Date"
elif data_type_oid == VerticaType.TIME:
return "Time"
elif data_type_oid == VerticaType.TIMETZ:
return "TimeTz"
elif data_type_oid == VerticaType.TIMESTAMP:
return "Timestamp"
elif data_type_oid == VerticaType.TIMESTAMPTZ:
return "TimestampTz"
elif data_type_oid in (VerticaType.INTERVAL, VerticaType.INTERVALYM):
return "Interval " + getIntervalRange(data_type_oid, type_modifier)
elif data_type_oid == VerticaType.BINARY:
return "Binary"
elif data_type_oid == VerticaType.VARBINARY:
return "Varbinary"
elif data_type_oid == VerticaType.LONGVARBINARY:
return "Long Varbinary"
elif data_type_oid == VerticaType.NUMERIC:
return "Numeric"
elif data_type_oid == VerticaType.UUID:
return "Uuid"
else:
return "Unknown" | [
"def",
"getTypeName",
"(",
"data_type_oid",
",",
"type_modifier",
")",
":",
"if",
"data_type_oid",
"==",
"VerticaType",
".",
"BOOL",
":",
"return",
"\"Boolean\"",
"elif",
"data_type_oid",
"==",
"VerticaType",
".",
"INT8",
":",
"return",
"\"Integer\"",
"elif",
"d... | Returns the base type name according to data_type_oid and type_modifier | [
"Returns",
"the",
"base",
"type",
"name",
"according",
"to",
"data_type_oid",
"and",
"type_modifier"
] | 5619c1b2b2eb5ea751c684b28648fc376b5be29c | https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/datatypes.py#L163-L201 |
231,322 | vertica/vertica-python | vertica_python/datatypes.py | getIntervalRange | def getIntervalRange(data_type_oid, type_modifier):
"""Extracts an interval's range from the bits set in its type_modifier"""
if data_type_oid not in (VerticaType.INTERVAL, VerticaType.INTERVALYM):
raise ValueError("Invalid data type OID: {}".format(data_type_oid))
if type_modifier == -1: # assume the default
if data_type_oid == VerticaType.INTERVALYM:
return "Year to Month"
elif data_type_oid == VerticaType.INTERVAL:
return "Day to Second"
if data_type_oid == VerticaType.INTERVALYM: # Year/Month intervals
if (type_modifier & INTERVAL_MASK_YEAR2MONTH) == INTERVAL_MASK_YEAR2MONTH:
return "Year to Month"
elif (type_modifier & INTERVAL_MASK_YEAR) == INTERVAL_MASK_YEAR:
return "Year"
elif (type_modifier & INTERVAL_MASK_MONTH) == INTERVAL_MASK_MONTH:
return "Month"
else:
return "Year to Month"
if data_type_oid == VerticaType.INTERVAL: # Day/Time intervals
if (type_modifier & INTERVAL_MASK_DAY2SEC) == INTERVAL_MASK_DAY2SEC:
return "Day to Second"
elif (type_modifier & INTERVAL_MASK_DAY2MIN) == INTERVAL_MASK_DAY2MIN:
return "Day to Minute"
elif (type_modifier & INTERVAL_MASK_DAY2HOUR) == INTERVAL_MASK_DAY2HOUR:
return "Day to Hour"
elif (type_modifier & INTERVAL_MASK_DAY) == INTERVAL_MASK_DAY:
return "Day"
elif (type_modifier & INTERVAL_MASK_HOUR2SEC) == INTERVAL_MASK_HOUR2SEC:
return "Hour to Second"
elif (type_modifier & INTERVAL_MASK_HOUR2MIN) == INTERVAL_MASK_HOUR2MIN:
return "Hour to Minute"
elif (type_modifier & INTERVAL_MASK_HOUR) == INTERVAL_MASK_HOUR:
return "Hour"
elif (type_modifier & INTERVAL_MASK_MIN2SEC) == INTERVAL_MASK_MIN2SEC:
return "Minute to Second"
elif (type_modifier & INTERVAL_MASK_MINUTE) == INTERVAL_MASK_MINUTE:
return "Minute"
elif (type_modifier & INTERVAL_MASK_SECOND) == INTERVAL_MASK_SECOND:
return "Second"
else:
return "Day to Second" | python | def getIntervalRange(data_type_oid, type_modifier):
if data_type_oid not in (VerticaType.INTERVAL, VerticaType.INTERVALYM):
raise ValueError("Invalid data type OID: {}".format(data_type_oid))
if type_modifier == -1: # assume the default
if data_type_oid == VerticaType.INTERVALYM:
return "Year to Month"
elif data_type_oid == VerticaType.INTERVAL:
return "Day to Second"
if data_type_oid == VerticaType.INTERVALYM: # Year/Month intervals
if (type_modifier & INTERVAL_MASK_YEAR2MONTH) == INTERVAL_MASK_YEAR2MONTH:
return "Year to Month"
elif (type_modifier & INTERVAL_MASK_YEAR) == INTERVAL_MASK_YEAR:
return "Year"
elif (type_modifier & INTERVAL_MASK_MONTH) == INTERVAL_MASK_MONTH:
return "Month"
else:
return "Year to Month"
if data_type_oid == VerticaType.INTERVAL: # Day/Time intervals
if (type_modifier & INTERVAL_MASK_DAY2SEC) == INTERVAL_MASK_DAY2SEC:
return "Day to Second"
elif (type_modifier & INTERVAL_MASK_DAY2MIN) == INTERVAL_MASK_DAY2MIN:
return "Day to Minute"
elif (type_modifier & INTERVAL_MASK_DAY2HOUR) == INTERVAL_MASK_DAY2HOUR:
return "Day to Hour"
elif (type_modifier & INTERVAL_MASK_DAY) == INTERVAL_MASK_DAY:
return "Day"
elif (type_modifier & INTERVAL_MASK_HOUR2SEC) == INTERVAL_MASK_HOUR2SEC:
return "Hour to Second"
elif (type_modifier & INTERVAL_MASK_HOUR2MIN) == INTERVAL_MASK_HOUR2MIN:
return "Hour to Minute"
elif (type_modifier & INTERVAL_MASK_HOUR) == INTERVAL_MASK_HOUR:
return "Hour"
elif (type_modifier & INTERVAL_MASK_MIN2SEC) == INTERVAL_MASK_MIN2SEC:
return "Minute to Second"
elif (type_modifier & INTERVAL_MASK_MINUTE) == INTERVAL_MASK_MINUTE:
return "Minute"
elif (type_modifier & INTERVAL_MASK_SECOND) == INTERVAL_MASK_SECOND:
return "Second"
else:
return "Day to Second" | [
"def",
"getIntervalRange",
"(",
"data_type_oid",
",",
"type_modifier",
")",
":",
"if",
"data_type_oid",
"not",
"in",
"(",
"VerticaType",
".",
"INTERVAL",
",",
"VerticaType",
".",
"INTERVALYM",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid data type OID: {}\"",
... | Extracts an interval's range from the bits set in its type_modifier | [
"Extracts",
"an",
"interval",
"s",
"range",
"from",
"the",
"bits",
"set",
"in",
"its",
"type_modifier"
] | 5619c1b2b2eb5ea751c684b28648fc376b5be29c | https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/datatypes.py#L204-L248 |
231,323 | vertica/vertica-python | vertica_python/datatypes.py | getIntervalLeadingPrecision | def getIntervalLeadingPrecision(data_type_oid, type_modifier):
"""
Returns the leading precision for an interval, which is the largest number
of digits that can fit in the leading field of the interval.
All Year/Month intervals are defined in terms of months, even if the
type_modifier forbids months to be specified (i.e. INTERVAL YEAR).
Similarly, all Day/Time intervals are defined as a number of microseconds.
Because of this, interval types with shorter ranges will have a larger
leading precision.
For example, an INTERVAL DAY's leading precision is
((2^63)-1)/MICROSECS_PER_DAY, while an INTERVAL HOUR's leading precision
is ((2^63)-1)/MICROSECS_PER_HOUR
"""
interval_range = getIntervalRange(data_type_oid, type_modifier)
if interval_range in ("Year", "Year to Month"):
return 18
elif interval_range == "Month":
return 19
elif interval_range in ("Day", "Day to Hour", "Day to Minute", "Day to Second"):
return 9
elif interval_range in ("Hour", "Hour to Minute", "Hour to Second"):
return 10
elif interval_range in ("Minute", "Minute to Second"):
return 12
elif interval_range == "Second":
return 13
else:
raise ValueError("Invalid interval range: {}".format(interval_range)) | python | def getIntervalLeadingPrecision(data_type_oid, type_modifier):
interval_range = getIntervalRange(data_type_oid, type_modifier)
if interval_range in ("Year", "Year to Month"):
return 18
elif interval_range == "Month":
return 19
elif interval_range in ("Day", "Day to Hour", "Day to Minute", "Day to Second"):
return 9
elif interval_range in ("Hour", "Hour to Minute", "Hour to Second"):
return 10
elif interval_range in ("Minute", "Minute to Second"):
return 12
elif interval_range == "Second":
return 13
else:
raise ValueError("Invalid interval range: {}".format(interval_range)) | [
"def",
"getIntervalLeadingPrecision",
"(",
"data_type_oid",
",",
"type_modifier",
")",
":",
"interval_range",
"=",
"getIntervalRange",
"(",
"data_type_oid",
",",
"type_modifier",
")",
"if",
"interval_range",
"in",
"(",
"\"Year\"",
",",
"\"Year to Month\"",
")",
":",
... | Returns the leading precision for an interval, which is the largest number
of digits that can fit in the leading field of the interval.
All Year/Month intervals are defined in terms of months, even if the
type_modifier forbids months to be specified (i.e. INTERVAL YEAR).
Similarly, all Day/Time intervals are defined as a number of microseconds.
Because of this, interval types with shorter ranges will have a larger
leading precision.
For example, an INTERVAL DAY's leading precision is
((2^63)-1)/MICROSECS_PER_DAY, while an INTERVAL HOUR's leading precision
is ((2^63)-1)/MICROSECS_PER_HOUR | [
"Returns",
"the",
"leading",
"precision",
"for",
"an",
"interval",
"which",
"is",
"the",
"largest",
"number",
"of",
"digits",
"that",
"can",
"fit",
"in",
"the",
"leading",
"field",
"of",
"the",
"interval",
"."
] | 5619c1b2b2eb5ea751c684b28648fc376b5be29c | https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/datatypes.py#L251-L281 |
231,324 | vertica/vertica-python | vertica_python/datatypes.py | getPrecision | def getPrecision(data_type_oid, type_modifier):
"""
Returns the precision for the given Vertica type with consideration of
the type modifier.
For numerics, precision is the total number of digits (in base 10) that can
fit in the type.
For intervals, time and timestamps, precision is the number of digits to the
right of the decimal point in the seconds portion of the time.
The type modifier of -1 is used when the size of a type is unknown. In those
cases we assume the maximum possible size.
"""
if data_type_oid == VerticaType.NUMERIC:
if type_modifier == -1:
return 1024
return ((type_modifier - 4) >> 16) & 0xFFFF
elif data_type_oid in (VerticaType.TIME, VerticaType.TIMETZ,
VerticaType.TIMESTAMP, VerticaType.TIMESTAMPTZ,
VerticaType.INTERVAL, VerticaType.INTERVALYM):
if type_modifier == -1:
return 6
return type_modifier & 0xF
else:
return None | python | def getPrecision(data_type_oid, type_modifier):
if data_type_oid == VerticaType.NUMERIC:
if type_modifier == -1:
return 1024
return ((type_modifier - 4) >> 16) & 0xFFFF
elif data_type_oid in (VerticaType.TIME, VerticaType.TIMETZ,
VerticaType.TIMESTAMP, VerticaType.TIMESTAMPTZ,
VerticaType.INTERVAL, VerticaType.INTERVALYM):
if type_modifier == -1:
return 6
return type_modifier & 0xF
else:
return None | [
"def",
"getPrecision",
"(",
"data_type_oid",
",",
"type_modifier",
")",
":",
"if",
"data_type_oid",
"==",
"VerticaType",
".",
"NUMERIC",
":",
"if",
"type_modifier",
"==",
"-",
"1",
":",
"return",
"1024",
"return",
"(",
"(",
"type_modifier",
"-",
"4",
")",
... | Returns the precision for the given Vertica type with consideration of
the type modifier.
For numerics, precision is the total number of digits (in base 10) that can
fit in the type.
For intervals, time and timestamps, precision is the number of digits to the
right of the decimal point in the seconds portion of the time.
The type modifier of -1 is used when the size of a type is unknown. In those
cases we assume the maximum possible size. | [
"Returns",
"the",
"precision",
"for",
"the",
"given",
"Vertica",
"type",
"with",
"consideration",
"of",
"the",
"type",
"modifier",
"."
] | 5619c1b2b2eb5ea751c684b28648fc376b5be29c | https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/datatypes.py#L284-L310 |
231,325 | vertica/vertica-python | vertica_python/datatypes.py | getDisplaySize | def getDisplaySize(data_type_oid, type_modifier):
"""
Returns the column display size for the given Vertica type with
consideration of the type modifier.
The display size of a column is the maximum number of characters needed to
display data in character form.
"""
if data_type_oid == VerticaType.BOOL:
# T or F
return 1
elif data_type_oid == VerticaType.INT8:
# a sign and 19 digits if signed or 20 digits if unsigned
return 20
elif data_type_oid == VerticaType.FLOAT8:
# a sign, 15 digits, a decimal point, the letter E, a sign, and 3 digits
return 22
elif data_type_oid == VerticaType.NUMERIC:
# a sign, precision digits, and a decimal point
return getPrecision(data_type_oid, type_modifier) + 2
elif data_type_oid == VerticaType.DATE:
# yyyy-mm-dd, a space, and the calendar era (BC)
return 13
elif data_type_oid == VerticaType.TIME:
seconds_precision = getPrecision(data_type_oid, type_modifier)
if seconds_precision == 0:
# hh:mm:ss
return 8
else:
# hh:mm:ss.[fff...]
return 9 + seconds_precision
elif data_type_oid == VerticaType.TIMETZ:
seconds_precision = getPrecision(data_type_oid, type_modifier)
if seconds_precision == 0:
# hh:mm:ss, a sign, hh:mm
return 14
else:
# hh:mm:ss.[fff...], a sign, hh:mm
return 15 + seconds_precision
elif data_type_oid == VerticaType.TIMESTAMP:
seconds_precision = getPrecision(data_type_oid, type_modifier)
if seconds_precision == 0:
# yyyy-mm-dd hh:mm:ss, a space, and the calendar era (BC)
return 22
else:
# yyyy-mm-dd hh:mm:ss[.fff...], a space, and the calendar era (BC)
return 23 + seconds_precision
elif data_type_oid == VerticaType.TIMESTAMPTZ:
seconds_precision = getPrecision(data_type_oid, type_modifier)
if seconds_precision == 0:
# yyyy-mm-dd hh:mm:ss, a sign, hh:mm, a space, and the calendar era (BC)
return 28
else:
# yyyy-mm-dd hh:mm:ss.[fff...], a sign, hh:mm, a space, and the calendar era (BC)
return 29 + seconds_precision
elif data_type_oid in (VerticaType.INTERVAL, VerticaType.INTERVALYM):
leading_precision = getIntervalLeadingPrecision(data_type_oid, type_modifier)
seconds_precision = getPrecision(data_type_oid, type_modifier)
interval_range = getIntervalRange(data_type_oid, type_modifier)
if interval_range in ("Year", "Month", "Day", "Hour", "Minute"):
# a sign, [range...]
return 1 + leading_precision
elif interval_range in ("Day to Hour", "Year to Month", "Hour to Minute"):
# a sign, [dd...] hh; a sign, [yy...]-mm; a sign, [hh...]:mm
return 1 + leading_precision + 3
elif interval_range == "Day to Minute":
# a sign, [dd...] hh:mm
return 1 + leading_precision + 6
elif interval_range == "Second":
if seconds_precision == 0:
# a sign, [ss...]
return 1 + leading_precision
else:
# a sign, [ss...].[fff...]
return 1 + leading_precision + 1 + seconds_precision
elif interval_range == "Day to Second":
if seconds_precision == 0:
# a sign, [dd...] hh:mm:ss
return 1 + leading_precision + 9
else:
# a sign, [dd...] hh:mm:ss.[fff...]
return 1 + leading_precision + 10 + seconds_precision
elif interval_range == "Hour to Second":
if seconds_precision == 0:
# a sign, [hh...]:mm:ss
return 1 + leading_precision + 6
else:
# a sign, [hh...]:mm:ss.[fff...]
return 1 + leading_precision + 7 + seconds_precision
elif interval_range == "Minute to Second":
if seconds_precision == 0:
# a sign, [mm...]:ss
return 1 + leading_precision + 3
else:
# a sign, [mm...]:ss.[fff...]
return 1 + leading_precision + 4 + seconds_precision
elif data_type_oid == VerticaType.UUID:
# aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
return 36
elif data_type_oid in (VerticaType.CHAR,
VerticaType.VARCHAR,
VerticaType.BINARY,
VerticaType.VARBINARY,
VerticaType.UNKNOWN):
# the defined maximum octet length of the column
return MAX_STRING_LEN if type_modifier <= -1 else (type_modifier - 4)
elif data_type_oid in (VerticaType.LONGVARCHAR,
VerticaType.LONGVARBINARY):
return MAX_LONG_STRING_LEN if type_modifier <= -1 else (type_modifier - 4)
else:
return None | python | def getDisplaySize(data_type_oid, type_modifier):
if data_type_oid == VerticaType.BOOL:
# T or F
return 1
elif data_type_oid == VerticaType.INT8:
# a sign and 19 digits if signed or 20 digits if unsigned
return 20
elif data_type_oid == VerticaType.FLOAT8:
# a sign, 15 digits, a decimal point, the letter E, a sign, and 3 digits
return 22
elif data_type_oid == VerticaType.NUMERIC:
# a sign, precision digits, and a decimal point
return getPrecision(data_type_oid, type_modifier) + 2
elif data_type_oid == VerticaType.DATE:
# yyyy-mm-dd, a space, and the calendar era (BC)
return 13
elif data_type_oid == VerticaType.TIME:
seconds_precision = getPrecision(data_type_oid, type_modifier)
if seconds_precision == 0:
# hh:mm:ss
return 8
else:
# hh:mm:ss.[fff...]
return 9 + seconds_precision
elif data_type_oid == VerticaType.TIMETZ:
seconds_precision = getPrecision(data_type_oid, type_modifier)
if seconds_precision == 0:
# hh:mm:ss, a sign, hh:mm
return 14
else:
# hh:mm:ss.[fff...], a sign, hh:mm
return 15 + seconds_precision
elif data_type_oid == VerticaType.TIMESTAMP:
seconds_precision = getPrecision(data_type_oid, type_modifier)
if seconds_precision == 0:
# yyyy-mm-dd hh:mm:ss, a space, and the calendar era (BC)
return 22
else:
# yyyy-mm-dd hh:mm:ss[.fff...], a space, and the calendar era (BC)
return 23 + seconds_precision
elif data_type_oid == VerticaType.TIMESTAMPTZ:
seconds_precision = getPrecision(data_type_oid, type_modifier)
if seconds_precision == 0:
# yyyy-mm-dd hh:mm:ss, a sign, hh:mm, a space, and the calendar era (BC)
return 28
else:
# yyyy-mm-dd hh:mm:ss.[fff...], a sign, hh:mm, a space, and the calendar era (BC)
return 29 + seconds_precision
elif data_type_oid in (VerticaType.INTERVAL, VerticaType.INTERVALYM):
leading_precision = getIntervalLeadingPrecision(data_type_oid, type_modifier)
seconds_precision = getPrecision(data_type_oid, type_modifier)
interval_range = getIntervalRange(data_type_oid, type_modifier)
if interval_range in ("Year", "Month", "Day", "Hour", "Minute"):
# a sign, [range...]
return 1 + leading_precision
elif interval_range in ("Day to Hour", "Year to Month", "Hour to Minute"):
# a sign, [dd...] hh; a sign, [yy...]-mm; a sign, [hh...]:mm
return 1 + leading_precision + 3
elif interval_range == "Day to Minute":
# a sign, [dd...] hh:mm
return 1 + leading_precision + 6
elif interval_range == "Second":
if seconds_precision == 0:
# a sign, [ss...]
return 1 + leading_precision
else:
# a sign, [ss...].[fff...]
return 1 + leading_precision + 1 + seconds_precision
elif interval_range == "Day to Second":
if seconds_precision == 0:
# a sign, [dd...] hh:mm:ss
return 1 + leading_precision + 9
else:
# a sign, [dd...] hh:mm:ss.[fff...]
return 1 + leading_precision + 10 + seconds_precision
elif interval_range == "Hour to Second":
if seconds_precision == 0:
# a sign, [hh...]:mm:ss
return 1 + leading_precision + 6
else:
# a sign, [hh...]:mm:ss.[fff...]
return 1 + leading_precision + 7 + seconds_precision
elif interval_range == "Minute to Second":
if seconds_precision == 0:
# a sign, [mm...]:ss
return 1 + leading_precision + 3
else:
# a sign, [mm...]:ss.[fff...]
return 1 + leading_precision + 4 + seconds_precision
elif data_type_oid == VerticaType.UUID:
# aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
return 36
elif data_type_oid in (VerticaType.CHAR,
VerticaType.VARCHAR,
VerticaType.BINARY,
VerticaType.VARBINARY,
VerticaType.UNKNOWN):
# the defined maximum octet length of the column
return MAX_STRING_LEN if type_modifier <= -1 else (type_modifier - 4)
elif data_type_oid in (VerticaType.LONGVARCHAR,
VerticaType.LONGVARBINARY):
return MAX_LONG_STRING_LEN if type_modifier <= -1 else (type_modifier - 4)
else:
return None | [
"def",
"getDisplaySize",
"(",
"data_type_oid",
",",
"type_modifier",
")",
":",
"if",
"data_type_oid",
"==",
"VerticaType",
".",
"BOOL",
":",
"# T or F",
"return",
"1",
"elif",
"data_type_oid",
"==",
"VerticaType",
".",
"INT8",
":",
"# a sign and 19 digits if signed ... | Returns the column display size for the given Vertica type with
consideration of the type modifier.
The display size of a column is the maximum number of characters needed to
display data in character form. | [
"Returns",
"the",
"column",
"display",
"size",
"for",
"the",
"given",
"Vertica",
"type",
"with",
"consideration",
"of",
"the",
"type",
"modifier",
"."
] | 5619c1b2b2eb5ea751c684b28648fc376b5be29c | https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/datatypes.py#L325-L436 |
231,326 | baztian/jaydebeapi | jaydebeapi/__init__.py | _get_classpath | def _get_classpath():
"""Extract CLASSPATH from system environment as JPype doesn't seem
to respect that variable.
"""
try:
orig_cp = os.environ['CLASSPATH']
except KeyError:
return []
expanded_cp = []
for i in orig_cp.split(os.path.pathsep):
expanded_cp.extend(_jar_glob(i))
return expanded_cp | python | def _get_classpath():
try:
orig_cp = os.environ['CLASSPATH']
except KeyError:
return []
expanded_cp = []
for i in orig_cp.split(os.path.pathsep):
expanded_cp.extend(_jar_glob(i))
return expanded_cp | [
"def",
"_get_classpath",
"(",
")",
":",
"try",
":",
"orig_cp",
"=",
"os",
".",
"environ",
"[",
"'CLASSPATH'",
"]",
"except",
"KeyError",
":",
"return",
"[",
"]",
"expanded_cp",
"=",
"[",
"]",
"for",
"i",
"in",
"orig_cp",
".",
"split",
"(",
"os",
".",... | Extract CLASSPATH from system environment as JPype doesn't seem
to respect that variable. | [
"Extract",
"CLASSPATH",
"from",
"system",
"environment",
"as",
"JPype",
"doesn",
"t",
"seem",
"to",
"respect",
"that",
"variable",
"."
] | e99a05d5a84e9aa37ff0bac00bd5591336f54402 | https://github.com/baztian/jaydebeapi/blob/e99a05d5a84e9aa37ff0bac00bd5591336f54402/jaydebeapi/__init__.py#L201-L212 |
231,327 | baztian/jaydebeapi | jaydebeapi/__init__.py | Cursor._close_last | def _close_last(self):
"""Close the resultset and reset collected meta data.
"""
if self._rs:
self._rs.close()
self._rs = None
if self._prep:
self._prep.close()
self._prep = None
self._meta = None
self._description = None | python | def _close_last(self):
if self._rs:
self._rs.close()
self._rs = None
if self._prep:
self._prep.close()
self._prep = None
self._meta = None
self._description = None | [
"def",
"_close_last",
"(",
"self",
")",
":",
"if",
"self",
".",
"_rs",
":",
"self",
".",
"_rs",
".",
"close",
"(",
")",
"self",
".",
"_rs",
"=",
"None",
"if",
"self",
".",
"_prep",
":",
"self",
".",
"_prep",
".",
"close",
"(",
")",
"self",
".",... | Close the resultset and reset collected meta data. | [
"Close",
"the",
"resultset",
"and",
"reset",
"collected",
"meta",
"data",
"."
] | e99a05d5a84e9aa37ff0bac00bd5591336f54402 | https://github.com/baztian/jaydebeapi/blob/e99a05d5a84e9aa37ff0bac00bd5591336f54402/jaydebeapi/__init__.py#L471-L481 |
231,328 | opentracing/opentracing-python | opentracing/__init__.py | set_global_tracer | def set_global_tracer(value):
"""Sets the global tracer.
It is an error to pass ``None``.
:param value: the :class:`Tracer` used as global instance.
:type value: :class:`Tracer`
"""
if value is None:
raise ValueError('The global Tracer tracer cannot be None')
global tracer, is_tracer_registered
tracer = value
is_tracer_registered = True | python | def set_global_tracer(value):
if value is None:
raise ValueError('The global Tracer tracer cannot be None')
global tracer, is_tracer_registered
tracer = value
is_tracer_registered = True | [
"def",
"set_global_tracer",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'The global Tracer tracer cannot be None'",
")",
"global",
"tracer",
",",
"is_tracer_registered",
"tracer",
"=",
"value",
"is_tracer_registered",
"=",
... | Sets the global tracer.
It is an error to pass ``None``.
:param value: the :class:`Tracer` used as global instance.
:type value: :class:`Tracer` | [
"Sets",
"the",
"global",
"tracer",
".",
"It",
"is",
"an",
"error",
"to",
"pass",
"None",
"."
] | 5ceb76d67b01c1c3316cfed02371d7922830e317 | https://github.com/opentracing/opentracing-python/blob/5ceb76d67b01c1c3316cfed02371d7922830e317/opentracing/__init__.py#L50-L62 |
231,329 | opentracing/opentracing-python | opentracing/tracer.py | Tracer.inject | def inject(self, span_context, format, carrier):
"""Injects `span_context` into `carrier`.
The type of `carrier` is determined by `format`. See the
:class:`Format` class/namespace for the built-in OpenTracing formats.
Implementations *must* raise :exc:`UnsupportedFormatException` if
`format` is unknown or disallowed.
:param span_context: the :class:`SpanContext` instance to inject
:type span_context: SpanContext
:param format: a python object instance that represents a given
carrier format. `format` may be of any type, and `format` equality
is defined by python ``==`` equality.
:type format: Format
:param carrier: the format-specific carrier object to inject into
"""
if format in Tracer._supported_formats:
return
raise UnsupportedFormatException(format) | python | def inject(self, span_context, format, carrier):
if format in Tracer._supported_formats:
return
raise UnsupportedFormatException(format) | [
"def",
"inject",
"(",
"self",
",",
"span_context",
",",
"format",
",",
"carrier",
")",
":",
"if",
"format",
"in",
"Tracer",
".",
"_supported_formats",
":",
"return",
"raise",
"UnsupportedFormatException",
"(",
"format",
")"
] | Injects `span_context` into `carrier`.
The type of `carrier` is determined by `format`. See the
:class:`Format` class/namespace for the built-in OpenTracing formats.
Implementations *must* raise :exc:`UnsupportedFormatException` if
`format` is unknown or disallowed.
:param span_context: the :class:`SpanContext` instance to inject
:type span_context: SpanContext
:param format: a python object instance that represents a given
carrier format. `format` may be of any type, and `format` equality
is defined by python ``==`` equality.
:type format: Format
:param carrier: the format-specific carrier object to inject into | [
"Injects",
"span_context",
"into",
"carrier",
"."
] | 5ceb76d67b01c1c3316cfed02371d7922830e317 | https://github.com/opentracing/opentracing-python/blob/5ceb76d67b01c1c3316cfed02371d7922830e317/opentracing/tracer.py#L190-L210 |
231,330 | reingart/pyafipws | wsctg.py | WSCTG.__analizar_controles | def __analizar_controles(self, ret):
"Comprueba y extrae controles si existen en la respuesta XML"
if 'arrayControles' in ret:
controles = ret['arrayControles']
self.Controles = ["%(tipo)s: %(descripcion)s" % ctl['control']
for ctl in controles] | python | def __analizar_controles(self, ret):
"Comprueba y extrae controles si existen en la respuesta XML"
if 'arrayControles' in ret:
controles = ret['arrayControles']
self.Controles = ["%(tipo)s: %(descripcion)s" % ctl['control']
for ctl in controles] | [
"def",
"__analizar_controles",
"(",
"self",
",",
"ret",
")",
":",
"if",
"'arrayControles'",
"in",
"ret",
":",
"controles",
"=",
"ret",
"[",
"'arrayControles'",
"]",
"self",
".",
"Controles",
"=",
"[",
"\"%(tipo)s: %(descripcion)s\"",
"%",
"ctl",
"[",
"'control... | Comprueba y extrae controles si existen en la respuesta XML | [
"Comprueba",
"y",
"extrae",
"controles",
"si",
"existen",
"en",
"la",
"respuesta",
"XML"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsctg.py#L214-L219 |
231,331 | reingart/pyafipws | wsctg.py | WSCTG.Dummy | def Dummy(self):
"Obtener el estado de los servidores de la AFIP"
results = self.client.dummy()['response']
self.AppServerStatus = str(results['appserver'])
self.DbServerStatus = str(results['dbserver'])
self.AuthServerStatus = str(results['authserver']) | python | def Dummy(self):
"Obtener el estado de los servidores de la AFIP"
results = self.client.dummy()['response']
self.AppServerStatus = str(results['appserver'])
self.DbServerStatus = str(results['dbserver'])
self.AuthServerStatus = str(results['authserver']) | [
"def",
"Dummy",
"(",
"self",
")",
":",
"results",
"=",
"self",
".",
"client",
".",
"dummy",
"(",
")",
"[",
"'response'",
"]",
"self",
".",
"AppServerStatus",
"=",
"str",
"(",
"results",
"[",
"'appserver'",
"]",
")",
"self",
".",
"DbServerStatus",
"=",
... | Obtener el estado de los servidores de la AFIP | [
"Obtener",
"el",
"estado",
"de",
"los",
"servidores",
"de",
"la",
"AFIP"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsctg.py#L222-L227 |
231,332 | reingart/pyafipws | wsctg.py | WSCTG.SolicitarCTGInicial | def SolicitarCTGInicial(self, numero_carta_de_porte, codigo_especie,
cuit_canjeador, cuit_destino, cuit_destinatario, codigo_localidad_origen,
codigo_localidad_destino, codigo_cosecha, peso_neto_carga,
cant_horas=None, patente_vehiculo=None, cuit_transportista=None,
km_a_recorrer=None, remitente_comercial_como_canjeador=None,
cuit_corredor=None, remitente_comercial_como_productor=None,
turno=None,
**kwargs):
"Solicitar CTG Desde el Inicio"
# ajusto parámetros según validaciones de AFIP:
if not cuit_canjeador or int(cuit_canjeador) == 0:
cuit_canjeador = None # nulo
if not cuit_corredor or int(cuit_corredor) == 0:
cuit_corredor = None # nulo
if not remitente_comercial_como_canjeador:
remitente_comercial_como_canjeador = None
if not remitente_comercial_como_productor:
remitente_comercial_como_productor = None
if turno == '':
turno = None # nulo
ret = self.client.solicitarCTGInicial(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
datosSolicitarCTGInicial=dict(
cartaPorte=numero_carta_de_porte,
codigoEspecie=codigo_especie,
cuitCanjeador=cuit_canjeador or None,
remitenteComercialComoCanjeador=remitente_comercial_como_canjeador,
cuitDestino=cuit_destino,
cuitDestinatario=cuit_destinatario,
codigoLocalidadOrigen=codigo_localidad_origen,
codigoLocalidadDestino=codigo_localidad_destino,
codigoCosecha=codigo_cosecha,
pesoNeto=peso_neto_carga,
cuitTransportista=cuit_transportista,
cantHoras=cant_horas,
patente=patente_vehiculo,
kmARecorrer=km_a_recorrer,
cuitCorredor=cuit_corredor,
remitenteComercialcomoProductor=remitente_comercial_como_productor,
turno=turno,
)))['response']
self.__analizar_errores(ret)
self.Observaciones = ret['observacion']
datos = ret.get('datosSolicitarCTGResponse')
if datos:
self.CartaPorte = str(datos['cartaPorte'])
datos_ctg = datos.get('datosSolicitarCTG')
if datos_ctg:
self.NumeroCTG = str(datos_ctg['ctg'])
self.FechaHora = str(datos_ctg['fechaEmision'])
self.VigenciaDesde = str(datos_ctg['fechaVigenciaDesde'])
self.VigenciaHasta = str(datos_ctg['fechaVigenciaHasta'])
self.TarifaReferencia = str(datos_ctg.get('tarifaReferencia'))
self.__analizar_controles(datos)
return self.NumeroCTG or 0 | python | def SolicitarCTGInicial(self, numero_carta_de_porte, codigo_especie,
cuit_canjeador, cuit_destino, cuit_destinatario, codigo_localidad_origen,
codigo_localidad_destino, codigo_cosecha, peso_neto_carga,
cant_horas=None, patente_vehiculo=None, cuit_transportista=None,
km_a_recorrer=None, remitente_comercial_como_canjeador=None,
cuit_corredor=None, remitente_comercial_como_productor=None,
turno=None,
**kwargs):
"Solicitar CTG Desde el Inicio"
# ajusto parámetros según validaciones de AFIP:
if not cuit_canjeador or int(cuit_canjeador) == 0:
cuit_canjeador = None # nulo
if not cuit_corredor or int(cuit_corredor) == 0:
cuit_corredor = None # nulo
if not remitente_comercial_como_canjeador:
remitente_comercial_como_canjeador = None
if not remitente_comercial_como_productor:
remitente_comercial_como_productor = None
if turno == '':
turno = None # nulo
ret = self.client.solicitarCTGInicial(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
datosSolicitarCTGInicial=dict(
cartaPorte=numero_carta_de_porte,
codigoEspecie=codigo_especie,
cuitCanjeador=cuit_canjeador or None,
remitenteComercialComoCanjeador=remitente_comercial_como_canjeador,
cuitDestino=cuit_destino,
cuitDestinatario=cuit_destinatario,
codigoLocalidadOrigen=codigo_localidad_origen,
codigoLocalidadDestino=codigo_localidad_destino,
codigoCosecha=codigo_cosecha,
pesoNeto=peso_neto_carga,
cuitTransportista=cuit_transportista,
cantHoras=cant_horas,
patente=patente_vehiculo,
kmARecorrer=km_a_recorrer,
cuitCorredor=cuit_corredor,
remitenteComercialcomoProductor=remitente_comercial_como_productor,
turno=turno,
)))['response']
self.__analizar_errores(ret)
self.Observaciones = ret['observacion']
datos = ret.get('datosSolicitarCTGResponse')
if datos:
self.CartaPorte = str(datos['cartaPorte'])
datos_ctg = datos.get('datosSolicitarCTG')
if datos_ctg:
self.NumeroCTG = str(datos_ctg['ctg'])
self.FechaHora = str(datos_ctg['fechaEmision'])
self.VigenciaDesde = str(datos_ctg['fechaVigenciaDesde'])
self.VigenciaHasta = str(datos_ctg['fechaVigenciaHasta'])
self.TarifaReferencia = str(datos_ctg.get('tarifaReferencia'))
self.__analizar_controles(datos)
return self.NumeroCTG or 0 | [
"def",
"SolicitarCTGInicial",
"(",
"self",
",",
"numero_carta_de_porte",
",",
"codigo_especie",
",",
"cuit_canjeador",
",",
"cuit_destino",
",",
"cuit_destinatario",
",",
"codigo_localidad_origen",
",",
"codigo_localidad_destino",
",",
"codigo_cosecha",
",",
"peso_neto_carg... | Solicitar CTG Desde el Inicio | [
"Solicitar",
"CTG",
"Desde",
"el",
"Inicio"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsctg.py#L267-L324 |
231,333 | reingart/pyafipws | wsctg.py | WSCTG.SolicitarCTGDatoPendiente | def SolicitarCTGDatoPendiente(self, numero_carta_de_porte, cant_horas,
patente_vehiculo, cuit_transportista, patente=None, turno=None):
"Solicitud que permite completar los datos faltantes de un Pre-CTG "
"generado anteriormente a través de la operación solicitarCTGInicial"
ret = self.client.solicitarCTGDatoPendiente(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
datosSolicitarCTGDatoPendiente=dict(
cartaPorte=numero_carta_de_porte,
cuitTransportista=cuit_transportista,
cantHoras=cant_horas,
patente=patente,
turno=turno,
)))['response']
self.__analizar_errores(ret)
self.Observaciones = ret['observacion']
datos = ret.get('datosSolicitarCTGResponse')
if datos:
self.CartaPorte = str(datos['cartaPorte'])
datos_ctg = datos.get('datosSolicitarCTG')
if datos_ctg:
self.NumeroCTG = str(datos_ctg['ctg'])
self.FechaHora = str(datos_ctg['fechaEmision'])
self.VigenciaDesde = str(datos_ctg['fechaVigenciaDesde'])
self.VigenciaHasta = str(datos_ctg['fechaVigenciaHasta'])
self.TarifaReferencia = str(datos_ctg.get('tarifaReferencia'))
self.__analizar_controles(datos)
return self.NumeroCTG | python | def SolicitarCTGDatoPendiente(self, numero_carta_de_porte, cant_horas,
patente_vehiculo, cuit_transportista, patente=None, turno=None):
"Solicitud que permite completar los datos faltantes de un Pre-CTG "
"generado anteriormente a través de la operación solicitarCTGInicial"
ret = self.client.solicitarCTGDatoPendiente(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
datosSolicitarCTGDatoPendiente=dict(
cartaPorte=numero_carta_de_porte,
cuitTransportista=cuit_transportista,
cantHoras=cant_horas,
patente=patente,
turno=turno,
)))['response']
self.__analizar_errores(ret)
self.Observaciones = ret['observacion']
datos = ret.get('datosSolicitarCTGResponse')
if datos:
self.CartaPorte = str(datos['cartaPorte'])
datos_ctg = datos.get('datosSolicitarCTG')
if datos_ctg:
self.NumeroCTG = str(datos_ctg['ctg'])
self.FechaHora = str(datos_ctg['fechaEmision'])
self.VigenciaDesde = str(datos_ctg['fechaVigenciaDesde'])
self.VigenciaHasta = str(datos_ctg['fechaVigenciaHasta'])
self.TarifaReferencia = str(datos_ctg.get('tarifaReferencia'))
self.__analizar_controles(datos)
return self.NumeroCTG | [
"def",
"SolicitarCTGDatoPendiente",
"(",
"self",
",",
"numero_carta_de_porte",
",",
"cant_horas",
",",
"patente_vehiculo",
",",
"cuit_transportista",
",",
"patente",
"=",
"None",
",",
"turno",
"=",
"None",
")",
":",
"\"generado anteriormente a través de la operación solic... | Solicitud que permite completar los datos faltantes de un Pre-CTG | [
"Solicitud",
"que",
"permite",
"completar",
"los",
"datos",
"faltantes",
"de",
"un",
"Pre",
"-",
"CTG"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsctg.py#L327-L355 |
231,334 | reingart/pyafipws | wsctg.py | WSCTG.ConfirmarArribo | def ConfirmarArribo(self, numero_carta_de_porte, numero_ctg,
cuit_transportista, peso_neto_carga,
consumo_propio, establecimiento=None, cuit_chofer=None,
**kwargs):
"Confirma arribo CTG"
ret = self.client.confirmarArribo(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
datosConfirmarArribo=dict(
cartaPorte=numero_carta_de_porte,
ctg=numero_ctg,
cuitTransportista=cuit_transportista,
cuitChofer=cuit_chofer,
cantKilosCartaPorte=peso_neto_carga,
consumoPropio=consumo_propio,
establecimiento=establecimiento,
)))['response']
self.__analizar_errores(ret)
datos = ret.get('datosResponse')
if datos:
self.CartaPorte = str(datos['cartaPorte'])
self.NumeroCTG = str(datos['ctg'])
self.FechaHora = str(datos['fechaHora'])
self.CodigoTransaccion = str(datos['codigoOperacion'])
self.Observaciones = ""
return self.CodigoTransaccion | python | def ConfirmarArribo(self, numero_carta_de_porte, numero_ctg,
cuit_transportista, peso_neto_carga,
consumo_propio, establecimiento=None, cuit_chofer=None,
**kwargs):
"Confirma arribo CTG"
ret = self.client.confirmarArribo(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
datosConfirmarArribo=dict(
cartaPorte=numero_carta_de_porte,
ctg=numero_ctg,
cuitTransportista=cuit_transportista,
cuitChofer=cuit_chofer,
cantKilosCartaPorte=peso_neto_carga,
consumoPropio=consumo_propio,
establecimiento=establecimiento,
)))['response']
self.__analizar_errores(ret)
datos = ret.get('datosResponse')
if datos:
self.CartaPorte = str(datos['cartaPorte'])
self.NumeroCTG = str(datos['ctg'])
self.FechaHora = str(datos['fechaHora'])
self.CodigoTransaccion = str(datos['codigoOperacion'])
self.Observaciones = ""
return self.CodigoTransaccion | [
"def",
"ConfirmarArribo",
"(",
"self",
",",
"numero_carta_de_porte",
",",
"numero_ctg",
",",
"cuit_transportista",
",",
"peso_neto_carga",
",",
"consumo_propio",
",",
"establecimiento",
"=",
"None",
",",
"cuit_chofer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
... | Confirma arribo CTG | [
"Confirma",
"arribo",
"CTG"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsctg.py#L358-L384 |
231,335 | reingart/pyafipws | wsctg.py | WSCTG.ConfirmarDefinitivo | def ConfirmarDefinitivo(self, numero_carta_de_porte, numero_ctg,
establecimiento=None, codigo_cosecha=None, peso_neto_carga=None,
**kwargs):
"Confirma arribo definitivo CTG"
ret = self.client.confirmarDefinitivo(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
datosConfirmarDefinitivo=dict(
cartaPorte=numero_carta_de_porte,
ctg=numero_ctg,
establecimiento=establecimiento,
codigoCosecha=codigo_cosecha,
pesoNeto=peso_neto_carga,
)))['response']
self.__analizar_errores(ret)
datos = ret.get('datosResponse')
if datos:
self.CartaPorte = str(datos['cartaPorte'])
self.NumeroCTG = str(datos['ctg'])
self.FechaHora = str(datos['fechaHora'])
self.CodigoTransaccion = str(datos.get('codigoOperacion', ""))
self.Observaciones = ""
return self.CodigoTransaccion | python | def ConfirmarDefinitivo(self, numero_carta_de_porte, numero_ctg,
establecimiento=None, codigo_cosecha=None, peso_neto_carga=None,
**kwargs):
"Confirma arribo definitivo CTG"
ret = self.client.confirmarDefinitivo(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
datosConfirmarDefinitivo=dict(
cartaPorte=numero_carta_de_porte,
ctg=numero_ctg,
establecimiento=establecimiento,
codigoCosecha=codigo_cosecha,
pesoNeto=peso_neto_carga,
)))['response']
self.__analizar_errores(ret)
datos = ret.get('datosResponse')
if datos:
self.CartaPorte = str(datos['cartaPorte'])
self.NumeroCTG = str(datos['ctg'])
self.FechaHora = str(datos['fechaHora'])
self.CodigoTransaccion = str(datos.get('codigoOperacion', ""))
self.Observaciones = ""
return self.CodigoTransaccion | [
"def",
"ConfirmarDefinitivo",
"(",
"self",
",",
"numero_carta_de_porte",
",",
"numero_ctg",
",",
"establecimiento",
"=",
"None",
",",
"codigo_cosecha",
"=",
"None",
",",
"peso_neto_carga",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"self",
"... | Confirma arribo definitivo CTG | [
"Confirma",
"arribo",
"definitivo",
"CTG"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsctg.py#L387-L410 |
231,336 | reingart/pyafipws | wsctg.py | WSCTG.RegresarAOrigenCTGRechazado | def RegresarAOrigenCTGRechazado(self, numero_carta_de_porte, numero_ctg,
km_a_recorrer=None,
**kwargs):
"Al consultar los CTGs rechazados se puede Regresar a Origen"
ret = self.client.regresarAOrigenCTGRechazado(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
datosRegresarAOrigenCTGRechazado=dict(
cartaPorte=numero_carta_de_porte,
ctg=numero_ctg, kmARecorrer=km_a_recorrer,
)))['response']
self.__analizar_errores(ret)
datos = ret.get('datosResponse')
if datos:
self.CartaPorte = str(datos['cartaPorte'])
self.NumeroCTG = str(datos['ctg'])
self.FechaHora = str(datos['fechaHora'])
self.CodigoTransaccion = str(datos['codigoOperacion'])
self.Observaciones = ""
return self.CodigoTransaccion | python | def RegresarAOrigenCTGRechazado(self, numero_carta_de_porte, numero_ctg,
km_a_recorrer=None,
**kwargs):
"Al consultar los CTGs rechazados se puede Regresar a Origen"
ret = self.client.regresarAOrigenCTGRechazado(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
datosRegresarAOrigenCTGRechazado=dict(
cartaPorte=numero_carta_de_porte,
ctg=numero_ctg, kmARecorrer=km_a_recorrer,
)))['response']
self.__analizar_errores(ret)
datos = ret.get('datosResponse')
if datos:
self.CartaPorte = str(datos['cartaPorte'])
self.NumeroCTG = str(datos['ctg'])
self.FechaHora = str(datos['fechaHora'])
self.CodigoTransaccion = str(datos['codigoOperacion'])
self.Observaciones = ""
return self.CodigoTransaccion | [
"def",
"RegresarAOrigenCTGRechazado",
"(",
"self",
",",
"numero_carta_de_porte",
",",
"numero_ctg",
",",
"km_a_recorrer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"regresarAOrigenCTGRechazado",
"(",
"request",
"=",
... | Al consultar los CTGs rechazados se puede Regresar a Origen | [
"Al",
"consultar",
"los",
"CTGs",
"rechazados",
"se",
"puede",
"Regresar",
"a",
"Origen"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsctg.py#L413-L433 |
231,337 | reingart/pyafipws | wsctg.py | WSCTG.ConsultarCTGActivosPorPatente | def ConsultarCTGActivosPorPatente(self, patente="ZZZ999"):
"Consulta de CTGs activos por patente"
ret = self.client.consultarCTGActivosPorPatente(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
patente=patente,
))['response']
self.__analizar_errores(ret)
datos = ret.get('arrayConsultarCTGActivosPorPatenteResponse')
if datos:
self.DatosCTG = datos
self.LeerDatosCTG(pop=False)
return True
else:
self.DatosCTG = []
return False | python | def ConsultarCTGActivosPorPatente(self, patente="ZZZ999"):
"Consulta de CTGs activos por patente"
ret = self.client.consultarCTGActivosPorPatente(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
patente=patente,
))['response']
self.__analizar_errores(ret)
datos = ret.get('arrayConsultarCTGActivosPorPatenteResponse')
if datos:
self.DatosCTG = datos
self.LeerDatosCTG(pop=False)
return True
else:
self.DatosCTG = []
return False | [
"def",
"ConsultarCTGActivosPorPatente",
"(",
"self",
",",
"patente",
"=",
"\"ZZZ999\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"consultarCTGActivosPorPatente",
"(",
"request",
"=",
"dict",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token... | Consulta de CTGs activos por patente | [
"Consulta",
"de",
"CTGs",
"activos",
"por",
"patente"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsctg.py#L512-L528 |
231,338 | reingart/pyafipws | wslpg.py | WSLPG.ConsultarLiquidacionesPorContrato | def ConsultarLiquidacionesPorContrato(self, nro_contrato=None,
cuit_comprador=None,
cuit_vendedor=None,
cuit_corredor=None,
cod_grano=None,
**kwargs):
"Obtener los COE de liquidaciones relacionadas a un contrato"
ret = self.client.liquidacionPorContratoConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
nroContrato=nro_contrato,
cuitComprador=cuit_comprador,
cuitVendedor=cuit_vendedor,
cuitCorredor=cuit_corredor,
codGrano=cod_grano,
)
ret = ret['liqPorContratoCons']
self.__analizar_errores(ret)
if 'coeRelacionados' in ret:
# analizo la respuesta = [{'coe': "...."}]
self.DatosLiquidacion = sorted(ret['coeRelacionados'])
# establezco el primer COE
self.LeerDatosLiquidacion()
return True | python | def ConsultarLiquidacionesPorContrato(self, nro_contrato=None,
cuit_comprador=None,
cuit_vendedor=None,
cuit_corredor=None,
cod_grano=None,
**kwargs):
"Obtener los COE de liquidaciones relacionadas a un contrato"
ret = self.client.liquidacionPorContratoConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
nroContrato=nro_contrato,
cuitComprador=cuit_comprador,
cuitVendedor=cuit_vendedor,
cuitCorredor=cuit_corredor,
codGrano=cod_grano,
)
ret = ret['liqPorContratoCons']
self.__analizar_errores(ret)
if 'coeRelacionados' in ret:
# analizo la respuesta = [{'coe': "...."}]
self.DatosLiquidacion = sorted(ret['coeRelacionados'])
# establezco el primer COE
self.LeerDatosLiquidacion()
return True | [
"def",
"ConsultarLiquidacionesPorContrato",
"(",
"self",
",",
"nro_contrato",
"=",
"None",
",",
"cuit_comprador",
"=",
"None",
",",
"cuit_vendedor",
"=",
"None",
",",
"cuit_corredor",
"=",
"None",
",",
"cod_grano",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
... | Obtener los COE de liquidaciones relacionadas a un contrato | [
"Obtener",
"los",
"COE",
"de",
"liquidaciones",
"relacionadas",
"a",
"un",
"contrato"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2100-L2124 |
231,339 | reingart/pyafipws | wslpg.py | WSLPG.ConsultarCertificacion | def ConsultarCertificacion(self, pto_emision=None, nro_orden=None,
coe=None, pdf=None):
"Consulta una certificacion por No de orden o COE"
if coe:
ret = self.client.cgConsultarXCoe(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
coe=coe,
pdf='S' if pdf else 'N',
)
else:
ret = self.client.cgConsultarXNroOrden(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
ptoEmision=pto_emision,
nroOrden=nro_orden,
)
ret = ret['oReturn']
self.__analizar_errores(ret)
if 'autorizacion' in ret:
self.AnalizarAutorizarCertificadoResp(ret)
# guardo el PDF si se indico archivo y vino en la respuesta:
if pdf and 'pdf' in ret:
open(pdf, "wb").write(ret['pdf'])
return True | python | def ConsultarCertificacion(self, pto_emision=None, nro_orden=None,
coe=None, pdf=None):
"Consulta una certificacion por No de orden o COE"
if coe:
ret = self.client.cgConsultarXCoe(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
coe=coe,
pdf='S' if pdf else 'N',
)
else:
ret = self.client.cgConsultarXNroOrden(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
ptoEmision=pto_emision,
nroOrden=nro_orden,
)
ret = ret['oReturn']
self.__analizar_errores(ret)
if 'autorizacion' in ret:
self.AnalizarAutorizarCertificadoResp(ret)
# guardo el PDF si se indico archivo y vino en la respuesta:
if pdf and 'pdf' in ret:
open(pdf, "wb").write(ret['pdf'])
return True | [
"def",
"ConsultarCertificacion",
"(",
"self",
",",
"pto_emision",
"=",
"None",
",",
"nro_orden",
"=",
"None",
",",
"coe",
"=",
"None",
",",
"pdf",
"=",
"None",
")",
":",
"if",
"coe",
":",
"ret",
"=",
"self",
".",
"client",
".",
"cgConsultarXCoe",
"(",
... | Consulta una certificacion por No de orden o COE | [
"Consulta",
"una",
"certificacion",
"por",
"No",
"de",
"orden",
"o",
"COE"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2248-L2274 |
231,340 | reingart/pyafipws | wslpg.py | WSLPG.ConsultarTipoDeduccion | def ConsultarTipoDeduccion(self, sep="||"):
"Consulta de tipos de Deducciones"
ret = self.client.tipoDeduccionConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['tipoDeduccionReturn']
self.__analizar_errores(ret)
array = ret.get('tiposDeduccion', [])
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array] | python | def ConsultarTipoDeduccion(self, sep="||"):
"Consulta de tipos de Deducciones"
ret = self.client.tipoDeduccionConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['tipoDeduccionReturn']
self.__analizar_errores(ret)
array = ret.get('tiposDeduccion', [])
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array] | [
"def",
"ConsultarTipoDeduccion",
"(",
"self",
",",
"sep",
"=",
"\"||\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"tipoDeduccionConsultar",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'",
":",
"self",
".",
"Sign",
"... | Consulta de tipos de Deducciones | [
"Consulta",
"de",
"tipos",
"de",
"Deducciones"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2489-L2501 |
231,341 | reingart/pyafipws | wslpg.py | WSLPG.ConsultarTipoRetencion | def ConsultarTipoRetencion(self, sep="||"):
"Consulta de tipos de Retenciones."
ret = self.client.tipoRetencionConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['tipoRetencionReturn']
self.__analizar_errores(ret)
array = ret.get('tiposRetencion', [])
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array] | python | def ConsultarTipoRetencion(self, sep="||"):
"Consulta de tipos de Retenciones."
ret = self.client.tipoRetencionConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['tipoRetencionReturn']
self.__analizar_errores(ret)
array = ret.get('tiposRetencion', [])
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array] | [
"def",
"ConsultarTipoRetencion",
"(",
"self",
",",
"sep",
"=",
"\"||\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"tipoRetencionConsultar",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'",
":",
"self",
".",
"Sign",
"... | Consulta de tipos de Retenciones. | [
"Consulta",
"de",
"tipos",
"de",
"Retenciones",
"."
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2503-L2515 |
231,342 | reingart/pyafipws | wslpg.py | WSLPG.ConsultarPuerto | def ConsultarPuerto(self, sep="||"):
"Consulta de Puertos habilitados"
ret = self.client.puertoConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['puertoReturn']
self.__analizar_errores(ret)
array = ret.get('puertos', [])
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array] | python | def ConsultarPuerto(self, sep="||"):
"Consulta de Puertos habilitados"
ret = self.client.puertoConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['puertoReturn']
self.__analizar_errores(ret)
array = ret.get('puertos', [])
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array] | [
"def",
"ConsultarPuerto",
"(",
"self",
",",
"sep",
"=",
"\"||\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"puertoConsultar",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'",
":",
"self",
".",
"Sign",
",",
"'cuit'"... | Consulta de Puertos habilitados | [
"Consulta",
"de",
"Puertos",
"habilitados"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2517-L2529 |
231,343 | reingart/pyafipws | wslpg.py | WSLPG.ConsultarTipoActividad | def ConsultarTipoActividad(self, sep="||"):
"Consulta de Tipos de Actividad."
ret = self.client.tipoActividadConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['tipoActividadReturn']
self.__analizar_errores(ret)
array = ret.get('tiposActividad', [])
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array] | python | def ConsultarTipoActividad(self, sep="||"):
"Consulta de Tipos de Actividad."
ret = self.client.tipoActividadConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['tipoActividadReturn']
self.__analizar_errores(ret)
array = ret.get('tiposActividad', [])
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array] | [
"def",
"ConsultarTipoActividad",
"(",
"self",
",",
"sep",
"=",
"\"||\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"tipoActividadConsultar",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'",
":",
"self",
".",
"Sign",
"... | Consulta de Tipos de Actividad. | [
"Consulta",
"de",
"Tipos",
"de",
"Actividad",
"."
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2531-L2543 |
231,344 | reingart/pyafipws | wslpg.py | WSLPG.ConsultarTipoActividadRepresentado | def ConsultarTipoActividadRepresentado(self, sep="||"):
"Consulta de Tipos de Actividad inscripta en el RUOCA."
try:
ret = self.client.tipoActividadRepresentadoConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['tipoActividadReturn']
self.__analizar_errores(ret)
array = ret.get('tiposActividad', [])
self.Excepcion = self.Traceback = ""
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array]
except Exception:
ex = utils.exception_info()
self.Excepcion = ex['msg']
self.Traceback = ex['tb']
if sep:
return ["ERROR"] | python | def ConsultarTipoActividadRepresentado(self, sep="||"):
"Consulta de Tipos de Actividad inscripta en el RUOCA."
try:
ret = self.client.tipoActividadRepresentadoConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['tipoActividadReturn']
self.__analizar_errores(ret)
array = ret.get('tiposActividad', [])
self.Excepcion = self.Traceback = ""
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array]
except Exception:
ex = utils.exception_info()
self.Excepcion = ex['msg']
self.Traceback = ex['tb']
if sep:
return ["ERROR"] | [
"def",
"ConsultarTipoActividadRepresentado",
"(",
"self",
",",
"sep",
"=",
"\"||\"",
")",
":",
"try",
":",
"ret",
"=",
"self",
".",
"client",
".",
"tipoActividadRepresentadoConsultar",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'... | Consulta de Tipos de Actividad inscripta en el RUOCA. | [
"Consulta",
"de",
"Tipos",
"de",
"Actividad",
"inscripta",
"en",
"el",
"RUOCA",
"."
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2545-L2565 |
231,345 | reingart/pyafipws | wslpg.py | WSLPG.ConsultarProvincias | def ConsultarProvincias(self, sep="||"):
"Consulta las provincias habilitadas"
ret = self.client.provinciasConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['provinciasReturn']
self.__analizar_errores(ret)
array = ret.get('provincias', [])
if sep is None:
return dict([(int(it['codigoDescripcion']['codigo']),
it['codigoDescripcion']['descripcion'])
for it in array])
else:
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array] | python | def ConsultarProvincias(self, sep="||"):
"Consulta las provincias habilitadas"
ret = self.client.provinciasConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['provinciasReturn']
self.__analizar_errores(ret)
array = ret.get('provincias', [])
if sep is None:
return dict([(int(it['codigoDescripcion']['codigo']),
it['codigoDescripcion']['descripcion'])
for it in array])
else:
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array] | [
"def",
"ConsultarProvincias",
"(",
"self",
",",
"sep",
"=",
"\"||\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"provinciasConsultar",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'",
":",
"self",
".",
"Sign",
",",
... | Consulta las provincias habilitadas | [
"Consulta",
"las",
"provincias",
"habilitadas"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2567-L2584 |
231,346 | reingart/pyafipws | wslpg.py | WSLPG.CargarFormatoPDF | def CargarFormatoPDF(self, archivo="liquidacion_form_c1116b_wslpg.csv"):
"Cargo el formato de campos a generar desde una planilla CSV"
# si no encuentro archivo, lo busco en el directorio predeterminado:
if not os.path.exists(archivo):
archivo = os.path.join(self.InstallDir, "plantillas", os.path.basename(archivo))
if DEBUG: print "abriendo archivo ", archivo
# inicializo la lista de los elementos:
self.elements = []
for lno, linea in enumerate(open(archivo.encode('latin1')).readlines()):
if DEBUG: print "procesando linea ", lno, linea
args = []
for i,v in enumerate(linea.split(";")):
if not v.startswith("'"):
v = v.replace(",",".")
else:
v = v#.decode('latin1')
if v.strip()=='':
v = None
else:
v = eval(v.strip())
args.append(v)
# corrijo path relativo para las imágenes:
if args[1] == 'I':
if not os.path.exists(args[14]):
args[14] = os.path.join(self.InstallDir, "plantillas", os.path.basename(args[14]))
if DEBUG: print "NUEVO PATH:", args[14]
self.AgregarCampoPDF(*args)
self.AgregarCampoPDF("anulado", 'T', 150, 250, 0, 0,
size=70, rotate=45, foreground=0x808080,
priority=-1)
if HOMO:
self.AgregarCampoPDF("homo", 'T', 100, 250, 0, 0,
size=70, rotate=45, foreground=0x808080,
priority=-1)
# cargo los elementos en la plantilla
self.template.load_elements(self.elements)
return True | python | def CargarFormatoPDF(self, archivo="liquidacion_form_c1116b_wslpg.csv"):
"Cargo el formato de campos a generar desde una planilla CSV"
# si no encuentro archivo, lo busco en el directorio predeterminado:
if not os.path.exists(archivo):
archivo = os.path.join(self.InstallDir, "plantillas", os.path.basename(archivo))
if DEBUG: print "abriendo archivo ", archivo
# inicializo la lista de los elementos:
self.elements = []
for lno, linea in enumerate(open(archivo.encode('latin1')).readlines()):
if DEBUG: print "procesando linea ", lno, linea
args = []
for i,v in enumerate(linea.split(";")):
if not v.startswith("'"):
v = v.replace(",",".")
else:
v = v#.decode('latin1')
if v.strip()=='':
v = None
else:
v = eval(v.strip())
args.append(v)
# corrijo path relativo para las imágenes:
if args[1] == 'I':
if not os.path.exists(args[14]):
args[14] = os.path.join(self.InstallDir, "plantillas", os.path.basename(args[14]))
if DEBUG: print "NUEVO PATH:", args[14]
self.AgregarCampoPDF(*args)
self.AgregarCampoPDF("anulado", 'T', 150, 250, 0, 0,
size=70, rotate=45, foreground=0x808080,
priority=-1)
if HOMO:
self.AgregarCampoPDF("homo", 'T', 100, 250, 0, 0,
size=70, rotate=45, foreground=0x808080,
priority=-1)
# cargo los elementos en la plantilla
self.template.load_elements(self.elements)
return True | [
"def",
"CargarFormatoPDF",
"(",
"self",
",",
"archivo",
"=",
"\"liquidacion_form_c1116b_wslpg.csv\"",
")",
":",
"# si no encuentro archivo, lo busco en el directorio predeterminado:",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"archivo",
")",
":",
"archivo",
"=... | Cargo el formato de campos a generar desde una planilla CSV | [
"Cargo",
"el",
"formato",
"de",
"campos",
"a",
"generar",
"desde",
"una",
"planilla",
"CSV"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2656-L2701 |
231,347 | reingart/pyafipws | wslpg.py | WSLPG.AgregarCampoPDF | def AgregarCampoPDF(self, nombre, tipo, x1, y1, x2, y2,
font="Arial", size=12,
bold=False, italic=False, underline=False,
foreground= 0x000000, background=0xFFFFFF,
align="L", text="", priority=0, **kwargs):
"Agrego un campo a la plantilla"
# convierto colores de string (en hexadecimal)
if isinstance(foreground, basestring): foreground = int(foreground, 16)
if isinstance(background, basestring): background = int(background, 16)
if isinstance(text, unicode): text = text.encode("latin1")
field = {
'name': nombre,
'type': tipo,
'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2,
'font': font, 'size': size,
'bold': bold, 'italic': italic, 'underline': underline,
'foreground': foreground, 'background': background,
'align': align, 'text': text, 'priority': priority}
field.update(kwargs)
self.elements.append(field)
return True | python | def AgregarCampoPDF(self, nombre, tipo, x1, y1, x2, y2,
font="Arial", size=12,
bold=False, italic=False, underline=False,
foreground= 0x000000, background=0xFFFFFF,
align="L", text="", priority=0, **kwargs):
"Agrego un campo a la plantilla"
# convierto colores de string (en hexadecimal)
if isinstance(foreground, basestring): foreground = int(foreground, 16)
if isinstance(background, basestring): background = int(background, 16)
if isinstance(text, unicode): text = text.encode("latin1")
field = {
'name': nombre,
'type': tipo,
'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2,
'font': font, 'size': size,
'bold': bold, 'italic': italic, 'underline': underline,
'foreground': foreground, 'background': background,
'align': align, 'text': text, 'priority': priority}
field.update(kwargs)
self.elements.append(field)
return True | [
"def",
"AgregarCampoPDF",
"(",
"self",
",",
"nombre",
",",
"tipo",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"font",
"=",
"\"Arial\"",
",",
"size",
"=",
"12",
",",
"bold",
"=",
"False",
",",
"italic",
"=",
"False",
",",
"underline",
"=",
"... | Agrego un campo a la plantilla | [
"Agrego",
"un",
"campo",
"a",
"la",
"plantilla"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2704-L2724 |
231,348 | reingart/pyafipws | wslpg.py | WSLPG.GenerarPDF | def GenerarPDF(self, archivo="", dest="F"):
"Generar archivo de salida en formato PDF"
try:
self.template.render(archivo, dest=dest)
return True
except Exception, e:
self.Excepcion = str(e)
return False | python | def GenerarPDF(self, archivo="", dest="F"):
"Generar archivo de salida en formato PDF"
try:
self.template.render(archivo, dest=dest)
return True
except Exception, e:
self.Excepcion = str(e)
return False | [
"def",
"GenerarPDF",
"(",
"self",
",",
"archivo",
"=",
"\"\"",
",",
"dest",
"=",
"\"F\"",
")",
":",
"try",
":",
"self",
".",
"template",
".",
"render",
"(",
"archivo",
",",
"dest",
"=",
"dest",
")",
"return",
"True",
"except",
"Exception",
",",
"e",
... | Generar archivo de salida en formato PDF | [
"Generar",
"archivo",
"de",
"salida",
"en",
"formato",
"PDF"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2991-L2998 |
231,349 | reingart/pyafipws | iibb.py | IIBB.ConsultarContribuyentes | def ConsultarContribuyentes(self, fecha_desde, fecha_hasta, cuit_contribuyente):
"Realiza la consulta remota a ARBA, estableciendo los resultados"
self.limpiar()
try:
self.xml = SimpleXMLElement(XML_ENTRADA_BASE)
self.xml.fechaDesde = fecha_desde
self.xml.fechaHasta = fecha_hasta
self.xml.contribuyentes.contribuyente.cuitContribuyente = cuit_contribuyente
xml = self.xml.as_xml()
self.CodigoHash = md5.md5(xml).hexdigest()
nombre = "DFEServicioConsulta_%s.xml" % self.CodigoHash
# guardo el xml en el archivo a enviar y luego lo re-abro:
archivo = open(os.path.join(tempfile.gettempdir(), nombre), "w")
archivo.write(xml)
archivo.close()
archivo = open(os.path.join(tempfile.gettempdir(), nombre), "r")
if not self.testing:
response = self.client(user=self.Usuario, password=self.Password,
file=archivo)
else:
response = open(self.testing).read()
self.XmlResponse = response
self.xml = SimpleXMLElement(response)
if 'tipoError' in self.xml:
self.TipoError = str(self.xml.tipoError)
self.CodigoError = str(self.xml.codigoError)
self.MensajeError = str(self.xml.mensajeError).decode('latin1').encode("ascii", "replace")
if 'numeroComprobante' in self.xml:
self.NumeroComprobante = str(self.xml.numeroComprobante)
self.CantidadContribuyentes = int(self.xml.cantidadContribuyentes)
if 'contribuyentes' in self.xml:
for contrib in self.xml.contribuyente:
c = {
'CuitContribuytente': str(contrib.cuitContribuyente),
'AlicuotaPercepcion': str(contrib.alicuotaPercepcion),
'AlicuotaRetencion': str(contrib.alicuotaRetencion),
'GrupoPercepcion': str(contrib.grupoPercepcion),
'GrupoRetencion': str(contrib.grupoRetencion),
'Errores': [],
}
self.contribuyentes.append(c)
# establecer valores del primer contrib (sin eliminarlo)
self.LeerContribuyente(pop=False)
return True
except Exception, e:
ex = traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback)
self.Traceback = ''.join(ex)
try:
self.Excepcion = traceback.format_exception_only( sys.exc_type, sys.exc_value)[0]
except:
self.Excepcion = u"<no disponible>"
return False | python | def ConsultarContribuyentes(self, fecha_desde, fecha_hasta, cuit_contribuyente):
"Realiza la consulta remota a ARBA, estableciendo los resultados"
self.limpiar()
try:
self.xml = SimpleXMLElement(XML_ENTRADA_BASE)
self.xml.fechaDesde = fecha_desde
self.xml.fechaHasta = fecha_hasta
self.xml.contribuyentes.contribuyente.cuitContribuyente = cuit_contribuyente
xml = self.xml.as_xml()
self.CodigoHash = md5.md5(xml).hexdigest()
nombre = "DFEServicioConsulta_%s.xml" % self.CodigoHash
# guardo el xml en el archivo a enviar y luego lo re-abro:
archivo = open(os.path.join(tempfile.gettempdir(), nombre), "w")
archivo.write(xml)
archivo.close()
archivo = open(os.path.join(tempfile.gettempdir(), nombre), "r")
if not self.testing:
response = self.client(user=self.Usuario, password=self.Password,
file=archivo)
else:
response = open(self.testing).read()
self.XmlResponse = response
self.xml = SimpleXMLElement(response)
if 'tipoError' in self.xml:
self.TipoError = str(self.xml.tipoError)
self.CodigoError = str(self.xml.codigoError)
self.MensajeError = str(self.xml.mensajeError).decode('latin1').encode("ascii", "replace")
if 'numeroComprobante' in self.xml:
self.NumeroComprobante = str(self.xml.numeroComprobante)
self.CantidadContribuyentes = int(self.xml.cantidadContribuyentes)
if 'contribuyentes' in self.xml:
for contrib in self.xml.contribuyente:
c = {
'CuitContribuytente': str(contrib.cuitContribuyente),
'AlicuotaPercepcion': str(contrib.alicuotaPercepcion),
'AlicuotaRetencion': str(contrib.alicuotaRetencion),
'GrupoPercepcion': str(contrib.grupoPercepcion),
'GrupoRetencion': str(contrib.grupoRetencion),
'Errores': [],
}
self.contribuyentes.append(c)
# establecer valores del primer contrib (sin eliminarlo)
self.LeerContribuyente(pop=False)
return True
except Exception, e:
ex = traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback)
self.Traceback = ''.join(ex)
try:
self.Excepcion = traceback.format_exception_only( sys.exc_type, sys.exc_value)[0]
except:
self.Excepcion = u"<no disponible>"
return False | [
"def",
"ConsultarContribuyentes",
"(",
"self",
",",
"fecha_desde",
",",
"fecha_hasta",
",",
"cuit_contribuyente",
")",
":",
"self",
".",
"limpiar",
"(",
")",
"try",
":",
"self",
".",
"xml",
"=",
"SimpleXMLElement",
"(",
"XML_ENTRADA_BASE",
")",
"self",
".",
... | Realiza la consulta remota a ARBA, estableciendo los resultados | [
"Realiza",
"la",
"consulta",
"remota",
"a",
"ARBA",
"estableciendo",
"los",
"resultados"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/iibb.py#L89-L144 |
231,350 | reingart/pyafipws | wsltv.py | WSLTV.AgregarReceptor | def AgregarReceptor(self, cuit, iibb, nro_socio, nro_fet, **kwargs):
"Agrego un receptor a la liq."
rcpt = dict(cuit=cuit, iibb=iibb, nroSocio=nro_socio, nroFET=nro_fet)
self.solicitud['receptor'] = rcpt
return True | python | def AgregarReceptor(self, cuit, iibb, nro_socio, nro_fet, **kwargs):
"Agrego un receptor a la liq."
rcpt = dict(cuit=cuit, iibb=iibb, nroSocio=nro_socio, nroFET=nro_fet)
self.solicitud['receptor'] = rcpt
return True | [
"def",
"AgregarReceptor",
"(",
"self",
",",
"cuit",
",",
"iibb",
",",
"nro_socio",
",",
"nro_fet",
",",
"*",
"*",
"kwargs",
")",
":",
"rcpt",
"=",
"dict",
"(",
"cuit",
"=",
"cuit",
",",
"iibb",
"=",
"iibb",
",",
"nroSocio",
"=",
"nro_socio",
",",
"... | Agrego un receptor a la liq. | [
"Agrego",
"un",
"receptor",
"a",
"la",
"liq",
"."
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsltv.py#L233-L237 |
231,351 | reingart/pyafipws | wsltv.py | WSLTV.AgregarPrecioClase | def AgregarPrecioClase(self, clase_tabaco, precio, total_kilos=None, total_fardos=None, **kwargs):
"Agrego un PrecioClase a la liq."
precioclase = dict(claseTabaco=clase_tabaco, precio=precio,
totalKilos=total_kilos, totalFardos=total_fardos)
self.solicitud['precioClase'].append(precioclase)
return True | python | def AgregarPrecioClase(self, clase_tabaco, precio, total_kilos=None, total_fardos=None, **kwargs):
"Agrego un PrecioClase a la liq."
precioclase = dict(claseTabaco=clase_tabaco, precio=precio,
totalKilos=total_kilos, totalFardos=total_fardos)
self.solicitud['precioClase'].append(precioclase)
return True | [
"def",
"AgregarPrecioClase",
"(",
"self",
",",
"clase_tabaco",
",",
"precio",
",",
"total_kilos",
"=",
"None",
",",
"total_fardos",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"precioclase",
"=",
"dict",
"(",
"claseTabaco",
"=",
"clase_tabaco",
",",
"p... | Agrego un PrecioClase a la liq. | [
"Agrego",
"un",
"PrecioClase",
"a",
"la",
"liq",
"."
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsltv.py#L255-L260 |
231,352 | reingart/pyafipws | wsltv.py | WSLTV.ConsultarVariedadesClasesTabaco | def ConsultarVariedadesClasesTabaco(self, sep="||"):
"Retorna un listado de variedades y clases de tabaco"
# El listado es una estructura anidada (varias clases por variedad)
#import dbg; dbg.set_trace()
ret = self.client.consultarVariedadesClasesTabaco(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['respuesta']
self.__analizar_errores(ret)
self.XmlResponse = self.client.xml_response
array = ret.get('variedad', [])
if sep is None:
# sin separador, devuelve un diccionario con clave cod_variadedad
# y valor: {"descripcion": ds_variedad, "clases": lista_clases}
# siendo lista_clases = [{'codigo': ..., 'descripcion': ...}]
return dict([(it['codigo'], {'descripcion': it['descripcion'],
'clases': it['clase']})
for it in array])
else:
# con separador, devuelve una lista de strings:
# || cod.variedad || desc.variedad || desc.clase || cod.clase ||
ret = []
for it in array:
for clase in it['clase']:
ret.append(
("%s %%s %s %%s %s %%s %s %%s %s" %
(sep, sep, sep, sep, sep)) %
(it['codigo'], it['descripcion'],
clase['descripcion'], clase['codigo'])
)
return ret | python | def ConsultarVariedadesClasesTabaco(self, sep="||"):
"Retorna un listado de variedades y clases de tabaco"
# El listado es una estructura anidada (varias clases por variedad)
#import dbg; dbg.set_trace()
ret = self.client.consultarVariedadesClasesTabaco(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['respuesta']
self.__analizar_errores(ret)
self.XmlResponse = self.client.xml_response
array = ret.get('variedad', [])
if sep is None:
# sin separador, devuelve un diccionario con clave cod_variadedad
# y valor: {"descripcion": ds_variedad, "clases": lista_clases}
# siendo lista_clases = [{'codigo': ..., 'descripcion': ...}]
return dict([(it['codigo'], {'descripcion': it['descripcion'],
'clases': it['clase']})
for it in array])
else:
# con separador, devuelve una lista de strings:
# || cod.variedad || desc.variedad || desc.clase || cod.clase ||
ret = []
for it in array:
for clase in it['clase']:
ret.append(
("%s %%s %s %%s %s %%s %s %%s %s" %
(sep, sep, sep, sep, sep)) %
(it['codigo'], it['descripcion'],
clase['descripcion'], clase['codigo'])
)
return ret | [
"def",
"ConsultarVariedadesClasesTabaco",
"(",
"self",
",",
"sep",
"=",
"\"||\"",
")",
":",
"# El listado es una estructura anidada (varias clases por variedad)",
"#import dbg; dbg.set_trace()",
"ret",
"=",
"self",
".",
"client",
".",
"consultarVariedadesClasesTabaco",
"(",
... | Retorna un listado de variedades y clases de tabaco | [
"Retorna",
"un",
"listado",
"de",
"variedades",
"y",
"clases",
"de",
"tabaco"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsltv.py#L595-L626 |
231,353 | reingart/pyafipws | utils.py | exception_info | def exception_info(current_filename=None, index=-1):
"Analizar el traceback y armar un dict con la info amigable user-friendly"
# guardo el traceback original (por si hay una excepción):
info = sys.exc_info() # exc_type, exc_value, exc_traceback
# importante: no usar unpacking porque puede causar memory leak
if not current_filename:
# genero un call stack para ver quien me llamó y limitar la traza:
# advertencia: esto es necesario ya que en py2exe no tengo __file__
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
current_filename = os.path.normpath(os.path.abspath(f.f_code.co_filename))
# extraer la última traza del archivo solicitado:
# (útil para no alargar demasiado la traza con lineas de las librerías)
ret = {'filename': "", 'lineno': 0, 'function_name': "", 'code': ""}
try:
for (filename, lineno, fn, text) in traceback.extract_tb(info[2]):
if os.path.normpath(os.path.abspath(filename)) == current_filename:
ret = {'filename': filename, 'lineno': lineno,
'function_name': fn, 'code': text}
except Exception, e:
pass
# obtengo el mensaje de excepcion tal cual lo formatea python:
# (para evitar errores de encoding)
try:
ret['msg'] = traceback.format_exception_only(*info[0:2])[0]
except:
ret['msg'] = '<no disponible>'
# obtener el nombre de la excepcion (ej. "NameError")
try:
ret['name'] = info[0].__name__
except:
ret['name'] = 'Exception'
# obtener la traza formateada como string:
try:
tb = traceback.format_exception(*info)
ret['tb'] = ''.join(tb)
except:
ret['tb'] = ""
return ret | python | def exception_info(current_filename=None, index=-1):
"Analizar el traceback y armar un dict con la info amigable user-friendly"
# guardo el traceback original (por si hay una excepción):
info = sys.exc_info() # exc_type, exc_value, exc_traceback
# importante: no usar unpacking porque puede causar memory leak
if not current_filename:
# genero un call stack para ver quien me llamó y limitar la traza:
# advertencia: esto es necesario ya que en py2exe no tengo __file__
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
current_filename = os.path.normpath(os.path.abspath(f.f_code.co_filename))
# extraer la última traza del archivo solicitado:
# (útil para no alargar demasiado la traza con lineas de las librerías)
ret = {'filename': "", 'lineno': 0, 'function_name': "", 'code': ""}
try:
for (filename, lineno, fn, text) in traceback.extract_tb(info[2]):
if os.path.normpath(os.path.abspath(filename)) == current_filename:
ret = {'filename': filename, 'lineno': lineno,
'function_name': fn, 'code': text}
except Exception, e:
pass
# obtengo el mensaje de excepcion tal cual lo formatea python:
# (para evitar errores de encoding)
try:
ret['msg'] = traceback.format_exception_only(*info[0:2])[0]
except:
ret['msg'] = '<no disponible>'
# obtener el nombre de la excepcion (ej. "NameError")
try:
ret['name'] = info[0].__name__
except:
ret['name'] = 'Exception'
# obtener la traza formateada como string:
try:
tb = traceback.format_exception(*info)
ret['tb'] = ''.join(tb)
except:
ret['tb'] = ""
return ret | [
"def",
"exception_info",
"(",
"current_filename",
"=",
"None",
",",
"index",
"=",
"-",
"1",
")",
":",
"# guardo el traceback original (por si hay una excepción):",
"info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"# exc_type, exc_value, exc_traceback",
"# importante... | Analizar el traceback y armar un dict con la info amigable user-friendly | [
"Analizar",
"el",
"traceback",
"y",
"armar",
"un",
"dict",
"con",
"la",
"info",
"amigable",
"user",
"-",
"friendly"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/utils.py#L89-L130 |
231,354 | reingart/pyafipws | utils.py | leer | def leer(linea, formato, expandir_fechas=False):
"Analiza una linea de texto dado un formato, devuelve un diccionario"
dic = {}
comienzo = 1
for fmt in formato:
clave, longitud, tipo = fmt[0:3]
dec = (len(fmt)>3 and isinstance(fmt[3], int)) and fmt[3] or 2
valor = linea[comienzo-1:comienzo-1+longitud].strip()
try:
if chr(8) in valor or chr(127) in valor or chr(255) in valor:
valor = None # nulo
elif tipo == N:
if valor:
valor = long(valor)
else:
valor = 0
elif tipo == I:
if valor:
try:
if '.' in valor:
valor = float(valor)
else:
valor = valor.strip(" ")
if valor[0] == "-":
sign = -1
valor = valor[1:]
else:
sign = +1
valor = sign * float(("%%s.%%0%sd" % dec) % (long(valor[:-dec] or '0'), int(valor[-dec:] or '0')))
except ValueError:
raise ValueError("Campo invalido: %s = '%s'" % (clave, valor))
else:
valor = 0.00
elif expandir_fechas and clave.lower().startswith("fec") and longitud <= 8:
if valor:
valor = "%s-%s-%s" % (valor[0:4], valor[4:6], valor[6:8])
else:
valor = None
else:
valor = valor.decode("ascii","ignore")
if not valor and clave in dic and len(linea) <= comienzo:
pass # ignorar - compatibilidad hacia atrás (cambios tamaño)
else:
dic[clave] = valor
comienzo += longitud
except Exception, e:
raise ValueError("Error al leer campo %s pos %s val '%s': %s" % (
clave, comienzo, valor, str(e)))
return dic | python | def leer(linea, formato, expandir_fechas=False):
"Analiza una linea de texto dado un formato, devuelve un diccionario"
dic = {}
comienzo = 1
for fmt in formato:
clave, longitud, tipo = fmt[0:3]
dec = (len(fmt)>3 and isinstance(fmt[3], int)) and fmt[3] or 2
valor = linea[comienzo-1:comienzo-1+longitud].strip()
try:
if chr(8) in valor or chr(127) in valor or chr(255) in valor:
valor = None # nulo
elif tipo == N:
if valor:
valor = long(valor)
else:
valor = 0
elif tipo == I:
if valor:
try:
if '.' in valor:
valor = float(valor)
else:
valor = valor.strip(" ")
if valor[0] == "-":
sign = -1
valor = valor[1:]
else:
sign = +1
valor = sign * float(("%%s.%%0%sd" % dec) % (long(valor[:-dec] or '0'), int(valor[-dec:] or '0')))
except ValueError:
raise ValueError("Campo invalido: %s = '%s'" % (clave, valor))
else:
valor = 0.00
elif expandir_fechas and clave.lower().startswith("fec") and longitud <= 8:
if valor:
valor = "%s-%s-%s" % (valor[0:4], valor[4:6], valor[6:8])
else:
valor = None
else:
valor = valor.decode("ascii","ignore")
if not valor and clave in dic and len(linea) <= comienzo:
pass # ignorar - compatibilidad hacia atrás (cambios tamaño)
else:
dic[clave] = valor
comienzo += longitud
except Exception, e:
raise ValueError("Error al leer campo %s pos %s val '%s': %s" % (
clave, comienzo, valor, str(e)))
return dic | [
"def",
"leer",
"(",
"linea",
",",
"formato",
",",
"expandir_fechas",
"=",
"False",
")",
":",
"dic",
"=",
"{",
"}",
"comienzo",
"=",
"1",
"for",
"fmt",
"in",
"formato",
":",
"clave",
",",
"longitud",
",",
"tipo",
"=",
"fmt",
"[",
"0",
":",
"3",
"]... | Analiza una linea de texto dado un formato, devuelve un diccionario | [
"Analiza",
"una",
"linea",
"de",
"texto",
"dado",
"un",
"formato",
"devuelve",
"un",
"diccionario"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/utils.py#L566-L614 |
231,355 | reingart/pyafipws | utils.py | dar_nombre_campo_dbf | def dar_nombre_campo_dbf(clave, claves):
"Reducir nombre de campo a 10 caracteres, sin espacios ni _, sin repetir"
# achico el nombre del campo para que quepa en la tabla:
nombre = clave.replace("_","")[:10]
# si el campo esta repetido, le agrego un número
i = 0
while nombre in claves:
i += 1
nombre = nombre[:9] + str(i)
return nombre.lower() | python | def dar_nombre_campo_dbf(clave, claves):
"Reducir nombre de campo a 10 caracteres, sin espacios ni _, sin repetir"
# achico el nombre del campo para que quepa en la tabla:
nombre = clave.replace("_","")[:10]
# si el campo esta repetido, le agrego un número
i = 0
while nombre in claves:
i += 1
nombre = nombre[:9] + str(i)
return nombre.lower() | [
"def",
"dar_nombre_campo_dbf",
"(",
"clave",
",",
"claves",
")",
":",
"# achico el nombre del campo para que quepa en la tabla:",
"nombre",
"=",
"clave",
".",
"replace",
"(",
"\"_\"",
",",
"\"\"",
")",
"[",
":",
"10",
"]",
"# si el campo esta repetido, le agrego un núme... | Reducir nombre de campo a 10 caracteres, sin espacios ni _, sin repetir | [
"Reducir",
"nombre",
"de",
"campo",
"a",
"10",
"caracteres",
"sin",
"espacios",
"ni",
"_",
"sin",
"repetir"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/utils.py#L781-L790 |
231,356 | reingart/pyafipws | utils.py | verifica | def verifica(ver_list, res_dict, difs):
"Verificar que dos diccionarios sean iguales, actualiza lista diferencias"
for k, v in ver_list.items():
# normalizo a float para poder comparar numericamente:
if isinstance(v, (Decimal, int, long)):
v = float(v)
if isinstance(res_dict.get(k), (Decimal, int, long)):
res_dict[k] = float(res_dict[k])
if isinstance(v, list):
# verifico que ambas listas tengan la misma cantidad de elementos:
if v and not k in res_dict and v:
difs.append("falta tag %s: %s %s" % (k, repr(v), repr(res_dict.get(k))))
elif len(res_dict.get(k, []))!=len(v or []):
difs.append("tag %s len !=: %s %s" % (k, repr(v), repr(res_dict.get(k))))
else:
# ordeno las listas para poder compararlas si vienen mezcladas
rl = sorted(res_dict.get(k, []))
# comparo los elementos uno a uno:
for i, vl in enumerate(sorted(v)):
verifica(vl, rl[i], difs)
elif isinstance(v, dict):
# comparo recursivamente los elementos:
verifica(v, res_dict.get(k, {}), difs)
elif res_dict.get(k) is None or v is None:
# alguno de los dos es nulo, verifico si ambos lo son o faltan
if v=="":
v = None
r = res_dict.get(k)
if r=="":
r = None
if not (r is None and v is None):
difs.append("%s: nil %s!=%s" % (k, repr(v), repr(r)))
elif type(res_dict.get(k)) == type(v):
# tipos iguales, los comparo directamente
if res_dict.get(k) != v:
difs.append("%s: %s!=%s" % (k, repr(v), repr(res_dict.get(k))))
elif isinstance(v, float) or isinstance(res_dict.get(k), float):
# comparar numericamente
if float(res_dict.get(k)) != float(v):
difs.append("%s: %s!=%s" % (k, repr(v), repr(res_dict.get(k))))
elif unicode(res_dict.get(k)) != unicode(v):
# tipos diferentes, comparo la representación
difs.append("%s: str %s!=%s" % (k, repr(v), repr(res_dict.get(k))))
else:
pass | python | def verifica(ver_list, res_dict, difs):
"Verificar que dos diccionarios sean iguales, actualiza lista diferencias"
for k, v in ver_list.items():
# normalizo a float para poder comparar numericamente:
if isinstance(v, (Decimal, int, long)):
v = float(v)
if isinstance(res_dict.get(k), (Decimal, int, long)):
res_dict[k] = float(res_dict[k])
if isinstance(v, list):
# verifico que ambas listas tengan la misma cantidad de elementos:
if v and not k in res_dict and v:
difs.append("falta tag %s: %s %s" % (k, repr(v), repr(res_dict.get(k))))
elif len(res_dict.get(k, []))!=len(v or []):
difs.append("tag %s len !=: %s %s" % (k, repr(v), repr(res_dict.get(k))))
else:
# ordeno las listas para poder compararlas si vienen mezcladas
rl = sorted(res_dict.get(k, []))
# comparo los elementos uno a uno:
for i, vl in enumerate(sorted(v)):
verifica(vl, rl[i], difs)
elif isinstance(v, dict):
# comparo recursivamente los elementos:
verifica(v, res_dict.get(k, {}), difs)
elif res_dict.get(k) is None or v is None:
# alguno de los dos es nulo, verifico si ambos lo son o faltan
if v=="":
v = None
r = res_dict.get(k)
if r=="":
r = None
if not (r is None and v is None):
difs.append("%s: nil %s!=%s" % (k, repr(v), repr(r)))
elif type(res_dict.get(k)) == type(v):
# tipos iguales, los comparo directamente
if res_dict.get(k) != v:
difs.append("%s: %s!=%s" % (k, repr(v), repr(res_dict.get(k))))
elif isinstance(v, float) or isinstance(res_dict.get(k), float):
# comparar numericamente
if float(res_dict.get(k)) != float(v):
difs.append("%s: %s!=%s" % (k, repr(v), repr(res_dict.get(k))))
elif unicode(res_dict.get(k)) != unicode(v):
# tipos diferentes, comparo la representación
difs.append("%s: str %s!=%s" % (k, repr(v), repr(res_dict.get(k))))
else:
pass | [
"def",
"verifica",
"(",
"ver_list",
",",
"res_dict",
",",
"difs",
")",
":",
"for",
"k",
",",
"v",
"in",
"ver_list",
".",
"items",
"(",
")",
":",
"# normalizo a float para poder comparar numericamente:",
"if",
"isinstance",
"(",
"v",
",",
"(",
"Decimal",
",",... | Verificar que dos diccionarios sean iguales, actualiza lista diferencias | [
"Verificar",
"que",
"dos",
"diccionarios",
"sean",
"iguales",
"actualiza",
"lista",
"diferencias"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/utils.py#L793-L837 |
231,357 | reingart/pyafipws | utils.py | norm | def norm(x, encoding="latin1"):
"Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular"
if not isinstance(x, basestring):
x = unicode(x)
elif isinstance(x, str):
x = x.decode(encoding, 'ignore')
return unicodedata.normalize('NFKD', x).encode('ASCII', 'ignore') | python | def norm(x, encoding="latin1"):
"Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular"
if not isinstance(x, basestring):
x = unicode(x)
elif isinstance(x, str):
x = x.decode(encoding, 'ignore')
return unicodedata.normalize('NFKD', x).encode('ASCII', 'ignore') | [
"def",
"norm",
"(",
"x",
",",
"encoding",
"=",
"\"latin1\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"basestring",
")",
":",
"x",
"=",
"unicode",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"x",
"=",
"x",
".... | Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular | [
"Convertir",
"acentos",
"codificados",
"en",
"ISO",
"8859",
"-",
"1",
"u",
"otro",
"a",
"ASCII",
"regular"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/utils.py#L863-L869 |
231,358 | reingart/pyafipws | utils.py | BaseWS.SetTicketAcceso | def SetTicketAcceso(self, ta_string):
"Establecer el token y sign desde un ticket de acceso XML"
if ta_string:
ta = SimpleXMLElement(ta_string)
self.Token = str(ta.credentials.token)
self.Sign = str(ta.credentials.sign)
return True
else:
raise RuntimeError("Ticket de Acceso vacio!") | python | def SetTicketAcceso(self, ta_string):
"Establecer el token y sign desde un ticket de acceso XML"
if ta_string:
ta = SimpleXMLElement(ta_string)
self.Token = str(ta.credentials.token)
self.Sign = str(ta.credentials.sign)
return True
else:
raise RuntimeError("Ticket de Acceso vacio!") | [
"def",
"SetTicketAcceso",
"(",
"self",
",",
"ta_string",
")",
":",
"if",
"ta_string",
":",
"ta",
"=",
"SimpleXMLElement",
"(",
"ta_string",
")",
"self",
".",
"Token",
"=",
"str",
"(",
"ta",
".",
"credentials",
".",
"token",
")",
"self",
".",
"Sign",
"=... | Establecer el token y sign desde un ticket de acceso XML | [
"Establecer",
"el",
"token",
"y",
"sign",
"desde",
"un",
"ticket",
"de",
"acceso",
"XML"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/utils.py#L383-L391 |
231,359 | reingart/pyafipws | wsremcarne.py | WSRemCarne.__analizar_observaciones | def __analizar_observaciones(self, ret):
"Comprueba y extrae observaciones si existen en la respuesta XML"
self.Observaciones = [obs["codigoDescripcion"] for obs in ret.get('arrayObservaciones', [])]
self.Obs = '\n'.join(["%(codigo)s: %(descripcion)s" % obs for obs in self.Observaciones]) | python | def __analizar_observaciones(self, ret):
"Comprueba y extrae observaciones si existen en la respuesta XML"
self.Observaciones = [obs["codigoDescripcion"] for obs in ret.get('arrayObservaciones', [])]
self.Obs = '\n'.join(["%(codigo)s: %(descripcion)s" % obs for obs in self.Observaciones]) | [
"def",
"__analizar_observaciones",
"(",
"self",
",",
"ret",
")",
":",
"self",
".",
"Observaciones",
"=",
"[",
"obs",
"[",
"\"codigoDescripcion\"",
"]",
"for",
"obs",
"in",
"ret",
".",
"get",
"(",
"'arrayObservaciones'",
",",
"[",
"]",
")",
"]",
"self",
"... | Comprueba y extrae observaciones si existen en la respuesta XML | [
"Comprueba",
"y",
"extrae",
"observaciones",
"si",
"existen",
"en",
"la",
"respuesta",
"XML"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsremcarne.py#L138-L141 |
231,360 | reingart/pyafipws | wsremcarne.py | WSRemCarne.__analizar_evento | def __analizar_evento(self, ret):
"Comprueba y extrae el wvento informativo si existen en la respuesta XML"
evt = ret.get('evento')
if evt:
self.Eventos = [evt]
self.Evento = "%(codigo)s: %(descripcion)s" % evt | python | def __analizar_evento(self, ret):
"Comprueba y extrae el wvento informativo si existen en la respuesta XML"
evt = ret.get('evento')
if evt:
self.Eventos = [evt]
self.Evento = "%(codigo)s: %(descripcion)s" % evt | [
"def",
"__analizar_evento",
"(",
"self",
",",
"ret",
")",
":",
"evt",
"=",
"ret",
".",
"get",
"(",
"'evento'",
")",
"if",
"evt",
":",
"self",
".",
"Eventos",
"=",
"[",
"evt",
"]",
"self",
".",
"Evento",
"=",
"\"%(codigo)s: %(descripcion)s\"",
"%",
"evt... | Comprueba y extrae el wvento informativo si existen en la respuesta XML | [
"Comprueba",
"y",
"extrae",
"el",
"wvento",
"informativo",
"si",
"existen",
"en",
"la",
"respuesta",
"XML"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsremcarne.py#L143-L148 |
231,361 | reingart/pyafipws | wsremcarne.py | WSRemCarne.CrearRemito | def CrearRemito(self, tipo_comprobante, punto_emision, tipo_movimiento, categoria_emisor, cuit_titular_mercaderia, cod_dom_origen,
tipo_receptor, categoria_receptor=None, cuit_receptor=None, cuit_depositario=None,
cod_dom_destino=None, cod_rem_redestinar=None, cod_remito=None, estado=None,
**kwargs):
"Inicializa internamente los datos de un remito para autorizar"
self.remito = {'tipoComprobante': tipo_comprobante, 'puntoEmision': punto_emision, 'categoriaEmisor': categoria_emisor,
'cuitTitularMercaderia': cuit_titular_mercaderia, 'cuitDepositario': cuit_depositario,
'tipoReceptor': tipo_receptor, 'categoriaReceptor': categoria_receptor, 'cuitReceptor': cuit_receptor,
'codDomOrigen': cod_dom_origen, 'codDomDestino': cod_dom_destino, 'tipoMovimiento': tipo_movimiento,
'estado': estado, 'codRemito': cod_remito,
'codRemRedestinado': cod_rem_redestinar,
'arrayMercaderias': [], 'arrayContingencias': [],
}
return True | python | def CrearRemito(self, tipo_comprobante, punto_emision, tipo_movimiento, categoria_emisor, cuit_titular_mercaderia, cod_dom_origen,
tipo_receptor, categoria_receptor=None, cuit_receptor=None, cuit_depositario=None,
cod_dom_destino=None, cod_rem_redestinar=None, cod_remito=None, estado=None,
**kwargs):
"Inicializa internamente los datos de un remito para autorizar"
self.remito = {'tipoComprobante': tipo_comprobante, 'puntoEmision': punto_emision, 'categoriaEmisor': categoria_emisor,
'cuitTitularMercaderia': cuit_titular_mercaderia, 'cuitDepositario': cuit_depositario,
'tipoReceptor': tipo_receptor, 'categoriaReceptor': categoria_receptor, 'cuitReceptor': cuit_receptor,
'codDomOrigen': cod_dom_origen, 'codDomDestino': cod_dom_destino, 'tipoMovimiento': tipo_movimiento,
'estado': estado, 'codRemito': cod_remito,
'codRemRedestinado': cod_rem_redestinar,
'arrayMercaderias': [], 'arrayContingencias': [],
}
return True | [
"def",
"CrearRemito",
"(",
"self",
",",
"tipo_comprobante",
",",
"punto_emision",
",",
"tipo_movimiento",
",",
"categoria_emisor",
",",
"cuit_titular_mercaderia",
",",
"cod_dom_origen",
",",
"tipo_receptor",
",",
"categoria_receptor",
"=",
"None",
",",
"cuit_receptor",
... | Inicializa internamente los datos de un remito para autorizar | [
"Inicializa",
"internamente",
"los",
"datos",
"de",
"un",
"remito",
"para",
"autorizar"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsremcarne.py#L151-L164 |
231,362 | reingart/pyafipws | wsremcarne.py | WSRemCarne.AnalizarRemito | def AnalizarRemito(self, ret, archivo=None):
"Extrae el resultado del remito, si existen en la respuesta XML"
if ret:
self.CodRemito = ret.get("codRemito")
self.TipoComprobante = ret.get("tipoComprobante")
self.PuntoEmision = ret.get("puntoEmision")
datos_aut = ret.get('datosAutorizacion')
if datos_aut:
self.NroRemito = datos_aut.get('nroRemito')
self.CodAutorizacion = datos_aut.get('codAutorizacion')
self.FechaEmision = datos_aut.get('fechaEmision')
self.FechaVencimiento = datos_aut.get('fechaVencimiento')
self.Estado = ret.get('estado')
self.Resultado = ret.get('resultado')
self.QR = ret.get('qr') or ""
if archivo:
qr = base64.b64decode(self.QR)
f = open(archivo, "wb")
f.write(qr)
f.close() | python | def AnalizarRemito(self, ret, archivo=None):
"Extrae el resultado del remito, si existen en la respuesta XML"
if ret:
self.CodRemito = ret.get("codRemito")
self.TipoComprobante = ret.get("tipoComprobante")
self.PuntoEmision = ret.get("puntoEmision")
datos_aut = ret.get('datosAutorizacion')
if datos_aut:
self.NroRemito = datos_aut.get('nroRemito')
self.CodAutorizacion = datos_aut.get('codAutorizacion')
self.FechaEmision = datos_aut.get('fechaEmision')
self.FechaVencimiento = datos_aut.get('fechaVencimiento')
self.Estado = ret.get('estado')
self.Resultado = ret.get('resultado')
self.QR = ret.get('qr') or ""
if archivo:
qr = base64.b64decode(self.QR)
f = open(archivo, "wb")
f.write(qr)
f.close() | [
"def",
"AnalizarRemito",
"(",
"self",
",",
"ret",
",",
"archivo",
"=",
"None",
")",
":",
"if",
"ret",
":",
"self",
".",
"CodRemito",
"=",
"ret",
".",
"get",
"(",
"\"codRemito\"",
")",
"self",
".",
"TipoComprobante",
"=",
"ret",
".",
"get",
"(",
"\"ti... | Extrae el resultado del remito, si existen en la respuesta XML | [
"Extrae",
"el",
"resultado",
"del",
"remito",
"si",
"existen",
"en",
"la",
"respuesta",
"XML"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsremcarne.py#L222-L241 |
231,363 | reingart/pyafipws | wsremcarne.py | WSRemCarne.EmitirRemito | def EmitirRemito(self, archivo="qr.png"):
"Emitir Remitos que se encuentren en estado Pendiente de Emitir."
response = self.client.emitirRemito(
authRequest={'token': self.Token, 'sign': self.Sign, 'cuitRepresentada': self.Cuit},
codRemito=self.remito['codRemito'],
viaje=self.remito.get('viaje'))
ret = response.get("emitirRemitoReturn")
if ret:
self.__analizar_errores(ret)
self.__analizar_observaciones(ret)
self.__analizar_evento(ret)
self.AnalizarRemito(ret, archivo)
return bool(self.CodRemito) | python | def EmitirRemito(self, archivo="qr.png"):
"Emitir Remitos que se encuentren en estado Pendiente de Emitir."
response = self.client.emitirRemito(
authRequest={'token': self.Token, 'sign': self.Sign, 'cuitRepresentada': self.Cuit},
codRemito=self.remito['codRemito'],
viaje=self.remito.get('viaje'))
ret = response.get("emitirRemitoReturn")
if ret:
self.__analizar_errores(ret)
self.__analizar_observaciones(ret)
self.__analizar_evento(ret)
self.AnalizarRemito(ret, archivo)
return bool(self.CodRemito) | [
"def",
"EmitirRemito",
"(",
"self",
",",
"archivo",
"=",
"\"qr.png\"",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"emitirRemito",
"(",
"authRequest",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'",
":",
"self",
".",
"Sign",
"... | Emitir Remitos que se encuentren en estado Pendiente de Emitir. | [
"Emitir",
"Remitos",
"que",
"se",
"encuentren",
"en",
"estado",
"Pendiente",
"de",
"Emitir",
"."
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsremcarne.py#L244-L256 |
231,364 | reingart/pyafipws | wsremcarne.py | WSRemCarne.ConsultarRemito | def ConsultarRemito(self, cod_remito=None, id_req=None,
tipo_comprobante=None, punto_emision=None, nro_comprobante=None):
"Obtener los datos de un remito generado"
print(self.client.help("consultarRemito"))
response = self.client.consultarRemito(
authRequest={'token': self.Token, 'sign': self.Sign, 'cuitRepresentada': self.Cuit},
codRemito=cod_remito,
idReq=id_req,
tipoComprobante=tipo_comprobante,
puntoEmision=punto_emision,
nroComprobante=nro_comprobante)
ret = response.get("consultarRemitoReturn", {})
id_req = ret.get("idReq", 0)
self.remito = rec = ret.get("remito", {})
self.__analizar_errores(ret)
self.__analizar_observaciones(ret)
self.__analizar_evento(ret)
self.AnalizarRemito(rec)
return id_req | python | def ConsultarRemito(self, cod_remito=None, id_req=None,
tipo_comprobante=None, punto_emision=None, nro_comprobante=None):
"Obtener los datos de un remito generado"
print(self.client.help("consultarRemito"))
response = self.client.consultarRemito(
authRequest={'token': self.Token, 'sign': self.Sign, 'cuitRepresentada': self.Cuit},
codRemito=cod_remito,
idReq=id_req,
tipoComprobante=tipo_comprobante,
puntoEmision=punto_emision,
nroComprobante=nro_comprobante)
ret = response.get("consultarRemitoReturn", {})
id_req = ret.get("idReq", 0)
self.remito = rec = ret.get("remito", {})
self.__analizar_errores(ret)
self.__analizar_observaciones(ret)
self.__analizar_evento(ret)
self.AnalizarRemito(rec)
return id_req | [
"def",
"ConsultarRemito",
"(",
"self",
",",
"cod_remito",
"=",
"None",
",",
"id_req",
"=",
"None",
",",
"tipo_comprobante",
"=",
"None",
",",
"punto_emision",
"=",
"None",
",",
"nro_comprobante",
"=",
"None",
")",
":",
"print",
"(",
"self",
".",
"client",
... | Obtener los datos de un remito generado | [
"Obtener",
"los",
"datos",
"de",
"un",
"remito",
"generado"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsremcarne.py#L304-L322 |
231,365 | reingart/pyafipws | wslsp.py | WSLSP.AgregarEmisor | def AgregarEmisor(self, tipo_cbte, pto_vta, nro_cbte, cod_caracter=None,
fecha_inicio_act=None, iibb=None, nro_ruca=None,
nro_renspa=None, cuit_autorizado=None, **kwargs):
"Agrego los datos del emisor a la liq."
# cod_caracter y fecha_inicio_act no es requerido para ajustes
d = {'tipoComprobante': tipo_cbte, 'puntoVenta': pto_vta,
'nroComprobante': nro_cbte,
'codCaracter': cod_caracter,
'fechaInicioActividades': fecha_inicio_act,
'iibb': iibb,
'nroRUCA': nro_ruca,
'nroRenspa': nro_renspa,
'cuitAutorizado': cuit_autorizado}
self.solicitud['emisor'].update(d)
return True | python | def AgregarEmisor(self, tipo_cbte, pto_vta, nro_cbte, cod_caracter=None,
fecha_inicio_act=None, iibb=None, nro_ruca=None,
nro_renspa=None, cuit_autorizado=None, **kwargs):
"Agrego los datos del emisor a la liq."
# cod_caracter y fecha_inicio_act no es requerido para ajustes
d = {'tipoComprobante': tipo_cbte, 'puntoVenta': pto_vta,
'nroComprobante': nro_cbte,
'codCaracter': cod_caracter,
'fechaInicioActividades': fecha_inicio_act,
'iibb': iibb,
'nroRUCA': nro_ruca,
'nroRenspa': nro_renspa,
'cuitAutorizado': cuit_autorizado}
self.solicitud['emisor'].update(d)
return True | [
"def",
"AgregarEmisor",
"(",
"self",
",",
"tipo_cbte",
",",
"pto_vta",
",",
"nro_cbte",
",",
"cod_caracter",
"=",
"None",
",",
"fecha_inicio_act",
"=",
"None",
",",
"iibb",
"=",
"None",
",",
"nro_ruca",
"=",
"None",
",",
"nro_renspa",
"=",
"None",
",",
"... | Agrego los datos del emisor a la liq. | [
"Agrego",
"los",
"datos",
"del",
"emisor",
"a",
"la",
"liq",
"."
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslsp.py#L222-L236 |
231,366 | reingart/pyafipws | wslsp.py | WSLSP.AgregarReceptor | def AgregarReceptor(self, cod_caracter, **kwargs):
"Agrego los datos del receptor a la liq."
d = {'codCaracter': cod_caracter}
self.solicitud['receptor'].update(d)
return True | python | def AgregarReceptor(self, cod_caracter, **kwargs):
"Agrego los datos del receptor a la liq."
d = {'codCaracter': cod_caracter}
self.solicitud['receptor'].update(d)
return True | [
"def",
"AgregarReceptor",
"(",
"self",
",",
"cod_caracter",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"'codCaracter'",
":",
"cod_caracter",
"}",
"self",
".",
"solicitud",
"[",
"'receptor'",
"]",
".",
"update",
"(",
"d",
")",
"return",
"True"
] | Agrego los datos del receptor a la liq. | [
"Agrego",
"los",
"datos",
"del",
"receptor",
"a",
"la",
"liq",
"."
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslsp.py#L239-L243 |
231,367 | reingart/pyafipws | wslsp.py | WSLSP.AgregarOperador | def AgregarOperador(self, cuit, iibb=None, nro_ruca=None, nro_renspa=None,
cuit_autorizado=None, **kwargs):
"Agrego los datos del operador a la liq."
d = {'cuit': cuit,
'iibb': iibb,
'nroRUCA': nro_ruca,
'nroRenspa': nro_renspa,
'cuitAutorizado': cuit_autorizado}
self.solicitud['receptor']['operador'] = d
return True | python | def AgregarOperador(self, cuit, iibb=None, nro_ruca=None, nro_renspa=None,
cuit_autorizado=None, **kwargs):
"Agrego los datos del operador a la liq."
d = {'cuit': cuit,
'iibb': iibb,
'nroRUCA': nro_ruca,
'nroRenspa': nro_renspa,
'cuitAutorizado': cuit_autorizado}
self.solicitud['receptor']['operador'] = d
return True | [
"def",
"AgregarOperador",
"(",
"self",
",",
"cuit",
",",
"iibb",
"=",
"None",
",",
"nro_ruca",
"=",
"None",
",",
"nro_renspa",
"=",
"None",
",",
"cuit_autorizado",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"'cuit'",
":",
"cuit",
... | Agrego los datos del operador a la liq. | [
"Agrego",
"los",
"datos",
"del",
"operador",
"a",
"la",
"liq",
"."
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslsp.py#L246-L255 |
231,368 | reingart/pyafipws | wslsp.py | WSLSP.AgregarAjusteFisico | def AgregarAjusteFisico(self, cantidad, cantidad_cabezas=None,
cantidad_kg_vivo=None, **kwargs):
"Agrega campos al detalle de item por un ajuste fisico"
d = {'cantidad': cantidad,
'cantidadCabezas': cantidad_cabezas,
'cantidadKgVivo': cantidad_kg_vivo,
}
item_liq = self.solicitud['itemDetalleAjusteLiquidacion'][-1]
item_liq['ajusteFisico'] = d
return True | python | def AgregarAjusteFisico(self, cantidad, cantidad_cabezas=None,
cantidad_kg_vivo=None, **kwargs):
"Agrega campos al detalle de item por un ajuste fisico"
d = {'cantidad': cantidad,
'cantidadCabezas': cantidad_cabezas,
'cantidadKgVivo': cantidad_kg_vivo,
}
item_liq = self.solicitud['itemDetalleAjusteLiquidacion'][-1]
item_liq['ajusteFisico'] = d
return True | [
"def",
"AgregarAjusteFisico",
"(",
"self",
",",
"cantidad",
",",
"cantidad_cabezas",
"=",
"None",
",",
"cantidad_kg_vivo",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"'cantidad'",
":",
"cantidad",
",",
"'cantidadCabezas'",
":",
"cantidad_... | Agrega campos al detalle de item por un ajuste fisico | [
"Agrega",
"campos",
"al",
"detalle",
"de",
"item",
"por",
"un",
"ajuste",
"fisico"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslsp.py#L535-L544 |
231,369 | reingart/pyafipws | wslsp.py | WSLSP.AgregarAjusteMonetario | def AgregarAjusteMonetario(self, precio_unitario, precio_recupero=None,
**kwargs):
"Agrega campos al detalle de item por un ajuste monetario"
d = {'precioUnitario': precio_unitario,
'precioRecupero': precio_recupero,
}
item_liq = self.solicitud['itemDetalleAjusteLiquidacion'][-1]
item_liq['ajusteMonetario'] = d
return True | python | def AgregarAjusteMonetario(self, precio_unitario, precio_recupero=None,
**kwargs):
"Agrega campos al detalle de item por un ajuste monetario"
d = {'precioUnitario': precio_unitario,
'precioRecupero': precio_recupero,
}
item_liq = self.solicitud['itemDetalleAjusteLiquidacion'][-1]
item_liq['ajusteMonetario'] = d
return True | [
"def",
"AgregarAjusteMonetario",
"(",
"self",
",",
"precio_unitario",
",",
"precio_recupero",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"'precioUnitario'",
":",
"precio_unitario",
",",
"'precioRecupero'",
":",
"precio_recupero",
",",
"}",
... | Agrega campos al detalle de item por un ajuste monetario | [
"Agrega",
"campos",
"al",
"detalle",
"de",
"item",
"por",
"un",
"ajuste",
"monetario"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslsp.py#L547-L555 |
231,370 | reingart/pyafipws | wslsp.py | WSLSP.ConsultarLocalidades | def ConsultarLocalidades(self, cod_provincia, sep="||"):
"Consulta las localidades habilitadas"
ret = self.client.consultarLocalidadesPorProvincia(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
solicitud={'codProvincia': cod_provincia},
)['respuesta']
self.__analizar_errores(ret)
array = ret.get('localidad', [])
if sep is None:
return dict([(it['codigo'], it['descripcion']) for it in array])
else:
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigo'], it['descripcion']) for it in array] | python | def ConsultarLocalidades(self, cod_provincia, sep="||"):
"Consulta las localidades habilitadas"
ret = self.client.consultarLocalidadesPorProvincia(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
solicitud={'codProvincia': cod_provincia},
)['respuesta']
self.__analizar_errores(ret)
array = ret.get('localidad', [])
if sep is None:
return dict([(it['codigo'], it['descripcion']) for it in array])
else:
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigo'], it['descripcion']) for it in array] | [
"def",
"ConsultarLocalidades",
"(",
"self",
",",
"cod_provincia",
",",
"sep",
"=",
"\"||\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"consultarLocalidadesPorProvincia",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'",
"... | Consulta las localidades habilitadas | [
"Consulta",
"las",
"localidades",
"habilitadas"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslsp.py#L605-L619 |
231,371 | reingart/pyafipws | padron.py | PadronAFIP.Descargar | def Descargar(self, url=URL, filename="padron.txt", proxy=None):
"Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado"
proxies = {}
if proxy:
proxies['http'] = proxy
proxies['https'] = proxy
proxy_handler = urllib2.ProxyHandler(proxies)
print "Abriendo URL %s ..." % url
req = urllib2.Request(url)
if os.path.exists(filename):
http_date = formatdate(timeval=os.path.getmtime(filename),
localtime=False, usegmt=True)
req.add_header('If-Modified-Since', http_date)
try:
web = urllib2.urlopen(req)
except urllib2.HTTPError, e:
if e.code == 304:
print "No modificado desde", http_date
return 304
else:
raise
# leer info del request:
meta = web.info()
lenght = float(meta['Content-Length'])
date = meta['Last-Modified']
tmp = open(filename + ".zip", "wb")
print "Guardando"
size = 0
p0 = None
while True:
p = int(size / lenght * 100)
if p0 is None or p>p0:
print "Leyendo ... %0d %%" % p
p0 = p
data = web.read(1024*100)
size = size + len(data)
if not data:
print "Descarga Terminada!"
break
tmp.write(data)
print "Abriendo ZIP..."
tmp.close()
web.close()
uf = open(filename + ".zip", "rb")
zf = zipfile.ZipFile(uf)
for fn in zf.namelist():
print "descomprimiendo", fn
tf = open(filename, "wb")
tf.write(zf.read(fn))
tf.close()
return 200 | python | def Descargar(self, url=URL, filename="padron.txt", proxy=None):
"Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado"
proxies = {}
if proxy:
proxies['http'] = proxy
proxies['https'] = proxy
proxy_handler = urllib2.ProxyHandler(proxies)
print "Abriendo URL %s ..." % url
req = urllib2.Request(url)
if os.path.exists(filename):
http_date = formatdate(timeval=os.path.getmtime(filename),
localtime=False, usegmt=True)
req.add_header('If-Modified-Since', http_date)
try:
web = urllib2.urlopen(req)
except urllib2.HTTPError, e:
if e.code == 304:
print "No modificado desde", http_date
return 304
else:
raise
# leer info del request:
meta = web.info()
lenght = float(meta['Content-Length'])
date = meta['Last-Modified']
tmp = open(filename + ".zip", "wb")
print "Guardando"
size = 0
p0 = None
while True:
p = int(size / lenght * 100)
if p0 is None or p>p0:
print "Leyendo ... %0d %%" % p
p0 = p
data = web.read(1024*100)
size = size + len(data)
if not data:
print "Descarga Terminada!"
break
tmp.write(data)
print "Abriendo ZIP..."
tmp.close()
web.close()
uf = open(filename + ".zip", "rb")
zf = zipfile.ZipFile(uf)
for fn in zf.namelist():
print "descomprimiendo", fn
tf = open(filename, "wb")
tf.write(zf.read(fn))
tf.close()
return 200 | [
"def",
"Descargar",
"(",
"self",
",",
"url",
"=",
"URL",
",",
"filename",
"=",
"\"padron.txt\"",
",",
"proxy",
"=",
"None",
")",
":",
"proxies",
"=",
"{",
"}",
"if",
"proxy",
":",
"proxies",
"[",
"'http'",
"]",
"=",
"proxy",
"proxies",
"[",
"'https'"... | Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado | [
"Descarga",
"el",
"archivo",
"de",
"AFIP",
"devuelve",
"200",
"o",
"304",
"si",
"no",
"fue",
"modificado"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/padron.py#L129-L179 |
231,372 | reingart/pyafipws | padron.py | PadronAFIP.Procesar | def Procesar(self, filename="padron.txt", borrar=False):
"Analiza y crea la base de datos interna sqlite para consultas"
f = open(filename, "r")
keys = [k for k, l, t, d in FORMATO]
# conversion a planilla csv (no usado)
if False and not os.path.exists("padron.csv"):
csvfile = open('padron.csv', 'wb')
import csv
wr = csv.writer(csvfile, delimiter=',',
quotechar='"', quoting=csv.QUOTE_MINIMAL)
for i, l in enumerate(f):
if i % 100000 == 0:
print "Progreso: %d registros" % i
r = leer(l, FORMATO)
row = [r[k] for k in keys]
wr.writerow(row)
csvfile.close()
f.seek(0)
if os.path.exists(self.db_path) and borrar:
os.remove(self.db_path)
if True:
db = db = sqlite3.connect(self.db_path)
c = db.cursor()
c.execute("CREATE TABLE padron ("
"nro_doc INTEGER, "
"denominacion VARCHAR(30), "
"imp_ganancias VARCHAR(2), "
"imp_iva VARCHAR(2), "
"monotributo VARCHAR(1), "
"integrante_soc VARCHAR(1), "
"empleador VARCHAR(1), "
"actividad_monotributo VARCHAR(2), "
"tipo_doc INTEGER, "
"cat_iva INTEGER DEFAULT NULL, "
"email VARCHAR(250), "
"PRIMARY KEY (tipo_doc, nro_doc)"
");")
c.execute("CREATE TABLE domicilio ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"tipo_doc INTEGER, "
"nro_doc INTEGER, "
"direccion TEXT, "
"FOREIGN KEY (tipo_doc, nro_doc) REFERENCES padron "
");")
# importar los datos a la base sqlite
for i, l in enumerate(f):
if i % 10000 == 0: print i
l = l.strip("\x00")
r = leer(l, FORMATO)
params = [r[k] for k in keys]
params[8] = 80 # agrego tipo_doc = CUIT
params[9] = None # cat_iva no viene de AFIP
placeholders = ", ".join(["?"] * len(params))
c.execute("INSERT INTO padron VALUES (%s)" % placeholders,
params)
db.commit()
c.close()
db.close() | python | def Procesar(self, filename="padron.txt", borrar=False):
"Analiza y crea la base de datos interna sqlite para consultas"
f = open(filename, "r")
keys = [k for k, l, t, d in FORMATO]
# conversion a planilla csv (no usado)
if False and not os.path.exists("padron.csv"):
csvfile = open('padron.csv', 'wb')
import csv
wr = csv.writer(csvfile, delimiter=',',
quotechar='"', quoting=csv.QUOTE_MINIMAL)
for i, l in enumerate(f):
if i % 100000 == 0:
print "Progreso: %d registros" % i
r = leer(l, FORMATO)
row = [r[k] for k in keys]
wr.writerow(row)
csvfile.close()
f.seek(0)
if os.path.exists(self.db_path) and borrar:
os.remove(self.db_path)
if True:
db = db = sqlite3.connect(self.db_path)
c = db.cursor()
c.execute("CREATE TABLE padron ("
"nro_doc INTEGER, "
"denominacion VARCHAR(30), "
"imp_ganancias VARCHAR(2), "
"imp_iva VARCHAR(2), "
"monotributo VARCHAR(1), "
"integrante_soc VARCHAR(1), "
"empleador VARCHAR(1), "
"actividad_monotributo VARCHAR(2), "
"tipo_doc INTEGER, "
"cat_iva INTEGER DEFAULT NULL, "
"email VARCHAR(250), "
"PRIMARY KEY (tipo_doc, nro_doc)"
");")
c.execute("CREATE TABLE domicilio ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"tipo_doc INTEGER, "
"nro_doc INTEGER, "
"direccion TEXT, "
"FOREIGN KEY (tipo_doc, nro_doc) REFERENCES padron "
");")
# importar los datos a la base sqlite
for i, l in enumerate(f):
if i % 10000 == 0: print i
l = l.strip("\x00")
r = leer(l, FORMATO)
params = [r[k] for k in keys]
params[8] = 80 # agrego tipo_doc = CUIT
params[9] = None # cat_iva no viene de AFIP
placeholders = ", ".join(["?"] * len(params))
c.execute("INSERT INTO padron VALUES (%s)" % placeholders,
params)
db.commit()
c.close()
db.close() | [
"def",
"Procesar",
"(",
"self",
",",
"filename",
"=",
"\"padron.txt\"",
",",
"borrar",
"=",
"False",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"keys",
"=",
"[",
"k",
"for",
"k",
",",
"l",
",",
"t",
",",
"d",
"in",
"FORMATO",... | Analiza y crea la base de datos interna sqlite para consultas | [
"Analiza",
"y",
"crea",
"la",
"base",
"de",
"datos",
"interna",
"sqlite",
"para",
"consultas"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/padron.py#L182-L239 |
231,373 | reingart/pyafipws | padron.py | PadronAFIP.Buscar | def Buscar(self, nro_doc, tipo_doc=80):
"Devuelve True si fue encontrado y establece atributos con datos"
# cuit: codigo único de identificación tributaria del contribuyente
# (sin guiones)
self.cursor.execute("SELECT * FROM padron WHERE "
" tipo_doc=? AND nro_doc=?", [tipo_doc, nro_doc])
row = self.cursor.fetchone()
for key in [k for k, l, t, d in FORMATO]:
if row:
val = row[key]
if not isinstance(val, basestring):
val = str(row[key])
setattr(self, key, val)
else:
setattr(self, key, '')
if self.tipo_doc == 80:
self.cuit = self.nro_doc
elif self.tipo_doc == 96:
self.dni = self.nro_doc
# determinar categoría de IVA (tentativa)
try:
cat_iva = int(self.cat_iva)
except ValueError:
cat_iva = None
if cat_iva:
pass
elif self.imp_iva in ('AC', 'S'):
self.cat_iva = 1 # RI
elif self.imp_iva == 'EX':
self.cat_iva = 4 # EX
elif self.monotributo:
self.cat_iva = 6 # MT
else:
self.cat_iva = 5 # CF
return True if row else False | python | def Buscar(self, nro_doc, tipo_doc=80):
"Devuelve True si fue encontrado y establece atributos con datos"
# cuit: codigo único de identificación tributaria del contribuyente
# (sin guiones)
self.cursor.execute("SELECT * FROM padron WHERE "
" tipo_doc=? AND nro_doc=?", [tipo_doc, nro_doc])
row = self.cursor.fetchone()
for key in [k for k, l, t, d in FORMATO]:
if row:
val = row[key]
if not isinstance(val, basestring):
val = str(row[key])
setattr(self, key, val)
else:
setattr(self, key, '')
if self.tipo_doc == 80:
self.cuit = self.nro_doc
elif self.tipo_doc == 96:
self.dni = self.nro_doc
# determinar categoría de IVA (tentativa)
try:
cat_iva = int(self.cat_iva)
except ValueError:
cat_iva = None
if cat_iva:
pass
elif self.imp_iva in ('AC', 'S'):
self.cat_iva = 1 # RI
elif self.imp_iva == 'EX':
self.cat_iva = 4 # EX
elif self.monotributo:
self.cat_iva = 6 # MT
else:
self.cat_iva = 5 # CF
return True if row else False | [
"def",
"Buscar",
"(",
"self",
",",
"nro_doc",
",",
"tipo_doc",
"=",
"80",
")",
":",
"# cuit: codigo único de identificación tributaria del contribuyente",
"# (sin guiones)",
"self",
".",
"cursor",
".",
"execute",
"(",
"\"SELECT * FROM padron WHERE \"",
"\" tipo_doc=? ... | Devuelve True si fue encontrado y establece atributos con datos | [
"Devuelve",
"True",
"si",
"fue",
"encontrado",
"y",
"establece",
"atributos",
"con",
"datos"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/padron.py#L242-L276 |
231,374 | reingart/pyafipws | padron.py | PadronAFIP.ConsultarDomicilios | def ConsultarDomicilios(self, nro_doc, tipo_doc=80, cat_iva=None):
"Busca los domicilios, devuelve la cantidad y establece la lista"
self.cursor.execute("SELECT direccion FROM domicilio WHERE "
" tipo_doc=? AND nro_doc=? ORDER BY id ",
[tipo_doc, nro_doc])
filas = self.cursor.fetchall()
self.domicilios = [fila['direccion'] for fila in filas]
return len(filas) | python | def ConsultarDomicilios(self, nro_doc, tipo_doc=80, cat_iva=None):
"Busca los domicilios, devuelve la cantidad y establece la lista"
self.cursor.execute("SELECT direccion FROM domicilio WHERE "
" tipo_doc=? AND nro_doc=? ORDER BY id ",
[tipo_doc, nro_doc])
filas = self.cursor.fetchall()
self.domicilios = [fila['direccion'] for fila in filas]
return len(filas) | [
"def",
"ConsultarDomicilios",
"(",
"self",
",",
"nro_doc",
",",
"tipo_doc",
"=",
"80",
",",
"cat_iva",
"=",
"None",
")",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"\"SELECT direccion FROM domicilio WHERE \"",
"\" tipo_doc=? AND nro_doc=? ORDER BY id \"",
",",
... | Busca los domicilios, devuelve la cantidad y establece la lista | [
"Busca",
"los",
"domicilios",
"devuelve",
"la",
"cantidad",
"y",
"establece",
"la",
"lista"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/padron.py#L279-L286 |
231,375 | reingart/pyafipws | padron.py | PadronAFIP.Guardar | def Guardar(self, tipo_doc, nro_doc, denominacion, cat_iva, direccion,
email, imp_ganancias='NI', imp_iva='NI', monotributo='NI',
integrante_soc='N', empleador='N'):
"Agregar o actualizar los datos del cliente"
if self.Buscar(nro_doc, tipo_doc):
sql = ("UPDATE padron SET denominacion=?, cat_iva=?, email=?, "
"imp_ganancias=?, imp_iva=?, monotributo=?, "
"integrante_soc=?, empleador=? "
"WHERE tipo_doc=? AND nro_doc=?")
params = [denominacion, cat_iva, email, imp_ganancias,
imp_iva, monotributo, integrante_soc, empleador,
tipo_doc, nro_doc]
else:
sql = ("INSERT INTO padron (tipo_doc, nro_doc, denominacion, "
"cat_iva, email, imp_ganancias, imp_iva, monotributo, "
"integrante_soc, empleador) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
params = [tipo_doc, nro_doc, denominacion, cat_iva, email,
imp_ganancias, imp_iva, monotributo,
integrante_soc, empleador]
self.cursor.execute(sql, params)
# agregar el domicilio solo si no existe:
if direccion:
self.cursor.execute("SELECT * FROM domicilio WHERE direccion=? "
"AND tipo_doc=? AND nro_doc=?",
[direccion, tipo_doc, nro_doc])
if self.cursor.rowcount < 0:
sql = ("INSERT INTO domicilio (nro_doc, tipo_doc, direccion)"
"VALUES (?, ?, ?)")
self.cursor.execute(sql, [nro_doc, tipo_doc, direccion])
self.db.commit()
return True | python | def Guardar(self, tipo_doc, nro_doc, denominacion, cat_iva, direccion,
email, imp_ganancias='NI', imp_iva='NI', monotributo='NI',
integrante_soc='N', empleador='N'):
"Agregar o actualizar los datos del cliente"
if self.Buscar(nro_doc, tipo_doc):
sql = ("UPDATE padron SET denominacion=?, cat_iva=?, email=?, "
"imp_ganancias=?, imp_iva=?, monotributo=?, "
"integrante_soc=?, empleador=? "
"WHERE tipo_doc=? AND nro_doc=?")
params = [denominacion, cat_iva, email, imp_ganancias,
imp_iva, monotributo, integrante_soc, empleador,
tipo_doc, nro_doc]
else:
sql = ("INSERT INTO padron (tipo_doc, nro_doc, denominacion, "
"cat_iva, email, imp_ganancias, imp_iva, monotributo, "
"integrante_soc, empleador) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
params = [tipo_doc, nro_doc, denominacion, cat_iva, email,
imp_ganancias, imp_iva, monotributo,
integrante_soc, empleador]
self.cursor.execute(sql, params)
# agregar el domicilio solo si no existe:
if direccion:
self.cursor.execute("SELECT * FROM domicilio WHERE direccion=? "
"AND tipo_doc=? AND nro_doc=?",
[direccion, tipo_doc, nro_doc])
if self.cursor.rowcount < 0:
sql = ("INSERT INTO domicilio (nro_doc, tipo_doc, direccion)"
"VALUES (?, ?, ?)")
self.cursor.execute(sql, [nro_doc, tipo_doc, direccion])
self.db.commit()
return True | [
"def",
"Guardar",
"(",
"self",
",",
"tipo_doc",
",",
"nro_doc",
",",
"denominacion",
",",
"cat_iva",
",",
"direccion",
",",
"email",
",",
"imp_ganancias",
"=",
"'NI'",
",",
"imp_iva",
"=",
"'NI'",
",",
"monotributo",
"=",
"'NI'",
",",
"integrante_soc",
"="... | Agregar o actualizar los datos del cliente | [
"Agregar",
"o",
"actualizar",
"los",
"datos",
"del",
"cliente"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/padron.py#L289-L320 |
231,376 | reingart/pyafipws | wslum.py | WSLUM.ConsultarPuntosVentas | def ConsultarPuntosVentas(self, sep="||"):
"Retorna los puntos de ventas autorizados para la utilizacion de WS"
ret = self.client.consultarPuntosVenta(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['respuesta']
self.__analizar_errores(ret)
array = ret.get('puntoVenta', [])
if sep is None:
return dict([(it['codigo'], it['descripcion']) for it in array])
else:
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigo'], it['descripcion']) for it in array] | python | def ConsultarPuntosVentas(self, sep="||"):
"Retorna los puntos de ventas autorizados para la utilizacion de WS"
ret = self.client.consultarPuntosVenta(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['respuesta']
self.__analizar_errores(ret)
array = ret.get('puntoVenta', [])
if sep is None:
return dict([(it['codigo'], it['descripcion']) for it in array])
else:
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigo'], it['descripcion']) for it in array] | [
"def",
"ConsultarPuntosVentas",
"(",
"self",
",",
"sep",
"=",
"\"||\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"consultarPuntosVenta",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'",
":",
"self",
".",
"Sign",
",",... | Retorna los puntos de ventas autorizados para la utilizacion de WS | [
"Retorna",
"los",
"puntos",
"de",
"ventas",
"autorizados",
"para",
"la",
"utilizacion",
"de",
"WS"
] | ee87cfe4ac12285ab431df5fec257f103042d1ab | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslum.py#L576-L589 |
231,377 | FPGAwars/apio | apio/resources.py | Resources.list_boards | def list_boards(self):
"""Return a list with all the supported boards"""
# Print table
click.echo('\nSupported boards:\n')
BOARDLIST_TPL = ('{board:25} {fpga:20} {type:<5} {size:<5} {pack:<10}')
terminal_width, _ = click.get_terminal_size()
click.echo('-' * terminal_width)
click.echo(BOARDLIST_TPL.format(
board=click.style('Board', fg='cyan'), fpga='FPGA', type='Type',
size='Size', pack='Pack'))
click.echo('-' * terminal_width)
for board in self.boards:
fpga = self.boards.get(board).get('fpga')
click.echo(BOARDLIST_TPL.format(
board=click.style(board, fg='cyan'),
fpga=fpga,
type=self.fpgas.get(fpga).get('type'),
size=self.fpgas.get(fpga).get('size'),
pack=self.fpgas.get(fpga).get('pack')))
click.secho(BOARDS_MSG, fg='green') | python | def list_boards(self):
# Print table
click.echo('\nSupported boards:\n')
BOARDLIST_TPL = ('{board:25} {fpga:20} {type:<5} {size:<5} {pack:<10}')
terminal_width, _ = click.get_terminal_size()
click.echo('-' * terminal_width)
click.echo(BOARDLIST_TPL.format(
board=click.style('Board', fg='cyan'), fpga='FPGA', type='Type',
size='Size', pack='Pack'))
click.echo('-' * terminal_width)
for board in self.boards:
fpga = self.boards.get(board).get('fpga')
click.echo(BOARDLIST_TPL.format(
board=click.style(board, fg='cyan'),
fpga=fpga,
type=self.fpgas.get(fpga).get('type'),
size=self.fpgas.get(fpga).get('size'),
pack=self.fpgas.get(fpga).get('pack')))
click.secho(BOARDS_MSG, fg='green') | [
"def",
"list_boards",
"(",
"self",
")",
":",
"# Print table",
"click",
".",
"echo",
"(",
"'\\nSupported boards:\\n'",
")",
"BOARDLIST_TPL",
"=",
"(",
"'{board:25} {fpga:20} {type:<5} {size:<5} {pack:<10}'",
")",
"terminal_width",
",",
"_",
"=",
"click",
".",
"get_term... | Return a list with all the supported boards | [
"Return",
"a",
"list",
"with",
"all",
"the",
"supported",
"boards"
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/resources.py#L112-L136 |
231,378 | FPGAwars/apio | apio/resources.py | Resources.list_fpgas | def list_fpgas(self):
"""Return a list with all the supported FPGAs"""
# Print table
click.echo('\nSupported FPGAs:\n')
FPGALIST_TPL = ('{fpga:30} {type:<5} {size:<5} {pack:<10}')
terminal_width, _ = click.get_terminal_size()
click.echo('-' * terminal_width)
click.echo(FPGALIST_TPL.format(
fpga=click.style('FPGA', fg='cyan'), type='Type',
size='Size', pack='Pack'))
click.echo('-' * terminal_width)
for fpga in self.fpgas:
click.echo(FPGALIST_TPL.format(
fpga=click.style(fpga, fg='cyan'),
type=self.fpgas.get(fpga).get('type'),
size=self.fpgas.get(fpga).get('size'),
pack=self.fpgas.get(fpga).get('pack'))) | python | def list_fpgas(self):
# Print table
click.echo('\nSupported FPGAs:\n')
FPGALIST_TPL = ('{fpga:30} {type:<5} {size:<5} {pack:<10}')
terminal_width, _ = click.get_terminal_size()
click.echo('-' * terminal_width)
click.echo(FPGALIST_TPL.format(
fpga=click.style('FPGA', fg='cyan'), type='Type',
size='Size', pack='Pack'))
click.echo('-' * terminal_width)
for fpga in self.fpgas:
click.echo(FPGALIST_TPL.format(
fpga=click.style(fpga, fg='cyan'),
type=self.fpgas.get(fpga).get('type'),
size=self.fpgas.get(fpga).get('size'),
pack=self.fpgas.get(fpga).get('pack'))) | [
"def",
"list_fpgas",
"(",
"self",
")",
":",
"# Print table",
"click",
".",
"echo",
"(",
"'\\nSupported FPGAs:\\n'",
")",
"FPGALIST_TPL",
"=",
"(",
"'{fpga:30} {type:<5} {size:<5} {pack:<10}'",
")",
"terminal_width",
",",
"_",
"=",
"click",
".",
"get_terminal_size",
... | Return a list with all the supported FPGAs | [
"Return",
"a",
"list",
"with",
"all",
"the",
"supported",
"FPGAs"
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/resources.py#L138-L158 |
231,379 | FPGAwars/apio | apio/commands/system.py | cli | def cli(ctx, lsftdi, lsusb, lsserial, info):
"""System tools.\n
Install with `apio install system`"""
exit_code = 0
if lsftdi:
exit_code = System().lsftdi()
elif lsusb:
exit_code = System().lsusb()
elif lsserial:
exit_code = System().lsserial()
elif info:
click.secho('Platform: ', nl=False)
click.secho(get_systype(), fg='yellow')
else:
click.secho(ctx.get_help())
ctx.exit(exit_code) | python | def cli(ctx, lsftdi, lsusb, lsserial, info):
exit_code = 0
if lsftdi:
exit_code = System().lsftdi()
elif lsusb:
exit_code = System().lsusb()
elif lsserial:
exit_code = System().lsserial()
elif info:
click.secho('Platform: ', nl=False)
click.secho(get_systype(), fg='yellow')
else:
click.secho(ctx.get_help())
ctx.exit(exit_code) | [
"def",
"cli",
"(",
"ctx",
",",
"lsftdi",
",",
"lsusb",
",",
"lsserial",
",",
"info",
")",
":",
"exit_code",
"=",
"0",
"if",
"lsftdi",
":",
"exit_code",
"=",
"System",
"(",
")",
".",
"lsftdi",
"(",
")",
"elif",
"lsusb",
":",
"exit_code",
"=",
"Syste... | System tools.\n
Install with `apio install system` | [
"System",
"tools",
".",
"\\",
"n",
"Install",
"with",
"apio",
"install",
"system"
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/system.py#L23-L41 |
231,380 | FPGAwars/apio | apio/managers/scons.py | SCons.run | def run(self, command, variables=[], board=None, packages=[]):
"""Executes scons for building"""
# -- Check for the SConstruct file
if not isfile(util.safe_join(util.get_project_dir(), 'SConstruct')):
variables += ['-f']
variables += [util.safe_join(
util.get_folder('resources'), 'SConstruct')]
else:
click.secho('Info: use custom SConstruct file')
# -- Resolve packages
if self.profile.check_exe_default():
# Run on `default` config mode
if not util.resolve_packages(
packages,
self.profile.packages,
self.resources.distribution.get('packages')
):
# Exit if a package is not installed
raise Exception
else:
click.secho('Info: native config mode')
# -- Execute scons
return self._execute_scons(command, variables, board) | python | def run(self, command, variables=[], board=None, packages=[]):
# -- Check for the SConstruct file
if not isfile(util.safe_join(util.get_project_dir(), 'SConstruct')):
variables += ['-f']
variables += [util.safe_join(
util.get_folder('resources'), 'SConstruct')]
else:
click.secho('Info: use custom SConstruct file')
# -- Resolve packages
if self.profile.check_exe_default():
# Run on `default` config mode
if not util.resolve_packages(
packages,
self.profile.packages,
self.resources.distribution.get('packages')
):
# Exit if a package is not installed
raise Exception
else:
click.secho('Info: native config mode')
# -- Execute scons
return self._execute_scons(command, variables, board) | [
"def",
"run",
"(",
"self",
",",
"command",
",",
"variables",
"=",
"[",
"]",
",",
"board",
"=",
"None",
",",
"packages",
"=",
"[",
"]",
")",
":",
"# -- Check for the SConstruct file",
"if",
"not",
"isfile",
"(",
"util",
".",
"safe_join",
"(",
"util",
".... | Executes scons for building | [
"Executes",
"scons",
"for",
"building"
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/managers/scons.py#L301-L326 |
231,381 | FPGAwars/apio | apio/commands/time.py | cli | def cli(ctx, board, fpga, pack, type, size, project_dir,
verbose, verbose_yosys, verbose_arachne):
"""Bitstream timing analysis."""
# Run scons
exit_code = SCons(project_dir).time({
'board': board,
'fpga': fpga,
'size': size,
'type': type,
'pack': pack,
'verbose': {
'all': verbose,
'yosys': verbose_yosys,
'arachne': verbose_arachne
}
})
ctx.exit(exit_code) | python | def cli(ctx, board, fpga, pack, type, size, project_dir,
verbose, verbose_yosys, verbose_arachne):
# Run scons
exit_code = SCons(project_dir).time({
'board': board,
'fpga': fpga,
'size': size,
'type': type,
'pack': pack,
'verbose': {
'all': verbose,
'yosys': verbose_yosys,
'arachne': verbose_arachne
}
})
ctx.exit(exit_code) | [
"def",
"cli",
"(",
"ctx",
",",
"board",
",",
"fpga",
",",
"pack",
",",
"type",
",",
"size",
",",
"project_dir",
",",
"verbose",
",",
"verbose_yosys",
",",
"verbose_arachne",
")",
":",
"# Run scons",
"exit_code",
"=",
"SCons",
"(",
"project_dir",
")",
"."... | Bitstream timing analysis. | [
"Bitstream",
"timing",
"analysis",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/time.py#L37-L54 |
231,382 | FPGAwars/apio | apio/commands/init.py | cli | def cli(ctx, board, scons, project_dir, sayyes):
"""Manage apio projects."""
if scons:
Project().create_sconstruct(project_dir, sayyes)
elif board:
Project().create_ini(board, project_dir, sayyes)
else:
click.secho(ctx.get_help()) | python | def cli(ctx, board, scons, project_dir, sayyes):
if scons:
Project().create_sconstruct(project_dir, sayyes)
elif board:
Project().create_ini(board, project_dir, sayyes)
else:
click.secho(ctx.get_help()) | [
"def",
"cli",
"(",
"ctx",
",",
"board",
",",
"scons",
",",
"project_dir",
",",
"sayyes",
")",
":",
"if",
"scons",
":",
"Project",
"(",
")",
".",
"create_sconstruct",
"(",
"project_dir",
",",
"sayyes",
")",
"elif",
"board",
":",
"Project",
"(",
")",
"... | Manage apio projects. | [
"Manage",
"apio",
"projects",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/init.py#L27-L35 |
231,383 | FPGAwars/apio | apio/commands/clean.py | cli | def cli(ctx, project_dir):
"""Clean the previous generated files."""
exit_code = SCons(project_dir).clean()
ctx.exit(exit_code) | python | def cli(ctx, project_dir):
exit_code = SCons(project_dir).clean()
ctx.exit(exit_code) | [
"def",
"cli",
"(",
"ctx",
",",
"project_dir",
")",
":",
"exit_code",
"=",
"SCons",
"(",
"project_dir",
")",
".",
"clean",
"(",
")",
"ctx",
".",
"exit",
"(",
"exit_code",
")"
] | Clean the previous generated files. | [
"Clean",
"the",
"previous",
"generated",
"files",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/clean.py#L21-L24 |
231,384 | FPGAwars/apio | apio/commands/lint.py | cli | def cli(ctx, all, top, nostyle, nowarn, warn, project_dir):
"""Lint the verilog code."""
exit_code = SCons(project_dir).lint({
'all': all,
'top': top,
'nostyle': nostyle,
'nowarn': nowarn,
'warn': warn
})
ctx.exit(exit_code) | python | def cli(ctx, all, top, nostyle, nowarn, warn, project_dir):
exit_code = SCons(project_dir).lint({
'all': all,
'top': top,
'nostyle': nostyle,
'nowarn': nowarn,
'warn': warn
})
ctx.exit(exit_code) | [
"def",
"cli",
"(",
"ctx",
",",
"all",
",",
"top",
",",
"nostyle",
",",
"nowarn",
",",
"warn",
",",
"project_dir",
")",
":",
"exit_code",
"=",
"SCons",
"(",
"project_dir",
")",
".",
"lint",
"(",
"{",
"'all'",
":",
"all",
",",
"'top'",
":",
"top",
... | Lint the verilog code. | [
"Lint",
"the",
"verilog",
"code",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/lint.py#L31-L41 |
231,385 | FPGAwars/apio | apio/managers/project.py | Project.create_sconstruct | def create_sconstruct(self, project_dir='', sayyes=False):
"""Creates a default SConstruct file"""
project_dir = util.check_dir(project_dir)
sconstruct_name = 'SConstruct'
sconstruct_path = util.safe_join(project_dir, sconstruct_name)
local_sconstruct_path = util.safe_join(
util.get_folder('resources'), sconstruct_name)
if isfile(sconstruct_path):
# -- If sayyes, skip the question
if sayyes:
self._copy_sconstruct_file(sconstruct_name, sconstruct_path,
local_sconstruct_path)
else:
click.secho(
'Warning: {} file already exists'.format(sconstruct_name),
fg='yellow')
if click.confirm('Do you want to replace it?'):
self._copy_sconstruct_file(sconstruct_name,
sconstruct_path,
local_sconstruct_path)
else:
click.secho('Abort!', fg='red')
else:
self._copy_sconstruct_file(sconstruct_name, sconstruct_path,
local_sconstruct_path) | python | def create_sconstruct(self, project_dir='', sayyes=False):
project_dir = util.check_dir(project_dir)
sconstruct_name = 'SConstruct'
sconstruct_path = util.safe_join(project_dir, sconstruct_name)
local_sconstruct_path = util.safe_join(
util.get_folder('resources'), sconstruct_name)
if isfile(sconstruct_path):
# -- If sayyes, skip the question
if sayyes:
self._copy_sconstruct_file(sconstruct_name, sconstruct_path,
local_sconstruct_path)
else:
click.secho(
'Warning: {} file already exists'.format(sconstruct_name),
fg='yellow')
if click.confirm('Do you want to replace it?'):
self._copy_sconstruct_file(sconstruct_name,
sconstruct_path,
local_sconstruct_path)
else:
click.secho('Abort!', fg='red')
else:
self._copy_sconstruct_file(sconstruct_name, sconstruct_path,
local_sconstruct_path) | [
"def",
"create_sconstruct",
"(",
"self",
",",
"project_dir",
"=",
"''",
",",
"sayyes",
"=",
"False",
")",
":",
"project_dir",
"=",
"util",
".",
"check_dir",
"(",
"project_dir",
")",
"sconstruct_name",
"=",
"'SConstruct'",
"sconstruct_path",
"=",
"util",
".",
... | Creates a default SConstruct file | [
"Creates",
"a",
"default",
"SConstruct",
"file"
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/managers/project.py#L29-L58 |
231,386 | FPGAwars/apio | apio/managers/project.py | Project.create_ini | def create_ini(self, board, project_dir='', sayyes=False):
"""Creates a new apio project file"""
project_dir = util.check_dir(project_dir)
ini_path = util.safe_join(project_dir, PROJECT_FILENAME)
# Check board
boards = Resources().boards
if board not in boards.keys():
click.secho(
'Error: no such board \'{}\''.format(board),
fg='red')
sys.exit(1)
if isfile(ini_path):
# -- If sayyes, skip the question
if sayyes:
self._create_ini_file(board, ini_path, PROJECT_FILENAME)
else:
click.secho(
'Warning: {} file already exists'.format(PROJECT_FILENAME),
fg='yellow')
if click.confirm('Do you want to replace it?'):
self._create_ini_file(board, ini_path, PROJECT_FILENAME)
else:
click.secho('Abort!', fg='red')
else:
self._create_ini_file(board, ini_path, PROJECT_FILENAME) | python | def create_ini(self, board, project_dir='', sayyes=False):
project_dir = util.check_dir(project_dir)
ini_path = util.safe_join(project_dir, PROJECT_FILENAME)
# Check board
boards = Resources().boards
if board not in boards.keys():
click.secho(
'Error: no such board \'{}\''.format(board),
fg='red')
sys.exit(1)
if isfile(ini_path):
# -- If sayyes, skip the question
if sayyes:
self._create_ini_file(board, ini_path, PROJECT_FILENAME)
else:
click.secho(
'Warning: {} file already exists'.format(PROJECT_FILENAME),
fg='yellow')
if click.confirm('Do you want to replace it?'):
self._create_ini_file(board, ini_path, PROJECT_FILENAME)
else:
click.secho('Abort!', fg='red')
else:
self._create_ini_file(board, ini_path, PROJECT_FILENAME) | [
"def",
"create_ini",
"(",
"self",
",",
"board",
",",
"project_dir",
"=",
"''",
",",
"sayyes",
"=",
"False",
")",
":",
"project_dir",
"=",
"util",
".",
"check_dir",
"(",
"project_dir",
")",
"ini_path",
"=",
"util",
".",
"safe_join",
"(",
"project_dir",
",... | Creates a new apio project file | [
"Creates",
"a",
"new",
"apio",
"project",
"file"
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/managers/project.py#L60-L88 |
231,387 | FPGAwars/apio | apio/managers/project.py | Project.read | def read(self):
"""Read the project config file"""
# -- If no project finel found, just return
if not isfile(PROJECT_FILENAME):
print('Info: No {} file'.format(PROJECT_FILENAME))
return
# -- Read stored board
board = self._read_board()
# -- Update board
self.board = board
if not board:
print('Error: invalid {} project file'.format(
PROJECT_FILENAME))
print('No \'board\' field defined in project file')
sys.exit(1) | python | def read(self):
# -- If no project finel found, just return
if not isfile(PROJECT_FILENAME):
print('Info: No {} file'.format(PROJECT_FILENAME))
return
# -- Read stored board
board = self._read_board()
# -- Update board
self.board = board
if not board:
print('Error: invalid {} project file'.format(
PROJECT_FILENAME))
print('No \'board\' field defined in project file')
sys.exit(1) | [
"def",
"read",
"(",
"self",
")",
":",
"# -- If no project finel found, just return",
"if",
"not",
"isfile",
"(",
"PROJECT_FILENAME",
")",
":",
"print",
"(",
"'Info: No {} file'",
".",
"format",
"(",
"PROJECT_FILENAME",
")",
")",
"return",
"# -- Read stored board",
"... | Read the project config file | [
"Read",
"the",
"project",
"config",
"file"
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/managers/project.py#L113-L130 |
231,388 | FPGAwars/apio | apio/commands/verify.py | cli | def cli(ctx, project_dir):
"""Verify the verilog code."""
exit_code = SCons(project_dir).verify()
ctx.exit(exit_code) | python | def cli(ctx, project_dir):
exit_code = SCons(project_dir).verify()
ctx.exit(exit_code) | [
"def",
"cli",
"(",
"ctx",
",",
"project_dir",
")",
":",
"exit_code",
"=",
"SCons",
"(",
"project_dir",
")",
".",
"verify",
"(",
")",
"ctx",
".",
"exit",
"(",
"exit_code",
")"
] | Verify the verilog code. | [
"Verify",
"the",
"verilog",
"code",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/verify.py#L21-L24 |
231,389 | FPGAwars/apio | apio/commands/drivers.py | cli | def cli(ctx, ftdi_enable, ftdi_disable, serial_enable, serial_disable):
"""Manage FPGA boards drivers."""
exit_code = 0
if ftdi_enable: # pragma: no cover
exit_code = Drivers().ftdi_enable()
elif ftdi_disable: # pragma: no cover
exit_code = Drivers().ftdi_disable()
elif serial_enable: # pragma: no cover
exit_code = Drivers().serial_enable()
elif serial_disable: # pragma: no cover
exit_code = Drivers().serial_disable()
else:
click.secho(ctx.get_help())
ctx.exit(exit_code) | python | def cli(ctx, ftdi_enable, ftdi_disable, serial_enable, serial_disable):
exit_code = 0
if ftdi_enable: # pragma: no cover
exit_code = Drivers().ftdi_enable()
elif ftdi_disable: # pragma: no cover
exit_code = Drivers().ftdi_disable()
elif serial_enable: # pragma: no cover
exit_code = Drivers().serial_enable()
elif serial_disable: # pragma: no cover
exit_code = Drivers().serial_disable()
else:
click.secho(ctx.get_help())
ctx.exit(exit_code) | [
"def",
"cli",
"(",
"ctx",
",",
"ftdi_enable",
",",
"ftdi_disable",
",",
"serial_enable",
",",
"serial_disable",
")",
":",
"exit_code",
"=",
"0",
"if",
"ftdi_enable",
":",
"# pragma: no cover",
"exit_code",
"=",
"Drivers",
"(",
")",
".",
"ftdi_enable",
"(",
"... | Manage FPGA boards drivers. | [
"Manage",
"FPGA",
"boards",
"drivers",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/drivers.py#L22-L38 |
231,390 | FPGAwars/apio | apio/commands/boards.py | cli | def cli(ctx, list, fpga):
"""Manage FPGA boards."""
if list:
Resources().list_boards()
elif fpga:
Resources().list_fpgas()
else:
click.secho(ctx.get_help()) | python | def cli(ctx, list, fpga):
if list:
Resources().list_boards()
elif fpga:
Resources().list_fpgas()
else:
click.secho(ctx.get_help()) | [
"def",
"cli",
"(",
"ctx",
",",
"list",
",",
"fpga",
")",
":",
"if",
"list",
":",
"Resources",
"(",
")",
".",
"list_boards",
"(",
")",
"elif",
"fpga",
":",
"Resources",
"(",
")",
".",
"list_fpgas",
"(",
")",
"else",
":",
"click",
".",
"secho",
"("... | Manage FPGA boards. | [
"Manage",
"FPGA",
"boards",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/boards.py#L18-L26 |
231,391 | FPGAwars/apio | apio/commands/upload.py | cli | def cli(ctx, board, serial_port, ftdi_id, sram, project_dir,
verbose, verbose_yosys, verbose_arachne):
"""Upload the bitstream to the FPGA."""
drivers = Drivers()
drivers.pre_upload()
# Run scons
exit_code = SCons(project_dir).upload({
'board': board,
'verbose': {
'all': verbose,
'yosys': verbose_yosys,
'arachne': verbose_arachne
}
}, serial_port, ftdi_id, sram)
drivers.post_upload()
ctx.exit(exit_code) | python | def cli(ctx, board, serial_port, ftdi_id, sram, project_dir,
verbose, verbose_yosys, verbose_arachne):
drivers = Drivers()
drivers.pre_upload()
# Run scons
exit_code = SCons(project_dir).upload({
'board': board,
'verbose': {
'all': verbose,
'yosys': verbose_yosys,
'arachne': verbose_arachne
}
}, serial_port, ftdi_id, sram)
drivers.post_upload()
ctx.exit(exit_code) | [
"def",
"cli",
"(",
"ctx",
",",
"board",
",",
"serial_port",
",",
"ftdi_id",
",",
"sram",
",",
"project_dir",
",",
"verbose",
",",
"verbose_yosys",
",",
"verbose_arachne",
")",
":",
"drivers",
"=",
"Drivers",
"(",
")",
"drivers",
".",
"pre_upload",
"(",
"... | Upload the bitstream to the FPGA. | [
"Upload",
"the",
"bitstream",
"to",
"the",
"FPGA",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/upload.py#L36-L52 |
231,392 | FPGAwars/apio | apio/commands/upgrade.py | cli | def cli(ctx):
"""Check the latest Apio version."""
current_version = get_distribution('apio').version
latest_version = get_pypi_latest_version()
if latest_version is None:
ctx.exit(1)
if latest_version == current_version:
click.secho('You\'re up-to-date!\nApio {} is currently the '
'newest version available.'.format(latest_version),
fg='green')
else:
click.secho('You\'re not updated\nPlease execute '
'`pip install -U apio` to upgrade.',
fg="yellow") | python | def cli(ctx):
current_version = get_distribution('apio').version
latest_version = get_pypi_latest_version()
if latest_version is None:
ctx.exit(1)
if latest_version == current_version:
click.secho('You\'re up-to-date!\nApio {} is currently the '
'newest version available.'.format(latest_version),
fg='green')
else:
click.secho('You\'re not updated\nPlease execute '
'`pip install -U apio` to upgrade.',
fg="yellow") | [
"def",
"cli",
"(",
"ctx",
")",
":",
"current_version",
"=",
"get_distribution",
"(",
"'apio'",
")",
".",
"version",
"latest_version",
"=",
"get_pypi_latest_version",
"(",
")",
"if",
"latest_version",
"is",
"None",
":",
"ctx",
".",
"exit",
"(",
"1",
")",
"i... | Check the latest Apio version. | [
"Check",
"the",
"latest",
"Apio",
"version",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/upgrade.py#L16-L32 |
231,393 | FPGAwars/apio | apio/util.py | unicoder | def unicoder(p):
""" Make sure a Unicode string is returned """
if isinstance(p, unicode):
return p
if isinstance(p, str):
return decoder(p)
else:
return unicode(decoder(p)) | python | def unicoder(p):
if isinstance(p, unicode):
return p
if isinstance(p, str):
return decoder(p)
else:
return unicode(decoder(p)) | [
"def",
"unicoder",
"(",
"p",
")",
":",
"if",
"isinstance",
"(",
"p",
",",
"unicode",
")",
":",
"return",
"p",
"if",
"isinstance",
"(",
"p",
",",
"str",
")",
":",
"return",
"decoder",
"(",
"p",
")",
"else",
":",
"return",
"unicode",
"(",
"decoder",
... | Make sure a Unicode string is returned | [
"Make",
"sure",
"a",
"Unicode",
"string",
"is",
"returned"
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/util.py#L95-L102 |
231,394 | FPGAwars/apio | apio/util.py | safe_join | def safe_join(*paths):
""" Join paths in a Unicode-safe way """
try:
return join(*paths)
except UnicodeDecodeError:
npaths = ()
for path in paths:
npaths += (unicoder(path),)
return join(*npaths) | python | def safe_join(*paths):
try:
return join(*paths)
except UnicodeDecodeError:
npaths = ()
for path in paths:
npaths += (unicoder(path),)
return join(*npaths) | [
"def",
"safe_join",
"(",
"*",
"paths",
")",
":",
"try",
":",
"return",
"join",
"(",
"*",
"paths",
")",
"except",
"UnicodeDecodeError",
":",
"npaths",
"=",
"(",
")",
"for",
"path",
"in",
"paths",
":",
"npaths",
"+=",
"(",
"unicoder",
"(",
"path",
")",... | Join paths in a Unicode-safe way | [
"Join",
"paths",
"in",
"a",
"Unicode",
"-",
"safe",
"way"
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/util.py#L114-L122 |
231,395 | FPGAwars/apio | apio/util.py | _check_apt_get | def _check_apt_get():
"""Check if apio can be installed through apt-get"""
check = False
if 'TESTING' not in os.environ:
result = exec_command(['dpkg', '-l', 'apio'])
if result and result.get('returncode') == 0:
match = re.findall('rc\s+apio', result.get('out')) + \
re.findall('ii\s+apio', result.get('out'))
check = len(match) > 0
return check | python | def _check_apt_get():
check = False
if 'TESTING' not in os.environ:
result = exec_command(['dpkg', '-l', 'apio'])
if result and result.get('returncode') == 0:
match = re.findall('rc\s+apio', result.get('out')) + \
re.findall('ii\s+apio', result.get('out'))
check = len(match) > 0
return check | [
"def",
"_check_apt_get",
"(",
")",
":",
"check",
"=",
"False",
"if",
"'TESTING'",
"not",
"in",
"os",
".",
"environ",
":",
"result",
"=",
"exec_command",
"(",
"[",
"'dpkg'",
",",
"'-l'",
",",
"'apio'",
"]",
")",
"if",
"result",
"and",
"result",
".",
"... | Check if apio can be installed through apt-get | [
"Check",
"if",
"apio",
"can",
"be",
"installed",
"through",
"apt",
"-",
"get"
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/util.py#L336-L345 |
231,396 | FPGAwars/apio | apio/commands/raw.py | cli | def cli(ctx, cmd):
"""Execute commands using Apio packages."""
exit_code = util.call(cmd)
ctx.exit(exit_code) | python | def cli(ctx, cmd):
exit_code = util.call(cmd)
ctx.exit(exit_code) | [
"def",
"cli",
"(",
"ctx",
",",
"cmd",
")",
":",
"exit_code",
"=",
"util",
".",
"call",
"(",
"cmd",
")",
"ctx",
".",
"exit",
"(",
"exit_code",
")"
] | Execute commands using Apio packages. | [
"Execute",
"commands",
"using",
"Apio",
"packages",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/raw.py#L15-L19 |
231,397 | FPGAwars/apio | apio/commands/config.py | cli | def cli(ctx, list, verbose, exe):
"""Apio configuration."""
if list: # pragma: no cover
profile = Profile()
profile.list()
elif verbose: # pragma: no cover
profile = Profile()
profile.add_config('verbose', verbose)
elif exe: # pragma: no cover
profile = Profile()
profile.add_config('exe', exe)
else:
click.secho(ctx.get_help()) | python | def cli(ctx, list, verbose, exe):
if list: # pragma: no cover
profile = Profile()
profile.list()
elif verbose: # pragma: no cover
profile = Profile()
profile.add_config('verbose', verbose)
elif exe: # pragma: no cover
profile = Profile()
profile.add_config('exe', exe)
else:
click.secho(ctx.get_help()) | [
"def",
"cli",
"(",
"ctx",
",",
"list",
",",
"verbose",
",",
"exe",
")",
":",
"if",
"list",
":",
"# pragma: no cover",
"profile",
"=",
"Profile",
"(",
")",
"profile",
".",
"list",
"(",
")",
"elif",
"verbose",
":",
"# pragma: no cover",
"profile",
"=",
"... | Apio configuration. | [
"Apio",
"configuration",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/config.py#L21-L34 |
231,398 | FPGAwars/apio | apio/commands/install.py | cli | def cli(ctx, packages, all, list, force, platform):
"""Install packages."""
if packages:
for package in packages:
Installer(package, platform, force).install()
elif all: # pragma: no cover
packages = Resources(platform).packages
for package in packages:
Installer(package, platform, force).install()
elif list:
Resources(platform).list_packages(installed=True, notinstalled=True)
else:
click.secho(ctx.get_help()) | python | def cli(ctx, packages, all, list, force, platform):
if packages:
for package in packages:
Installer(package, platform, force).install()
elif all: # pragma: no cover
packages = Resources(platform).packages
for package in packages:
Installer(package, platform, force).install()
elif list:
Resources(platform).list_packages(installed=True, notinstalled=True)
else:
click.secho(ctx.get_help()) | [
"def",
"cli",
"(",
"ctx",
",",
"packages",
",",
"all",
",",
"list",
",",
"force",
",",
"platform",
")",
":",
"if",
"packages",
":",
"for",
"package",
"in",
"packages",
":",
"Installer",
"(",
"package",
",",
"platform",
",",
"force",
")",
".",
"instal... | Install packages. | [
"Install",
"packages",
"."
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/install.py#L35-L48 |
231,399 | FPGAwars/apio | apio/commands/examples.py | cli | def cli(ctx, list, dir, files, project_dir, sayno):
"""Manage verilog examples.\n
Install with `apio install examples`"""
exit_code = 0
if list:
exit_code = Examples().list_examples()
elif dir:
exit_code = Examples().copy_example_dir(dir, project_dir, sayno)
elif files:
exit_code = Examples().copy_example_files(files, project_dir, sayno)
else:
click.secho(ctx.get_help())
click.secho(Examples().examples_of_use_cad())
ctx.exit(exit_code) | python | def cli(ctx, list, dir, files, project_dir, sayno):
exit_code = 0
if list:
exit_code = Examples().list_examples()
elif dir:
exit_code = Examples().copy_example_dir(dir, project_dir, sayno)
elif files:
exit_code = Examples().copy_example_files(files, project_dir, sayno)
else:
click.secho(ctx.get_help())
click.secho(Examples().examples_of_use_cad())
ctx.exit(exit_code) | [
"def",
"cli",
"(",
"ctx",
",",
"list",
",",
"dir",
",",
"files",
",",
"project_dir",
",",
"sayno",
")",
":",
"exit_code",
"=",
"0",
"if",
"list",
":",
"exit_code",
"=",
"Examples",
"(",
")",
".",
"list_examples",
"(",
")",
"elif",
"dir",
":",
"exit... | Manage verilog examples.\n
Install with `apio install examples` | [
"Manage",
"verilog",
"examples",
".",
"\\",
"n",
"Install",
"with",
"apio",
"install",
"examples"
] | 5c6310f11a061a760764c6b5847bfb431dc3d0bc | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/examples.py#L29-L45 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.