repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 β | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
michaelliao/sinaweibopy | weibo.py | APIClient._parse_access_token | python | def _parse_access_token(self, r):
'''
new:return access token as a JsonDict: {"access_token":"your-access-token","expires_in":12345678,"uid":1234}, expires_in is represented using standard unix-epoch-time
'''
current = int(time.time())
expires = r.expires_in + current
rem... | new:return access token as a JsonDict: {"access_token":"your-access-token","expires_in":12345678,"uid":1234}, expires_in is represented using standard unix-epoch-time | train | https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/weibo.py#L272-L283 | null | class APIClient(object):
'''
API client using synchronized invocation.
'''
def __init__(self, app_key, app_secret, redirect_uri=None, response_type='code', domain='api.weibo.com', version='2'):
self.client_id = str(app_key)
self.client_secret = str(app_secret)
self.redirect_uri =... |
c0fec0de/anytree | anytree/node/nodemixin.py | NodeMixin.siblings | python | def siblings(self):
parent = self.parent
if parent is None:
return tuple()
else:
return tuple([node for node in parent.children if node != self]) | Tuple of nodes with the same parent.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> lazy = Node("Lazy", parent=marc)
>>> udo.siblings
()
... | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/node/nodemixin.py#L384-L407 | null | class NodeMixin(object):
__slots__ = ("__parent", "__children")
separator = "/"
u"""
The :any:`NodeMixin` class extends any Python class to a tree node.
The only tree relevant information is the `parent` attribute.
If `None` the :any:`NodeMixin` is root node.
If set to another node, the ... |
c0fec0de/anytree | anytree/node/nodemixin.py | NodeMixin.height | python | def height(self):
if self.__children_:
return max([child.height for child in self.__children_]) + 1
else:
return 0 | Number of edges on the longest path to a leaf `Node`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.height
2
>>> marc.height
1
>>> lian.height
0 | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/node/nodemixin.py#L464-L482 | null | class NodeMixin(object):
__slots__ = ("__parent", "__children")
separator = "/"
u"""
The :any:`NodeMixin` class extends any Python class to a tree node.
The only tree relevant information is the `parent` attribute.
If `None` the :any:`NodeMixin` is root node.
If set to another node, the ... |
c0fec0de/anytree | anytree/importer/jsonimporter.py | JsonImporter.import_ | python | def import_(self, data):
return self.__import(json.loads(data, **self.kwargs)) | Read JSON from `data`. | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/importer/jsonimporter.py#L60-L62 | [
"def __import(self, data):\n dictimporter = self.dictimporter or DictImporter()\n return dictimporter.import_(data)\n"
] | class JsonImporter(object):
def __init__(self, dictimporter=None, **kwargs):
u"""
Import Tree from JSON.
The JSON is read and converted to a dictionary via `dictimporter`.
Keyword Arguments:
dictimporter: Dictionary Importer used (see :any:`DictImporter`).
... |
c0fec0de/anytree | anytree/importer/jsonimporter.py | JsonImporter.read | python | def read(self, filehandle):
return self.__import(json.load(filehandle, **self.kwargs)) | Read JSON from `filehandle`. | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/importer/jsonimporter.py#L64-L66 | [
"def __import(self, data):\n dictimporter = self.dictimporter or DictImporter()\n return dictimporter.import_(data)\n"
] | class JsonImporter(object):
def __init__(self, dictimporter=None, **kwargs):
u"""
Import Tree from JSON.
The JSON is read and converted to a dictionary via `dictimporter`.
Keyword Arguments:
dictimporter: Dictionary Importer used (see :any:`DictImporter`).
... |
c0fec0de/anytree | anytree/walker.py | Walker.walk | python | def walk(self, start, end):
s = start.path
e = end.path
if start.root != end.root:
msg = "%r and %r are not part of the same tree." % (start, end)
raise WalkError(msg)
# common
c = Walker.__calc_common(s, e)
assert c[0] is start.root
len_c ... | Walk from `start` node to `end` node.
Returns:
(upwards, common, downwards): `upwards` is a list of nodes to go upward to.
`common` top node. `downwards` is a list of nodes to go downward to.
Raises:
WalkError: on no common root node.
>>> from anytree impor... | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/walker.py#L10-L85 | [
"def __calc_common(s, e):\n return tuple([si for si, ei in zip(s, e) if si is ei])\n"
] | class Walker(object):
def __init__(self):
"""Walk from one node to another."""
super(Walker, self).__init__()
@staticmethod
def __calc_common(s, e):
return tuple([si for si, ei in zip(s, e) if si is ei])
|
c0fec0de/anytree | anytree/exporter/jsonexporter.py | JsonExporter.export | python | def export(self, node):
dictexporter = self.dictexporter or DictExporter()
data = dictexporter.export(node)
return json.dumps(data, **self.kwargs) | Return JSON for tree starting at `node`. | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/exporter/jsonexporter.py#L54-L58 | null | class JsonExporter(object):
def __init__(self, dictexporter=None, **kwargs):
"""
Tree to JSON exporter.
The tree is converted to a dictionary via `dictexporter` and exported to JSON.
Keyword Arguments:
dictexporter: Dictionary Exporter used (see :any:`DictExporter`).
... |
c0fec0de/anytree | anytree/exporter/jsonexporter.py | JsonExporter.write | python | def write(self, node, filehandle):
dictexporter = self.dictexporter or DictExporter()
data = dictexporter.export(node)
return json.dump(data, filehandle, **self.kwargs) | Write JSON to `filehandle` starting at `node`. | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/exporter/jsonexporter.py#L60-L64 | null | class JsonExporter(object):
def __init__(self, dictexporter=None, **kwargs):
"""
Tree to JSON exporter.
The tree is converted to a dictionary via `dictexporter` and exported to JSON.
Keyword Arguments:
dictexporter: Dictionary Exporter used (see :any:`DictExporter`).
... |
c0fec0de/anytree | anytree/search.py | findall | python | def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None):
return _findall(node, filter_=filter_, stop=stop,
maxlevel=maxlevel, mincount=mincount, maxcount=maxcount) | Search nodes matching `filter_` but stop at `maxlevel` or `stop`.
Return tuple with matching nodes.
Args:
node: top node, start searching.
Keyword Args:
filter_: function called with every `node` as argument, `node` is returned if `True`.
stop: stop iteration at `node` if `stop` f... | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/search.py#L6-L62 | [
"def _findall(node, filter_, stop=None, maxlevel=None, mincount=None, maxcount=None):\n result = tuple(PreOrderIter(node, filter_, stop, maxlevel))\n resultlen = len(result)\n if mincount is not None and resultlen < mincount:\n msg = \"Expecting at least %d elements, but found %d.\"\n raise C... | """Node Searching."""
from anytree.iterators import PreOrderIter
def findall_by_attr(node, value, name="name", maxlevel=None, mincount=None, maxcount=None):
"""
Search nodes with attribute `name` having `value` but stop at `maxlevel`.
Return tuple with matching nodes.
Args:
node: top node,... |
c0fec0de/anytree | anytree/search.py | findall_by_attr | python | def findall_by_attr(node, value, name="name", maxlevel=None, mincount=None, maxcount=None):
return _findall(node, filter_=lambda n: _filter_by_name(n, name, value),
maxlevel=maxlevel, mincount=mincount, maxcount=maxcount) | Search nodes with attribute `name` having `value` but stop at `maxlevel`.
Return tuple with matching nodes.
Args:
node: top node, start searching.
value: value which need to match
Keyword Args:
name (str): attribute name need to match
maxlevel (int): maximum decending in t... | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/search.py#L65-L108 | [
"def _findall(node, filter_, stop=None, maxlevel=None, mincount=None, maxcount=None):\n result = tuple(PreOrderIter(node, filter_, stop, maxlevel))\n resultlen = len(result)\n if mincount is not None and resultlen < mincount:\n msg = \"Expecting at least %d elements, but found %d.\"\n raise C... | """Node Searching."""
from anytree.iterators import PreOrderIter
def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None):
"""
Search nodes matching `filter_` but stop at `maxlevel` or `stop`.
Return tuple with matching nodes.
Args:
node: top node, start searc... |
c0fec0de/anytree | anytree/search.py | find | python | def find(node, filter_=None, stop=None, maxlevel=None):
return _find(node, filter_=filter_, stop=stop, maxlevel=maxlevel) | Search for *single* node matching `filter_` but stop at `maxlevel` or `stop`.
Return matching node.
Args:
node: top node, start searching.
Keyword Args:
filter_: function called with every `node` as argument, `node` is returned if `True`.
stop: stop iteration at `node` if `stop` f... | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/search.py#L111-L156 | [
"def _find(node, filter_, stop=None, maxlevel=None):\n items = _findall(node, filter_, stop=stop, maxlevel=maxlevel, maxcount=1)\n return items[0] if items else None\n"
] | """Node Searching."""
from anytree.iterators import PreOrderIter
def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None):
"""
Search nodes matching `filter_` but stop at `maxlevel` or `stop`.
Return tuple with matching nodes.
Args:
node: top node, start searc... |
c0fec0de/anytree | anytree/search.py | find_by_attr | python | def find_by_attr(node, value, name="name", maxlevel=None):
return _find(node, filter_=lambda n: _filter_by_name(n, name, value),
maxlevel=maxlevel) | Search for *single* node with attribute `name` having `value` but stop at `maxlevel`.
Return tuple with matching nodes.
Args:
node: top node, start searching.
value: value which need to match
Keyword Args:
name (str): attribute name need to match
maxlevel (int): maximum d... | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/search.py#L159-L204 | [
"def _find(node, filter_, stop=None, maxlevel=None):\n items = _findall(node, filter_, stop=stop, maxlevel=maxlevel, maxcount=1)\n return items[0] if items else None\n"
] | """Node Searching."""
from anytree.iterators import PreOrderIter
def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None):
"""
Search nodes matching `filter_` but stop at `maxlevel` or `stop`.
Return tuple with matching nodes.
Args:
node: top node, start searc... |
c0fec0de/anytree | anytree/resolver.py | Resolver.get | python | def get(self, node, path):
node, parts = self.__start(node, path)
for part in parts:
if part == "..":
node = node.parent
elif part in ("", "."):
pass
else:
node = self.__get(node, part)
return node | Return instance at `path`.
An example module tree:
>>> from anytree import Node
>>> top = Node("top", parent=None)
>>> sub0 = Node("sub0", parent=top)
>>> sub0sub0 = Node("sub0sub0", parent=sub0)
>>> sub0sub1 = Node("sub0sub1", parent=sub0)
>>> sub1 = Node("sub1... | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/resolver.py#L20-L77 | [
"def __get(self, node, name):\n for child in node.children:\n if _getattr(child, self.pathattr) == name:\n return child\n raise ChildResolverError(node, name, self.pathattr)\n",
"def __start(self, node, path):\n sep = node.separator\n parts = path.split(sep)\n if path.startswith(s... | class Resolver(object):
_match_cache = {}
def __init__(self, pathattr='name'):
"""Resolve :any:`NodeMixin` paths using attribute `pathattr`."""
super(Resolver, self).__init__()
self.pathattr = pathattr
def __get(self, node, name):
for child in node.children:
i... |
c0fec0de/anytree | anytree/resolver.py | Resolver.glob | python | def glob(self, node, path):
node, parts = self.__start(node, path)
return self.__glob(node, parts) | Return instances at `path` supporting wildcards.
Behaves identical to :any:`get`, but accepts wildcards and returns
a list of found nodes.
* `*` matches any characters, except '/'.
* `?` matches a single character, except '/'.
An example module tree:
>>> from anytree ... | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/resolver.py#L85-L147 | [
"def __start(self, node, path):\n sep = node.separator\n parts = path.split(sep)\n if path.startswith(sep):\n node = node.root\n rootpart = _getattr(node, self.pathattr)\n parts.pop(0)\n if not parts[0]:\n msg = \"root node missing. root is '%s%s'.\"\n rais... | class Resolver(object):
_match_cache = {}
def __init__(self, pathattr='name'):
"""Resolve :any:`NodeMixin` paths using attribute `pathattr`."""
super(Resolver, self).__init__()
self.pathattr = pathattr
def get(self, node, path):
"""
Return instance at `path`.
... |
c0fec0de/anytree | anytree/exporter/dotexporter.py | DotExporter.to_dotfile | python | def to_dotfile(self, filename):
with codecs.open(filename, "w", "utf-8") as file:
for line in self:
file.write("%s\n" % line) | Write graph to `filename`.
>>> from anytree import Node
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)
>>> s1a = Node("sub1A", parent=s1)
... | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/exporter/dotexporter.py#L190-L215 | null | class DotExporter(object):
def __init__(self, node, graph="digraph", name="tree", options=None,
indent=4, nodenamefunc=None, nodeattrfunc=None,
edgeattrfunc=None, edgetypefunc=None):
"""
Dot Language Exporter.
Args:
node (Node): start node.
... |
c0fec0de/anytree | anytree/exporter/dotexporter.py | DotExporter.to_picture | python | def to_picture(self, filename):
fileformat = path.splitext(filename)[1][1:]
with NamedTemporaryFile("wb", delete=False) as dotfile:
dotfilename = dotfile.name
for line in self:
dotfile.write(("%s\n" % line).encode("utf-8"))
dotfile.flush()
... | Write graph to a temporary file and invoke `dot`.
The output file type is automatically detected from the file suffix.
*`graphviz` needs to be installed, before usage of this method.* | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/exporter/dotexporter.py#L217-L237 | null | class DotExporter(object):
def __init__(self, node, graph="digraph", name="tree", options=None,
indent=4, nodenamefunc=None, nodeattrfunc=None,
edgeattrfunc=None, edgetypefunc=None):
"""
Dot Language Exporter.
Args:
node (Node): start node.
... |
c0fec0de/anytree | anytree/util/__init__.py | commonancestors | python | def commonancestors(*nodes):
ancestors = [node.ancestors for node in nodes]
common = []
for parentnodes in zip(*ancestors):
parentnode = parentnodes[0]
if all([parentnode is p for p in parentnodes[1:]]):
common.append(parentnode)
else:
break
return tuple(c... | Determine common ancestors of `nodes`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> dan = Node("Dan", parent=udo)
>>> jet = Node("Jet", parent=dan)
>>> jan = Node("Jan", parent=dan)
>>> joe = Node("Joe", ... | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/util/__init__.py#L4-L34 | null | """Utilities."""
def leftsibling(node):
"""
Return Left Sibling of `node`.
>>> from anytree import Node
>>> dan = Node("Dan")
>>> jet = Node("Jet", parent=dan)
>>> jan = Node("Jan", parent=dan)
>>> joe = Node("Joe", parent=dan)
>>> leftsibling(dan)
>>> leftsibling(jet)
>>> le... |
c0fec0de/anytree | anytree/util/__init__.py | leftsibling | python | def leftsibling(node):
if node.parent:
pchildren = node.parent.children
idx = pchildren.index(node)
if idx:
return pchildren[idx - 1]
else:
return None
else:
return None | Return Left Sibling of `node`.
>>> from anytree import Node
>>> dan = Node("Dan")
>>> jet = Node("Jet", parent=dan)
>>> jan = Node("Jan", parent=dan)
>>> joe = Node("Joe", parent=dan)
>>> leftsibling(dan)
>>> leftsibling(jet)
>>> leftsibling(jan)
Node('/Dan/Jet')
>>> leftsibling... | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/util/__init__.py#L37-L61 | null | """Utilities."""
def commonancestors(*nodes):
"""
Determine common ancestors of `nodes`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> dan = Node("Dan", parent=udo)
>>> jet = Node("Jet", parent=dan)
... |
c0fec0de/anytree | anytree/util/__init__.py | rightsibling | python | def rightsibling(node):
if node.parent:
pchildren = node.parent.children
idx = pchildren.index(node)
try:
return pchildren[idx + 1]
except IndexError:
return None
else:
return None | Return Right Sibling of `node`.
>>> from anytree import Node
>>> dan = Node("Dan")
>>> jet = Node("Jet", parent=dan)
>>> jan = Node("Jan", parent=dan)
>>> joe = Node("Joe", parent=dan)
>>> rightsibling(dan)
>>> rightsibling(jet)
Node('/Dan/Jan')
>>> rightsibling(jan)
Node('/Dan/... | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/util/__init__.py#L64-L88 | null | """Utilities."""
def commonancestors(*nodes):
"""
Determine common ancestors of `nodes`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> dan = Node("Dan", parent=udo)
>>> jet = Node("Jet", parent=dan)
... |
c0fec0de/anytree | anytree/exporter/dictexporter.py | DictExporter.export | python | def export(self, node):
attriter = self.attriter or (lambda attr_values: attr_values)
return self.__export(node, self.dictcls, attriter, self.childiter) | Export tree starting at `node`. | train | https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/exporter/dictexporter.py#L70-L73 | [
"def __export(self, node, dictcls, attriter, childiter):\n attr_values = attriter(self._iter_attr_values(node))\n data = dictcls(attr_values)\n children = [self.__export(child, dictcls, attriter, childiter)\n for child in childiter(node.children)]\n if children:\n data['children'] ... | class DictExporter(object):
def __init__(self, dictcls=dict, attriter=None, childiter=list):
"""
Tree to dictionary exporter.
Every node is converted to a dictionary with all instance
attributes as key-value pairs.
Child nodes are exported to the children attribute.
... |
gouthambs/Flask-Blogging | flask_blogging/engine.py | BloggingEngine.init_app | python | def init_app(self, app, storage=None, cache=None, file_upload=None):
self.app = app
self.config = self.app.config
self.storage = storage or self.storage
self.file_upload = file_upload or self.file_upload
self.cache = cache or self.cache
self._register_plugins(self.app, s... | Initialize the engine.
:param app: The app to use
:type app: Object
:param storage: The blog storage instance that implements the
:type storage: Object
:param cache: (Optional) A Flask-Cache object to enable caching
:type cache: Object
``Storage`` class interfac... | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/engine.py#L78-L111 | [
"def create_blueprint(import_name, blogging_engine):\n\n blog_app = Blueprint(\"blogging\", import_name, template_folder='templates')\n\n # register index\n index_func = cached_func(blogging_engine, index)\n blog_app.add_url_rule(\"/\", defaults={\"count\": None, \"page\": 1},\n ... | class BloggingEngine(object):
"""
The BloggingEngine is the class for initializing the blog support for your
web app. Here is an example usage:
.. code:: python
from flask import Flask
from flask_blogging import BloggingEngine, SQLAStorage
from sqlalchemy import create_engine
... |
gouthambs/Flask-Blogging | flask_blogging/engine.py | BloggingEngine.process_post | python | def process_post(self, post, render=True):
post_processor = self.post_processor
post_processor.process(post, render)
try:
author = self.user_callback(post["user_id"])
except Exception:
raise Exception("No user_loader has been installed for this "
... | A high level view to create post processing.
:param post: Dictionary representing the post
:type post: dict
:param render: Choice if the markdown text has to be converted or not
:type render: bool
:return: | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/engine.py#L144-L163 | [
"def get_user_name(cls, user):\n user_name = user.get_name() if hasattr(user, \"get_name\") else str(user)\n return user_name\n"
] | class BloggingEngine(object):
"""
The BloggingEngine is the class for initializing the blog support for your
web app. Here is an example usage:
.. code:: python
from flask import Flask
from flask_blogging import BloggingEngine, SQLAStorage
from sqlalchemy import create_engine
... |
gouthambs/Flask-Blogging | flask_blogging/processor.py | PostProcessor.process | python | def process(cls, post, render=True):
post["slug"] = cls.create_slug(post["title"])
post["editable"] = cls.is_author(post, current_user)
post["url"] = cls.construct_url(post)
post["priority"] = 0.8
if render:
cls.render_text(post)
post["meta"]["images"] = c... | This method takes the post data and renders it
:param post:
:param render:
:return: | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/processor.py#L67-L80 | null | class PostProcessor(object):
_markdown_extensions = [MathJaxExtension(), MetaExtension()]
@staticmethod
def create_slug(title):
return slugify(title)
@staticmethod
def extract_images(post):
regex = re.compile(r'<\s*img [^>]*src="([^"]+)')
return regex.findall(post["rendere... |
gouthambs/Flask-Blogging | flask_blogging/storage.py | Storage.save_post | python | def save_post(self, title, text, user_id, tags, draft=False,
post_date=None, last_modified_date=None, meta_data=None,
post_id=None):
raise NotImplementedError("This method needs to be implemented by "
"the inheriting class") | Persist the blog post data. If ``post_id`` is ``None`` or ``post_id``
is invalid, the post must be inserted into the storage. If ``post_id``
is a valid id, then the data must be updated.
:param title: The title of the blog post
:type title: str
:param text: The text of the blog ... | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/storage.py#L9-L43 | null | class Storage(object):
def get_post_by_id(self, post_id):
"""
Fetch the blog post given by ``post_id``
:param post_id: The post identifier for the blog post
:type post_id: int
:return: If the ``post_id`` is valid, the post data is retrieved,
else returns ``None``.
... |
gouthambs/Flask-Blogging | flask_blogging/storage.py | Storage.get_posts | python | def get_posts(self, count=10, offset=0, recent=True, tag=None,
user_id=None, include_draft=False):
raise NotImplementedError("This method needs to be implemented by the "
"inheriting class") | Get posts given by filter criteria
:param count: The number of posts to retrieve (default 10). If count
is ``None``, all posts are returned.
:type count: int
:param offset: The number of posts to offset (default 0)
:type offset: int
:param recent: Order by recent posts ... | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/storage.py#L57-L82 | null | class Storage(object):
def save_post(self, title, text, user_id, tags, draft=False,
post_date=None, last_modified_date=None, meta_data=None,
post_id=None):
"""
Persist the blog post data. If ``post_id`` is ``None`` or ``post_id``
is invalid, the post must... |
gouthambs/Flask-Blogging | flask_blogging/gcdatastore.py | GoogleCloudDatastore.get_posts | python | def get_posts(self, count=10, offset=0, recent=True, tag=None,
user_id=None, include_draft=False):
query = self._client.query(kind='Post')
if tag:
norm_tag = self.normalize_tag(tag)
posts_ids = self._filter_posts_by_tag(norm_tag)
if posts_ids:
... | TODO: implement cursors support, if it will be needed.
But for the regular blog, it is overhead and
cost savings are minimal. | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/gcdatastore.py#L111-L153 | [
"def _filter_posts_by_tag(self, tag):\n if not tag:\n return []\n else:\n query = self._client.query(kind='Post')\n query.projection = ['post_id', 'tags']\n proj_result = list(query.fetch())\n\n proj_result = [dict(entity) for entity in proj_result]\n ids = set()\n\n ... | class GoogleCloudDatastore(Storage):
def __init__(self, namespace=None):
self._logger = logging.getLogger("flask-blogging")
self._client = datastore.Client(namespace=namespace)
def _get_new_post_id(self):
key = self._client.key('PostIDCounter', 'Counter')
query = self._client.g... |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | SQLAStorage.save_post | python | def save_post(self, title, text, user_id, tags, draft=False,
post_date=None, last_modified_date=None, meta_data=None,
post_id=None):
new_post = post_id is None
post_id = _as_int(post_id)
current_datetime = datetime.datetime.utcnow()
draft = 1 if draft ... | Persist the blog post data. If ``post_id`` is ``None`` or ``post_id``
is invalid, the post must be inserted into the storage. If ``post_id``
is a valid id, then the data must be updated.
:param title: The title of the blog post
:type title: str
:param text: The text of the blog ... | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L130-L197 | [
"def _as_int(s):\n try:\n n = int(s) if s is not None else None\n return n\n except ValueError:\n return None\n",
"def _save_tags(self, tags, post_id, conn):\n\n tags = self.normalize_tags(tags)\n tag_ids = []\n\n for tag in tags: # iterate over given tags\n try:\n ... | class SQLAStorage(Storage):
"""
The ``SQLAStorage`` implements the interface specified by the ``Storage``
class. This class uses SQLAlchemy to implement storage and retrieval of
data from any of the databases supported by SQLAlchemy.
"""
_db = None
_logger = logging.getLogger("flask-bloggin... |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | SQLAStorage._serialise_posts_and_tags_from_joined_rows | python | def _serialise_posts_and_tags_from_joined_rows(cls, joined_rows):
posts_by_id = OrderedDict()
tags_by_post_id = defaultdict(list)
for joined_row in joined_rows:
post_id = joined_row.post_id
post = cls._serialise_post_from_joined_row(joined_row)
posts_by_id[pos... | Translates multiple rows of joined post and tag information
into the dictionary format expected by flask-blogging.
There will be one row per post/tag pairing. | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L200-L219 | [
"def _serialise_post_from_joined_row(joined_row):\n return dict(\n post_id=joined_row.post_id,\n title=joined_row.post_title,\n text=joined_row.post_text,\n post_date=joined_row.post_post_date,\n last_modified_date=joined_row.post_last_modified_date,\n draft=joined_row.p... | class SQLAStorage(Storage):
"""
The ``SQLAStorage`` implements the interface specified by the ``Storage``
class. This class uses SQLAlchemy to implement storage and retrieval of
data from any of the databases supported by SQLAlchemy.
"""
_db = None
_logger = logging.getLogger("flask-bloggin... |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | SQLAStorage.get_post_by_id | python | def get_post_by_id(self, post_id):
r = None
post_id = _as_int(post_id)
with self._engine.begin() as conn:
try:
post_statement = sqla.select([self._post_table]) \
.where(self._post_table.c.id == post_id) \
.alias('post')
... | Fetch the blog post given by ``post_id``
:param post_id: The post identifier for the blog post
:type post_id: str
:return: If the ``post_id`` is valid, the post data is retrieved, else
returns ``None``. | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L233-L266 | [
"def _as_int(s):\n try:\n n = int(s) if s is not None else None\n return n\n except ValueError:\n return None\n",
"def _serialise_posts_and_tags_from_joined_rows(cls, joined_rows):\n \"\"\"\n Translates multiple rows of joined post and tag information\n into the dictionary form... | class SQLAStorage(Storage):
"""
The ``SQLAStorage`` implements the interface specified by the ``Storage``
class. This class uses SQLAlchemy to implement storage and retrieval of
data from any of the databases supported by SQLAlchemy.
"""
_db = None
_logger = logging.getLogger("flask-bloggin... |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | SQLAStorage.get_posts | python | def get_posts(self, count=10, offset=0, recent=True, tag=None,
user_id=None, include_draft=False):
user_id = str(user_id) if user_id else user_id
with self._engine.begin() as conn:
try:
# post_statement ensures the correct posts are selected
... | Get posts given by filter criteria
:param count: The number of posts to retrieve (default 10)
:type count: int
:param offset: The number of posts to offset (default 0)
:type offset: int
:param recent: Order by recent posts or not
:type recent: bool
:param tag: Fi... | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L268-L334 | [
"def _serialise_posts_and_tags_from_joined_rows(cls, joined_rows):\n \"\"\"\n Translates multiple rows of joined post and tag information\n into the dictionary format expected by flask-blogging.\n There will be one row per post/tag pairing.\n \"\"\"\n posts_by_id = OrderedDict()\n tags_by_post_... | class SQLAStorage(Storage):
"""
The ``SQLAStorage`` implements the interface specified by the ``Storage``
class. This class uses SQLAlchemy to implement storage and retrieval of
data from any of the databases supported by SQLAlchemy.
"""
_db = None
_logger = logging.getLogger("flask-bloggin... |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | SQLAStorage.count_posts | python | def count_posts(self, tag=None, user_id=None, include_draft=False):
result = 0
with self._engine.begin() as conn:
try:
count_statement = sqla.select([sqla.func.count()]). \
select_from(self._post_table)
sql_filter = self._get_filter(tag, us... | Returns the total number of posts for the give filter
:param tag: Filter by a specific tag
:type tag: str
:param user_id: Filter by a specific user
:type user_id: str
:param include_draft: Whether to include posts marked as draft or not
:type include_draft: bool
... | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L336-L360 | [
"def _get_filter(self, tag, user_id, include_draft, conn):\n filters = []\n if tag:\n tag = tag.upper()\n tag_statement = sqla.select([self._tag_table.c.id]).where(\n self._tag_table.c.text == tag)\n tag_result = conn.execute(tag_statement).fetchone()\n if tag_result is ... | class SQLAStorage(Storage):
"""
The ``SQLAStorage`` implements the interface specified by the ``Storage``
class. This class uses SQLAlchemy to implement storage and retrieval of
data from any of the databases supported by SQLAlchemy.
"""
_db = None
_logger = logging.getLogger("flask-bloggin... |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | SQLAStorage.delete_post | python | def delete_post(self, post_id):
status = False
success = 0
post_id = _as_int(post_id)
with self._engine.begin() as conn:
try:
post_del_statement = self._post_table.delete().where(
self._post_table.c.id == post_id)
conn.execu... | Delete the post defined by ``post_id``
:param post_id: The identifier corresponding to a post
:type post_id: int
:return: Returns True if the post was successfully deleted and False
otherwise. | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L362-L397 | [
"def _as_int(s):\n try:\n n = int(s) if s is not None else None\n return n\n except ValueError:\n return None\n"
] | class SQLAStorage(Storage):
"""
The ``SQLAStorage`` implements the interface specified by the ``Storage``
class. This class uses SQLAlchemy to implement storage and retrieval of
data from any of the databases supported by SQLAlchemy.
"""
_db = None
_logger = logging.getLogger("flask-bloggin... |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | SQLAStorage._create_all_tables | python | def _create_all_tables(self):
self._create_post_table()
self._create_tag_table()
self._create_tag_posts_table()
self._create_user_posts_table() | Creates all the required tables by calling the required functions.
:return: | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L516-L524 | [
"def _create_post_table(self):\n \"\"\"\n Creates the table to store the blog posts.\n :return:\n \"\"\"\n with self._engine.begin() as conn:\n post_table_name = self._table_name(\"post\")\n if not conn.dialect.has_table(conn, post_table_name):\n\n self._post_table = sqla.Tab... | class SQLAStorage(Storage):
"""
The ``SQLAStorage`` implements the interface specified by the ``Storage``
class. This class uses SQLAlchemy to implement storage and retrieval of
data from any of the databases supported by SQLAlchemy.
"""
_db = None
_logger = logging.getLogger("flask-bloggin... |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | SQLAStorage._create_post_table | python | def _create_post_table(self):
with self._engine.begin() as conn:
post_table_name = self._table_name("post")
if not conn.dialect.has_table(conn, post_table_name):
self._post_table = sqla.Table(
post_table_name, self._metadata,
sqla.... | Creates the table to store the blog posts.
:return: | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L526-L552 | null | class SQLAStorage(Storage):
"""
The ``SQLAStorage`` implements the interface specified by the ``Storage``
class. This class uses SQLAlchemy to implement storage and retrieval of
data from any of the databases supported by SQLAlchemy.
"""
_db = None
_logger = logging.getLogger("flask-bloggin... |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | SQLAStorage._create_tag_table | python | def _create_tag_table(self):
with self._engine.begin() as conn:
tag_table_name = self._table_name("tag")
if not conn.dialect.has_table(conn, tag_table_name):
self._tag_table = sqla.Table(
tag_table_name, self._metadata,
sqla.Column(... | Creates the table to store blog post tags.
:return: | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L554-L574 | null | class SQLAStorage(Storage):
"""
The ``SQLAStorage`` implements the interface specified by the ``Storage``
class. This class uses SQLAlchemy to implement storage and retrieval of
data from any of the databases supported by SQLAlchemy.
"""
_db = None
_logger = logging.getLogger("flask-bloggin... |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | SQLAStorage._create_tag_posts_table | python | def _create_tag_posts_table(self):
with self._engine.begin() as conn:
tag_posts_table_name = self._table_name("tag_posts")
if not conn.dialect.has_table(conn, tag_posts_table_name):
tag_id_key = self._table_name("tag") + ".id"
post_id_key = self._table_nam... | Creates the table to store association info between blog posts and
tags.
:return: | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L576-L607 | null | class SQLAStorage(Storage):
"""
The ``SQLAStorage`` implements the interface specified by the ``Storage``
class. This class uses SQLAlchemy to implement storage and retrieval of
data from any of the databases supported by SQLAlchemy.
"""
_db = None
_logger = logging.getLogger("flask-bloggin... |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | SQLAStorage._create_user_posts_table | python | def _create_user_posts_table(self):
with self._engine.begin() as conn:
user_posts_table_name = self._table_name("user_posts")
if not conn.dialect.has_table(conn, user_posts_table_name):
post_id_key = self._table_name("post") + ".id"
self._user_posts_table ... | Creates the table to store association info between user and blog
posts.
:return: | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L609-L636 | null | class SQLAStorage(Storage):
"""
The ``SQLAStorage`` implements the interface specified by the ``Storage``
class. This class uses SQLAlchemy to implement storage and retrieval of
data from any of the databases supported by SQLAlchemy.
"""
_db = None
_logger = logging.getLogger("flask-bloggin... |
gouthambs/Flask-Blogging | flask_blogging/utils.py | ensureUtf | python | def ensureUtf(s, encoding='utf8'):
# In Python2, str == bytes.
# In Python3, bytes remains unchanged, but str means unicode
# while unicode is not defined anymore
if type(s) == bytes:
return s.decode(encoding, 'ignore')
else:
return s | Converts input to unicode if necessary.
If `s` is bytes, it will be decoded using the `encoding` parameters.
This function is used for preprocessing /source/ and /filename/ arguments
to the builtin function `compile`. | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/utils.py#L1-L13 | null | |
gouthambs/Flask-Blogging | flask_blogging/views.py | index | python | def index(count, page):
blogging_engine = _get_blogging_engine(current_app)
storage = blogging_engine.storage
config = blogging_engine.config
count = count or config.get("BLOGGING_POSTS_PER_PAGE", 10)
meta = _get_meta(storage, count, page)
offset = meta["offset"]
meta["is_user_blogger"] = _... | Serves the page with a list of blog posts
:param count:
:param offset:
:return: | train | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/views.py#L104-L133 | [
"def _get_blogging_engine(app):\n return app.extensions[\"FLASK_BLOGGING_ENGINE\"]\n",
"def _get_meta(storage, count, page, tag=None, user_id=None):\n max_posts = storage.count_posts(tag=tag, user_id=user_id)\n max_pages = math.ceil(float(max_posts)/float(count))\n max_offset = (max_pages-1)*count\n ... | from __future__ import division
try:
from builtins import str
except ImportError:
pass
from flask import escape
from .processor import PostProcessor
from flask_login import login_required, current_user
from flask import Blueprint, current_app, render_template, request, redirect, \
url_for, flash, make_respo... |
pydata/pandas-gbq | pandas_gbq/auth.py | get_service_account_credentials | python | def get_service_account_credentials(private_key):
import google.auth.transport.requests
from google.oauth2.service_account import Credentials
is_path = os.path.isfile(private_key)
try:
if is_path:
with open(private_key) as f:
json_key = json.loads(f.read())
... | DEPRECATED: Load service account credentials from key data or key path. | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/auth.py#L53-L92 | null | """Private module for fetching Google BigQuery credentials."""
import json
import logging
import os
import os.path
import pandas_gbq.exceptions
logger = logging.getLogger(__name__)
CREDENTIALS_CACHE_DIRNAME = "pandas_gbq"
CREDENTIALS_CACHE_FILENAME = "bigquery_credentials.dat"
SCOPES = ["https://www.googleapis.com... |
pydata/pandas-gbq | pandas_gbq/load.py | encode_chunk | python | def encode_chunk(dataframe):
csv_buffer = six.StringIO()
dataframe.to_csv(
csv_buffer,
index=False,
header=False,
encoding="utf-8",
float_format="%.15g",
date_format="%Y-%m-%d %H:%M:%S.%f",
)
# Convert to a BytesIO buffer so that unicode text is properly ... | Return a file-like object of CSV-encoded rows.
Args:
dataframe (pandas.DataFrame): A chunk of a dataframe to encode | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/load.py#L9-L31 | null | """Helper methods for loading data into BigQuery"""
import six
from google.cloud import bigquery
import pandas_gbq.schema
def encode_chunks(dataframe, chunksize=None):
dataframe = dataframe.reset_index(drop=True)
if chunksize is None:
yield 0, encode_chunk(dataframe)
return
remaining_r... |
pydata/pandas-gbq | pandas_gbq/gbq.py | _bqschema_to_nullsafe_dtypes | python | def _bqschema_to_nullsafe_dtypes(schema_fields):
# If you update this mapping, also update the table at
# `docs/source/reading.rst`.
dtype_map = {
"FLOAT": np.dtype(float),
# pandas doesn't support timezone-aware dtype in DataFrame/Series
# constructors. It's more idiomatic to locali... | Specify explicit dtypes based on BigQuery schema.
This function only specifies a dtype when the dtype allows nulls.
Otherwise, use pandas's default dtype choice.
See: http://pandas.pydata.org/pandas-docs/dev/missing_data.html
#missing-data-casting-rules-and-indexing | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L662-L694 | null | import logging
import time
import warnings
from datetime import datetime
import numpy as np
try:
# The BigQuery Storage API client is an optional dependency. It is only
# required when use_bqstorage_api=True.
from google.cloud import bigquery_storage_v1beta1
except ImportError: # pragma: NO COVER
big... |
pydata/pandas-gbq | pandas_gbq/gbq.py | _cast_empty_df_dtypes | python | def _cast_empty_df_dtypes(schema_fields, df):
if not df.empty:
raise ValueError(
"DataFrame must be empty in order to cast non-nullsafe dtypes"
)
dtype_map = {"BOOLEAN": bool, "INTEGER": np.int64}
for field in schema_fields:
column = str(field["name"])
if field[... | Cast any columns in an empty dataframe to correct type.
In an empty dataframe, pandas cannot choose a dtype unless one is
explicitly provided. The _bqschema_to_nullsafe_dtypes() function only
provides dtypes when the dtype safely handles null values. This means
that empty int64 and boolean columns are ... | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L697-L722 | null | import logging
import time
import warnings
from datetime import datetime
import numpy as np
try:
# The BigQuery Storage API client is an optional dependency. It is only
# required when use_bqstorage_api=True.
from google.cloud import bigquery_storage_v1beta1
except ImportError: # pragma: NO COVER
big... |
pydata/pandas-gbq | pandas_gbq/gbq.py | _localize_df | python | def _localize_df(schema_fields, df):
for field in schema_fields:
column = str(field["name"])
if field["mode"].upper() == "REPEATED":
continue
if field["type"].upper() == "TIMESTAMP" and df[column].dt.tz is None:
df[column] = df[column].dt.tz_localize("UTC")
retu... | Localize any TIMESTAMP columns to tz-aware type.
In pandas versions before 0.24.0, DatetimeTZDtype cannot be used as the
dtype in Series/DataFrame construction, so localize those columns after
the DataFrame is constructed. | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L725-L740 | null | import logging
import time
import warnings
from datetime import datetime
import numpy as np
try:
# The BigQuery Storage API client is an optional dependency. It is only
# required when use_bqstorage_api=True.
from google.cloud import bigquery_storage_v1beta1
except ImportError: # pragma: NO COVER
big... |
pydata/pandas-gbq | pandas_gbq/gbq.py | read_gbq | python | def read_gbq(
query,
project_id=None,
index_col=None,
col_order=None,
reauth=False,
auth_local_webserver=False,
dialect=None,
location=None,
configuration=None,
credentials=None,
use_bqstorage_api=False,
verbose=None,
private_key=None,
):
r"""Load data from Google... | r"""Load data from Google BigQuery using google-cloud-python
The main method a user calls to execute a Query in Google BigQuery
and read results into a pandas DataFrame.
This method uses the Google Cloud client library to make requests to
Google BigQuery, documented `here
<https://google-cloud-pyt... | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L758-L954 | [
"def _test_google_api_imports():\n\n try:\n import pydata_google_auth # noqa\n except ImportError as ex:\n raise ImportError(\n \"pandas-gbq requires pydata-google-auth: {0}\".format(ex)\n )\n\n try:\n from google_auth_oauthlib.flow import InstalledAppFlow # noqa\n ... | import logging
import time
import warnings
from datetime import datetime
import numpy as np
try:
# The BigQuery Storage API client is an optional dependency. It is only
# required when use_bqstorage_api=True.
from google.cloud import bigquery_storage_v1beta1
except ImportError: # pragma: NO COVER
big... |
pydata/pandas-gbq | pandas_gbq/gbq.py | to_gbq | python | def to_gbq(
dataframe,
destination_table,
project_id=None,
chunksize=None,
reauth=False,
if_exists="fail",
auth_local_webserver=False,
table_schema=None,
location=None,
progress_bar=True,
credentials=None,
verbose=None,
private_key=None,
):
_test_google_api_impor... | Write a DataFrame to a Google BigQuery table.
The main method a user calls to export pandas DataFrame contents to
Google BigQuery table.
This method uses the Google Cloud client library to make requests to
Google BigQuery, documented `here
<https://google-cloud-python.readthedocs.io/en/latest/bigq... | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L957-L1160 | [
"def _test_google_api_imports():\n\n try:\n import pydata_google_auth # noqa\n except ImportError as ex:\n raise ImportError(\n \"pandas-gbq requires pydata-google-auth: {0}\".format(ex)\n )\n\n try:\n from google_auth_oauthlib.flow import InstalledAppFlow # noqa\n ... | import logging
import time
import warnings
from datetime import datetime
import numpy as np
try:
# The BigQuery Storage API client is an optional dependency. It is only
# required when use_bqstorage_api=True.
from google.cloud import bigquery_storage_v1beta1
except ImportError: # pragma: NO COVER
big... |
pydata/pandas-gbq | pandas_gbq/gbq.py | generate_bq_schema | python | def generate_bq_schema(df, default_type="STRING"):
# deprecation TimeSeries, #11121
warnings.warn(
"generate_bq_schema is deprecated and will be removed in "
"a future version",
FutureWarning,
stacklevel=2,
)
return _generate_bq_schema(df, default_type=default_type) | DEPRECATED: Given a passed df, generate the associated Google BigQuery
schema.
Parameters
----------
df : DataFrame
default_type : string
The default big query type in case the type of the column
does not exist in the schema. | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1163-L1182 | [
"def _generate_bq_schema(df, default_type=\"STRING\"):\n \"\"\"DEPRECATED: Given a dataframe, generate a Google BigQuery schema.\n\n This is a private method, but was used in external code to work around\n issues in the default schema generation. Now that individual columns can\n be overridden: https://... | import logging
import time
import warnings
from datetime import datetime
import numpy as np
try:
# The BigQuery Storage API client is an optional dependency. It is only
# required when use_bqstorage_api=True.
from google.cloud import bigquery_storage_v1beta1
except ImportError: # pragma: NO COVER
big... |
pydata/pandas-gbq | pandas_gbq/gbq.py | _generate_bq_schema | python | def _generate_bq_schema(df, default_type="STRING"):
from pandas_gbq import schema
return schema.generate_bq_schema(df, default_type=default_type) | DEPRECATED: Given a dataframe, generate a Google BigQuery schema.
This is a private method, but was used in external code to work around
issues in the default schema generation. Now that individual columns can
be overridden: https://github.com/pydata/pandas-gbq/issues/218, this
method can be removed af... | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1185-L1195 | [
"def generate_bq_schema(dataframe, default_type=\"STRING\"):\n \"\"\"Given a passed dataframe, generate the associated Google BigQuery schema.\n\n Arguments:\n dataframe (pandas.DataFrame): D\n default_type : string\n The default big query type in case the type of the column\n does not... | import logging
import time
import warnings
from datetime import datetime
import numpy as np
try:
# The BigQuery Storage API client is an optional dependency. It is only
# required when use_bqstorage_api=True.
from google.cloud import bigquery_storage_v1beta1
except ImportError: # pragma: NO COVER
big... |
pydata/pandas-gbq | pandas_gbq/gbq.py | GbqConnector.schema | python | def schema(self, dataset_id, table_id):
table_ref = self.client.dataset(dataset_id).table(table_id)
try:
table = self.client.get_table(table_ref)
remote_schema = table.schema
remote_fields = [
field_remote.to_api_repr() for field_remote in remote_sch... | Retrieve the schema of the table
Obtain from BigQuery the field names and field types
for the table defined by the parameters
Parameters
----------
dataset_id : str
Name of the BigQuery dataset for the table
table_id : str
Name of the BigQuery ta... | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L550-L583 | [
"def process_http_error(ex):\n # See `BigQuery Troubleshooting Errors\n # <https://cloud.google.com/bigquery/troubleshooting-errors>`__\n\n raise GenericGBQException(\"Reason: {0}\".format(ex))\n"
] | class GbqConnector(object):
def __init__(
self,
project_id,
reauth=False,
private_key=None,
auth_local_webserver=False,
dialect="standard",
location=None,
credentials=None,
use_bqstorage_api=False,
):
global context
from goo... |
pydata/pandas-gbq | pandas_gbq/gbq.py | GbqConnector._clean_schema_fields | python | def _clean_schema_fields(self, fields):
fields_sorted = sorted(fields, key=lambda field: field["name"])
# Ignore mode and description when comparing schemas.
return [
{"name": field["name"], "type": field["type"]}
for field in fields_sorted
] | Return a sanitized version of the schema for comparisons. | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L585-L592 | null | class GbqConnector(object):
def __init__(
self,
project_id,
reauth=False,
private_key=None,
auth_local_webserver=False,
dialect="standard",
location=None,
credentials=None,
use_bqstorage_api=False,
):
global context
from goo... |
pydata/pandas-gbq | pandas_gbq/gbq.py | GbqConnector.verify_schema | python | def verify_schema(self, dataset_id, table_id, schema):
fields_remote = self._clean_schema_fields(
self.schema(dataset_id, table_id)
)
fields_local = self._clean_schema_fields(schema["fields"])
return fields_remote == fields_local | Indicate whether schemas match exactly
Compare the BigQuery table identified in the parameters with
the schema passed in and indicate whether all fields in the former
are present in the latter. Order is not considered.
Parameters
----------
dataset_id :str
N... | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L594-L622 | [
"def schema(self, dataset_id, table_id):\n \"\"\"Retrieve the schema of the table\n\n Obtain from BigQuery the field names and field types\n for the table defined by the parameters\n\n Parameters\n ----------\n dataset_id : str\n Name of the BigQuery dataset for the table\n table_id : st... | class GbqConnector(object):
def __init__(
self,
project_id,
reauth=False,
private_key=None,
auth_local_webserver=False,
dialect="standard",
location=None,
credentials=None,
use_bqstorage_api=False,
):
global context
from goo... |
pydata/pandas-gbq | pandas_gbq/gbq.py | GbqConnector.schema_is_subset | python | def schema_is_subset(self, dataset_id, table_id, schema):
fields_remote = self._clean_schema_fields(
self.schema(dataset_id, table_id)
)
fields_local = self._clean_schema_fields(schema["fields"])
return all(field in fields_remote for field in fields_local) | Indicate whether the schema to be uploaded is a subset
Compare the BigQuery table identified in the parameters with
the schema passed in and indicate whether a subset of the fields in
the former are present in the latter. Order is not considered.
Parameters
----------
d... | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L624-L652 | [
"def schema(self, dataset_id, table_id):\n \"\"\"Retrieve the schema of the table\n\n Obtain from BigQuery the field names and field types\n for the table defined by the parameters\n\n Parameters\n ----------\n dataset_id : str\n Name of the BigQuery dataset for the table\n table_id : st... | class GbqConnector(object):
def __init__(
self,
project_id,
reauth=False,
private_key=None,
auth_local_webserver=False,
dialect="standard",
location=None,
credentials=None,
use_bqstorage_api=False,
):
global context
from goo... |
pydata/pandas-gbq | pandas_gbq/gbq.py | _Table.exists | python | def exists(self, table_id):
from google.api_core.exceptions import NotFound
table_ref = self.client.dataset(self.dataset_id).table(table_id)
try:
self.client.get_table(table_ref)
return True
except NotFound:
return False
except self.http_error... | Check if a table exists in Google BigQuery
Parameters
----------
table : str
Name of table to be verified
Returns
-------
boolean
true if table exists, otherwise false | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1217-L1239 | [
"def process_http_error(ex):\n # See `BigQuery Troubleshooting Errors\n # <https://cloud.google.com/bigquery/troubleshooting-errors>`__\n\n raise GenericGBQException(\"Reason: {0}\".format(ex))\n"
] | class _Table(GbqConnector):
def __init__(
self,
project_id,
dataset_id,
reauth=False,
location=None,
credentials=None,
private_key=None,
):
self.dataset_id = dataset_id
super(_Table, self).__init__(
project_id,
reaut... |
pydata/pandas-gbq | pandas_gbq/gbq.py | _Table.create | python | def create(self, table_id, schema):
from google.cloud.bigquery import SchemaField
from google.cloud.bigquery import Table
if self.exists(table_id):
raise TableCreationError(
"Table {0} already " "exists".format(table_id)
)
if not _Dataset(self.pr... | Create a table in Google BigQuery given a table and schema
Parameters
----------
table : str
Name of table to be written
schema : str
Use the generate_bq_schema to generate your table schema from a
dataframe. | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1241-L1286 | [
"def exists(self, table_id):\n \"\"\" Check if a table exists in Google BigQuery\n\n Parameters\n ----------\n table : str\n Name of table to be verified\n\n Returns\n -------\n boolean\n true if table exists, otherwise false\n \"\"\"\n from google.api_core.exceptions import... | class _Table(GbqConnector):
def __init__(
self,
project_id,
dataset_id,
reauth=False,
location=None,
credentials=None,
private_key=None,
):
self.dataset_id = dataset_id
super(_Table, self).__init__(
project_id,
reaut... |
pydata/pandas-gbq | pandas_gbq/gbq.py | _Table.delete | python | def delete(self, table_id):
from google.api_core.exceptions import NotFound
if not self.exists(table_id):
raise NotFoundException("Table does not exist")
table_ref = self.client.dataset(self.dataset_id).table(table_id)
try:
self.client.delete_table(table_ref)
... | Delete a table in Google BigQuery
Parameters
----------
table : str
Name of table to be deleted | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1288-L1308 | [
"def exists(self, table_id):\n \"\"\" Check if a table exists in Google BigQuery\n\n Parameters\n ----------\n table : str\n Name of table to be verified\n\n Returns\n -------\n boolean\n true if table exists, otherwise false\n \"\"\"\n from google.api_core.exceptions import... | class _Table(GbqConnector):
def __init__(
self,
project_id,
dataset_id,
reauth=False,
location=None,
credentials=None,
private_key=None,
):
self.dataset_id = dataset_id
super(_Table, self).__init__(
project_id,
reaut... |
pydata/pandas-gbq | pandas_gbq/gbq.py | _Dataset.exists | python | def exists(self, dataset_id):
from google.api_core.exceptions import NotFound
try:
self.client.get_dataset(self.client.dataset(dataset_id))
return True
except NotFound:
return False
except self.http_error as ex:
self.process_http_error(ex) | Check if a dataset exists in Google BigQuery
Parameters
----------
dataset_id : str
Name of dataset to be verified
Returns
-------
boolean
true if dataset exists, otherwise false | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1328-L1349 | [
"def process_http_error(ex):\n # See `BigQuery Troubleshooting Errors\n # <https://cloud.google.com/bigquery/troubleshooting-errors>`__\n\n raise GenericGBQException(\"Reason: {0}\".format(ex))\n"
] | class _Dataset(GbqConnector):
def __init__(
self,
project_id,
reauth=False,
location=None,
credentials=None,
private_key=None,
):
super(_Dataset, self).__init__(
project_id,
reauth,
credentials=credentials,
l... |
pydata/pandas-gbq | pandas_gbq/gbq.py | _Dataset.create | python | def create(self, dataset_id):
from google.cloud.bigquery import Dataset
if self.exists(dataset_id):
raise DatasetCreationError(
"Dataset {0} already " "exists".format(dataset_id)
)
dataset = Dataset(self.client.dataset(dataset_id))
if self.locat... | Create a dataset in Google BigQuery
Parameters
----------
dataset : str
Name of dataset to be written | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1351-L1374 | [
"def exists(self, dataset_id):\n \"\"\" Check if a dataset exists in Google BigQuery\n\n Parameters\n ----------\n dataset_id : str\n Name of dataset to be verified\n\n Returns\n -------\n boolean\n true if dataset exists, otherwise false\n \"\"\"\n from google.api_core.exce... | class _Dataset(GbqConnector):
def __init__(
self,
project_id,
reauth=False,
location=None,
credentials=None,
private_key=None,
):
super(_Dataset, self).__init__(
project_id,
reauth,
credentials=credentials,
l... |
pydata/pandas-gbq | pandas_gbq/schema.py | update_schema | python | def update_schema(schema_old, schema_new):
old_fields = schema_old["fields"]
new_fields = schema_new["fields"]
output_fields = list(old_fields)
field_indices = {field["name"]: i for i, field in enumerate(output_fields)}
for field in new_fields:
name = field["name"]
if name in field... | Given an old BigQuery schema, update it with a new one.
Where a field name is the same, the new will replace the old. Any
new fields not present in the old schema will be added.
Arguments:
schema_old: the old schema to update
schema_new: the new schema which will overwrite/extend the old | train | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/schema.py#L38-L64 | null | """Helper methods for BigQuery schemas"""
def generate_bq_schema(dataframe, default_type="STRING"):
"""Given a passed dataframe, generate the associated Google BigQuery schema.
Arguments:
dataframe (pandas.DataFrame): D
default_type : string
The default big query type in case the type of ... |
IS-ENES-Data/esgf-pid | esgfpid/rabbit/asynchronous/thread_builder.py | ConnectionBuilder.__start_waiting_for_events | python | def __start_waiting_for_events(self):
'''
This waits until the whole chain of callback methods triggered by
"trigger_connection_to_rabbit_etc()" has finished, and then starts
waiting for publications.
This is done by starting the ioloop.
Note: In the pika usage example,... | This waits until the whole chain of callback methods triggered by
"trigger_connection_to_rabbit_etc()" has finished, and then starts
waiting for publications.
This is done by starting the ioloop.
Note: In the pika usage example, these things are both called inside the run()
met... | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/rabbit/asynchronous/thread_builder.py#L111-L184 | [
"def logdebug(logger, msg, *args, **kwargs):\n '''\n Logs messages as DEBUG,\n unless show=True and esgfpid.defaults.LOG_SHOW_TO_INFO=True,\n (then it logs messages as INFO).\n '''\n if esgfpid.defaults.LOG_DEBUG_TO_INFO:\n logger.info('DEBUG %s ' % msg, *args, **kwargs)\n else:\n ... | class ConnectionBuilder(object):
def __init__(self, thread, statemachine, confirmer, returnhandler, shutter, nodemanager):
self.thread = thread
self.statemachine = statemachine
'''
We need to pass the "confirmer.on_delivery_confirmation()" callback to
RabbitMQ's channel.'''... |
IS-ENES-Data/esgf-pid | esgfpid/utils/logutils.py | logtrace | python | def logtrace(logger, msg, *args, **kwargs):
'''
If esgfpid.defaults.LOG_TRACE_TO_DEBUG, messages are treated
like debug messages (with an added [trace]).
Otherwise, they are ignored.
'''
if esgfpid.defaults.LOG_TRACE_TO_DEBUG:
logdebug(logger, '[trace] %s' % msg, *args, **kwargs)
els... | If esgfpid.defaults.LOG_TRACE_TO_DEBUG, messages are treated
like debug messages (with an added [trace]).
Otherwise, they are ignored. | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/utils/logutils.py#L7-L16 | null | import esgfpid.defaults
#
# Logging helpers
#
def logdebug(logger, msg, *args, **kwargs):
'''
Logs messages as DEBUG,
unless show=True and esgfpid.defaults.LOG_SHOW_TO_INFO=True,
(then it logs messages as INFO).
'''
if esgfpid.defaults.LOG_DEBUG_TO_INFO:
logger.info('DEBUG %s ' % msg,... |
IS-ENES-Data/esgf-pid | esgfpid/utils/logutils.py | logdebug | python | def logdebug(logger, msg, *args, **kwargs):
'''
Logs messages as DEBUG,
unless show=True and esgfpid.defaults.LOG_SHOW_TO_INFO=True,
(then it logs messages as INFO).
'''
if esgfpid.defaults.LOG_DEBUG_TO_INFO:
logger.info('DEBUG %s ' % msg, *args, **kwargs)
else:
logger.debug(... | Logs messages as DEBUG,
unless show=True and esgfpid.defaults.LOG_SHOW_TO_INFO=True,
(then it logs messages as INFO). | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/utils/logutils.py#L18-L27 | [
"def debug(self, msg, *args, **kwargs):\n logging.warn('DEBUG! '+str(msg))\n msgf = msg % args\n self.debug_messages.append(msgf)\n"
] | import esgfpid.defaults
#
# Logging helpers
#
def logtrace(logger, msg, *args, **kwargs):
'''
If esgfpid.defaults.LOG_TRACE_TO_DEBUG, messages are treated
like debug messages (with an added [trace]).
Otherwise, they are ignored.
'''
if esgfpid.defaults.LOG_TRACE_TO_DEBUG:
logdebug(logg... |
IS-ENES-Data/esgf-pid | esgfpid/utils/logutils.py | loginfo | python | def loginfo(logger, msg, *args, **kwargs):
'''
Logs messages as INFO,
unless esgfpid.defaults.LOG_INFO_TO_DEBUG,
(then it logs messages as DEBUG).
'''
if esgfpid.defaults.LOG_INFO_TO_DEBUG:
logger.debug(msg, *args, **kwargs)
else:
logger.info(msg, *args, **kwargs) | Logs messages as INFO,
unless esgfpid.defaults.LOG_INFO_TO_DEBUG,
(then it logs messages as DEBUG). | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/utils/logutils.py#L29-L38 | [
"def info(self, msg, *args, **kwargs):\n msgf = msg % args\n self.info_messages.append(msgf)\n"
] | import esgfpid.defaults
#
# Logging helpers
#
def logtrace(logger, msg, *args, **kwargs):
'''
If esgfpid.defaults.LOG_TRACE_TO_DEBUG, messages are treated
like debug messages (with an added [trace]).
Otherwise, they are ignored.
'''
if esgfpid.defaults.LOG_TRACE_TO_DEBUG:
logdebug(logg... |
IS-ENES-Data/esgf-pid | esgfpid/utils/logutils.py | log_every_x_times | python | def log_every_x_times(logger, counter, x, msg, *args, **kwargs):
'''
Works like logdebug, but only prints first and
and every xth message.
'''
if counter==1 or counter % x == 0:
#msg = msg + (' (counter %i)' % counter)
logdebug(logger, msg, *args, **kwargs) | Works like logdebug, but only prints first and
and every xth message. | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/utils/logutils.py#L47-L54 | [
"def logdebug(logger, msg, *args, **kwargs):\n '''\n Logs messages as DEBUG,\n unless show=True and esgfpid.defaults.LOG_SHOW_TO_INFO=True,\n (then it logs messages as INFO).\n '''\n if esgfpid.defaults.LOG_DEBUG_TO_INFO:\n logger.info('DEBUG %s ' % msg, *args, **kwargs)\n else:\n ... | import esgfpid.defaults
#
# Logging helpers
#
def logtrace(logger, msg, *args, **kwargs):
'''
If esgfpid.defaults.LOG_TRACE_TO_DEBUG, messages are treated
like debug messages (with an added [trace]).
Otherwise, they are ignored.
'''
if esgfpid.defaults.LOG_TRACE_TO_DEBUG:
logdebug(logg... |
IS-ENES-Data/esgf-pid | esgfpid/solr/tasks/filehandles_same_dataset.py | FindFilesOfSameDatasetVersion.retrieve_file_handles_of_same_dataset | python | def retrieve_file_handles_of_same_dataset(self, **args):
'''
:return: List of handles, or empty list. Should never return None.
:raise: SolrSwitchedOff
:raise SolrError: If both strategies to find file handles failed.
'''
mandatory_args = ['drs_id', 'version_number', 'dat... | :return: List of handles, or empty list. Should never return None.
:raise: SolrSwitchedOff
:raise SolrError: If both strategies to find file handles failed. | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/solr/tasks/filehandles_same_dataset.py#L21-L50 | [
"def check_presence_of_mandatory_args(args, mandatory_args):\n missing_args = []\n for name in mandatory_args:\n if name not in args.keys():\n missing_args.append(name)\n if len(missing_args)>0:\n raise esgfpid.exceptions.ArgumentError('Missing mandatory arguments: '+', '.join(miss... | class FindFilesOfSameDatasetVersion(object):
def __init__(self, solr_interactor):
self.__solr_interactor = solr_interactor
self.__error_messages = None
def __reset_error_messages(self):
self.__error_messages = []
# General methods:
def __strategy1(self, args):
return... |
IS-ENES-Data/esgf-pid | esgfpid/utils/timeutils.py | get_now_utc | python | def get_now_utc():
''' date in UTC, ISO format'''
# Helper class for UTC time
# Source: http://stackoverflow.com/questions/2331592/datetime-datetime-utcnow-why-no-tzinfo
ZERO = datetime.timedelta(0)
class UTC(datetime.tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZE... | date in UTC, ISO format | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/utils/timeutils.py#L10-L27 | null | import datetime
def get_now_utc_as_formatted_string():
now = get_now_utc()
now_string = datetime.datetime.isoformat(now) # 2015-12-21T10:31:37.524825+00:00
return now_string
|
IS-ENES-Data/esgf-pid | esgfpid/solr/tasks/all_versions_of_dataset.py | FindVersionsOfSameDataset.retrieve_dataset_handles_or_version_numbers_of_all_versions | python | def retrieve_dataset_handles_or_version_numbers_of_all_versions(self, drs_id, prefix):
'''
:return: Dict. Should never return None.
:raise: SolrSwitchedOff
:raise SolrError: If ...
'''
self.__reset_error_messages()
response_json = self.__ask_solr_for_handles_or_ve... | :return: Dict. Should never return None.
:raise: SolrSwitchedOff
:raise SolrError: If ... | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/solr/tasks/all_versions_of_dataset.py#L19-L28 | [
"def __reset_error_messages(self):\n self.__error_messages = []\n",
"def __ask_solr_for_handles_or_version_numbers_of_all_versions(self, drs_id):\n LOGGER.debug('Asking solr for dataset handles or version numbers of all dataset versions with the drs_id \"%s\".', drs_id)\n query = self.__make_query_for_ha... | class FindVersionsOfSameDataset(object):
def __init__(self, solr_interactor):
self.__solr_interactor = solr_interactor
self.__error_messages = None
def __reset_error_messages(self):
self.__error_messages = []
# General methods:
# Querying solr for handles and/or version numb... |
IS-ENES-Data/esgf-pid | esgfpid/connector.py | Connector.create_publication_assistant | python | def create_publication_assistant(self, **args):
'''
Create an assistant for a dataset that allows to make PID
requests for the dataset and all of its files.
:param drs_id: Mandatory. The dataset id of the dataset
to be published.
:param version_number: Mandatory. Th... | Create an assistant for a dataset that allows to make PID
requests for the dataset and all of its files.
:param drs_id: Mandatory. The dataset id of the dataset
to be published.
:param version_number: Mandatory. The version number of the
dataset to be published.
... | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/connector.py#L287-L341 | [
"def check_presence_of_mandatory_args(args, mandatory_args):\n missing_args = []\n for name in mandatory_args:\n if name not in args.keys():\n missing_args.append(name)\n if len(missing_args)>0:\n raise esgfpid.exceptions.ArgumentError('Missing mandatory arguments: '+', '.join(miss... | class Connector(object):
'''
This class provides the main functionality for the ESGF PID
module.
Author: Merret Buurman (DKRZ), 2015-2016
'''
def __init__(self, **args):
'''
Create a connector object with the necessary config
to connect to a RabbitMQ messaging server a... |
IS-ENES-Data/esgf-pid | esgfpid/connector.py | Connector.unpublish_one_version | python | def unpublish_one_version(self, **args):
'''
Sends a PID update request for the unpublication of one version
of a dataset currently published at the given data node.
Either the handle or the pair of drs_id and version_number
have to be provided, otherwise an exception will occur... | Sends a PID update request for the unpublication of one version
of a dataset currently published at the given data node.
Either the handle or the pair of drs_id and version_number
have to be provided, otherwise an exception will occur.
The consumer will of course check the PID request ... | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/connector.py#L351-L401 | [
"def add_missing_optional_args_with_value_none(args, optional_args):\n for name in optional_args:\n if not name in args.keys():\n args[name] = None\n return args\n",
"def logwarn(logger, msg, *args, **kwargs):\n logger.warn(msg, *args, **kwargs)\n",
"def get_now_utc_as_formatted_strin... | class Connector(object):
'''
This class provides the main functionality for the ESGF PID
module.
Author: Merret Buurman (DKRZ), 2015-2016
'''
def __init__(self, **args):
'''
Create a connector object with the necessary config
to connect to a RabbitMQ messaging server a... |
IS-ENES-Data/esgf-pid | esgfpid/connector.py | Connector.unpublish_all_versions | python | def unpublish_all_versions(self, **args):
'''
Sends a PID update request for the unpublication of all versions
of a dataset currently published at the given data node.
If the library has solr access, it will try to find all the
dataset versions and their handles from solr, and s... | Sends a PID update request for the unpublication of all versions
of a dataset currently published at the given data node.
If the library has solr access, it will try to find all the
dataset versions and their handles from solr, and send individual
messages for each version. Otherwise, o... | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/connector.py#L403-L446 | [
"def check_presence_of_mandatory_args(args, mandatory_args):\n missing_args = []\n for name in mandatory_args:\n if name not in args.keys():\n missing_args.append(name)\n if len(missing_args)>0:\n raise esgfpid.exceptions.ArgumentError('Missing mandatory arguments: '+', '.join(miss... | class Connector(object):
'''
This class provides the main functionality for the ESGF PID
module.
Author: Merret Buurman (DKRZ), 2015-2016
'''
def __init__(self, **args):
'''
Create a connector object with the necessary config
to connect to a RabbitMQ messaging server a... |
IS-ENES-Data/esgf-pid | esgfpid/connector.py | Connector.add_errata_ids | python | def add_errata_ids(self, **args):
'''
Add errata ids to a dataset handle record.
To call this method, you do not need to provide the
PID of the dataset. Instead, the PID string is derived
from the dataset id and the version number.
:param errata_ids: Mandatory. A list o... | Add errata ids to a dataset handle record.
To call this method, you do not need to provide the
PID of the dataset. Instead, the PID string is derived
from the dataset id and the version number.
:param errata_ids: Mandatory. A list of errata ids (strings)
to be added to the ... | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/connector.py#L448-L484 | [
"def check_presence_of_mandatory_args(args, mandatory_args):\n missing_args = []\n for name in mandatory_args:\n if name not in args.keys():\n missing_args.append(name)\n if len(missing_args)>0:\n raise esgfpid.exceptions.ArgumentError('Missing mandatory arguments: '+', '.join(miss... | class Connector(object):
'''
This class provides the main functionality for the ESGF PID
module.
Author: Merret Buurman (DKRZ), 2015-2016
'''
def __init__(self, **args):
'''
Create a connector object with the necessary config
to connect to a RabbitMQ messaging server a... |
IS-ENES-Data/esgf-pid | esgfpid/connector.py | Connector.create_data_cart_pid | python | def create_data_cart_pid(self, dict_of_drs_ids_and_pids):
'''
Create a handle record for a data cart (a custom set of datasets).
The handle string is made of the prefix passed to tbe library,
and a hash over all the dataset ids in the cart. This way, if exactly
the same set of d... | Create a handle record for a data cart (a custom set of datasets).
The handle string is made of the prefix passed to tbe library,
and a hash over all the dataset ids in the cart. This way, if exactly
the same set of datasets is passed several times, the same handle
record is created, in... | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/connector.py#L525-L544 | [
"def make_data_cart_pid(self, dict_of_drs_ids_and_pids):\n logdebug(LOGGER, 'Making a PID for a data cart full of datasets...')\n\n # Check arg\n if not type(dict_of_drs_ids_and_pids) == type(dict()):\n if type(dict_of_drs_ids_and_pids) == type([]):\n raise esgfpid.exceptions.ArgumentErro... | class Connector(object):
'''
This class provides the main functionality for the ESGF PID
module.
Author: Merret Buurman (DKRZ), 2015-2016
'''
def __init__(self, **args):
'''
Create a connector object with the necessary config
to connect to a RabbitMQ messaging server a... |
IS-ENES-Data/esgf-pid | esgfpid/connector.py | Connector.make_handle_from_drsid_and_versionnumber | python | def make_handle_from_drsid_and_versionnumber(self, **args):
'''
Create a handle string for a specific dataset, based
on its dataset id and version number, and the prefix
passed to the library at initializing.
:param drs_id: The dataset id of the dataset.
:param version_n... | Create a handle string for a specific dataset, based
on its dataset id and version number, and the prefix
passed to the library at initializing.
:param drs_id: The dataset id of the dataset.
:param version_number: The version number of the dataset
(as a string or integer, th... | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/connector.py#L605-L617 | [
"def make_handle_from_drsid_and_versionnumber(**args):\n check_presence_of_mandatory_args(args, ['drs_id','version_number','prefix'])\n suffix = make_suffix_from_drsid_and_versionnumber(drs_id=args['drs_id'], version_number=args['version_number'])\n return _suffix_to_handle(args['prefix'], suffix)\n"
] | class Connector(object):
'''
This class provides the main functionality for the ESGF PID
module.
Author: Merret Buurman (DKRZ), 2015-2016
'''
def __init__(self, **args):
'''
Create a connector object with the necessary config
to connect to a RabbitMQ messaging server a... |
IS-ENES-Data/esgf-pid | esgfpid/assistant/publish.py | DatasetPublicationAssistant.add_file | python | def add_file(self, **args):
'''
Adds a file's information to the set of files to be
published in this dataset.
:param file_name: Mandatory. The file name (string).
This information will simply be included in the
PID record, but not used for anything.
:pa... | Adds a file's information to the set of files to be
published in this dataset.
:param file_name: Mandatory. The file name (string).
This information will simply be included in the
PID record, but not used for anything.
:param file_handle: Mandatory. The handle (PID) of
... | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/assistant/publish.py#L119-L177 | [
"def check_presence_of_mandatory_args(args, mandatory_args):\n missing_args = []\n for name in mandatory_args:\n if name not in args.keys():\n missing_args.append(name)\n if len(missing_args)>0:\n raise esgfpid.exceptions.ArgumentError('Missing mandatory arguments: '+', '.join(miss... | class DatasetPublicationAssistant(object):
def __init__(self, **args):
logdebug(LOGGER, 'Constructor for Publication assistant for dataset "%s", version "%s" at host "%s".',
args['drs_id'],
args['version_number'],
args['data_node']
)
# Check args
... |
IS-ENES-Data/esgf-pid | esgfpid/assistant/publish.py | DatasetPublicationAssistant.dataset_publication_finished | python | def dataset_publication_finished(self, ignore_exception=False):
'''
This is the "commit". It triggers the creation/update of handles.
* Check if the set of files corresponds to the previously published set (if applicable, and if solr url given, and if solr replied)
* The dataset... | This is the "commit". It triggers the creation/update of handles.
* Check if the set of files corresponds to the previously published set (if applicable, and if solr url given, and if solr replied)
* The dataset publication message is created and sent to the queue.
* All file publicatio... | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/assistant/publish.py#L241-L257 | [
"def loginfo(logger, msg, *args, **kwargs):\n '''\n Logs messages as INFO,\n unless esgfpid.defaults.LOG_INFO_TO_DEBUG,\n (then it logs messages as DEBUG).\n '''\n if esgfpid.defaults.LOG_INFO_TO_DEBUG:\n logger.debug(msg, *args, **kwargs)\n else:\n logger.info(msg, *args, **kwarg... | class DatasetPublicationAssistant(object):
def __init__(self, **args):
logdebug(LOGGER, 'Constructor for Publication assistant for dataset "%s", version "%s" at host "%s".',
args['drs_id'],
args['version_number'],
args['data_node']
)
# Check args
... |
IS-ENES-Data/esgf-pid | esgfpid/solr/solr.py | SolrInteractor.send_query | python | def send_query(self, query):
''' This method is called by the tasks. It is redirected to the submodule.'''
if self.__switched_on:
return self.__solr_server_connector.send_query(query)
else:
msg = 'Not sending query'
LOGGER.debug(msg)
raise esgfpid.... | This method is called by the tasks. It is redirected to the submodule. | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/solr/solr.py#L104-L111 | null | class SolrInteractor(object):
# Constructor:
'''
:param switched_off: Mandatory. Boolean.
:param prefix: Mandatory if not switched off.
:param solr_url: Mandatory if not switched off.
:param https_verify: Mandatory if not switched off.
:param disable_insecure_request_warning: Mandatory if ... |
IS-ENES-Data/esgf-pid | esgfpid/solr/solr.py | SolrInteractor.retrieve_file_handles_of_same_dataset | python | def retrieve_file_handles_of_same_dataset(self, **args):
'''
:return: List of handles, or empty list. Should never return None.
:raise: SolrSwitchedOff
:raise SolrError: If both strategies to find file handles failed.
'''
mandatory_args = ['drs_id', 'version_number', 'da... | :return: List of handles, or empty list. Should never return None.
:raise: SolrSwitchedOff
:raise SolrError: If both strategies to find file handles failed. | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/solr/solr.py#L126-L142 | [
"def check_presence_of_mandatory_args(args, mandatory_args):\n missing_args = []\n for name in mandatory_args:\n if name not in args.keys():\n missing_args.append(name)\n if len(missing_args)>0:\n raise esgfpid.exceptions.ArgumentError('Missing mandatory arguments: '+', '.join(miss... | class SolrInteractor(object):
# Constructor:
'''
:param switched_off: Mandatory. Boolean.
:param prefix: Mandatory if not switched off.
:param solr_url: Mandatory if not switched off.
:param https_verify: Mandatory if not switched off.
:param disable_insecure_request_warning: Mandatory if ... |
IS-ENES-Data/esgf-pid | esgfpid/rabbit/nodemanager.py | NodeManager.__complete_info_dict | python | def __complete_info_dict(self, node_info_dict, is_open):
# Make pika credentials
creds = pika.PlainCredentials(
node_info_dict['username'],
node_info_dict['password']
)
node_info_dict['credentials'] = creds
if 'priority' in node_info_dict and node_info_di... | https://pika.readthedocs.org/en/0.9.6/connecting.html
class pika.connection.ConnectionParameters(
host=None, port=None, virtual_host=None, credentials=None, channel_max=None,
frame_max=None, heartbeat_interval=None, ssl=None, ssl_options=None,
connection_attempts=None, retry_... | train | https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/rabbit/nodemanager.py#L256-L316 | null | class NodeManager(object):
'''
Constructor that takes no params. It creates an empty
container for RabbitMQ node information. The node
information then has to be added using "add_trusted_node()"
and "add_open_node()".
'''
def __init__(self):
# Props for basic_publish (needed by th... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_sales_w_lines.py | Customer.buy_product | python | def buy_product(self, product_pk):
if self.invoice_sales.filter(line_invoice_sales__line_order__product__pk=product_pk).exists() \
or self.ticket_sales.filter(line_ticket_sales__line_order__product__pk=product_pk).exists():
return True
else:
return False | determina si el customer ha comprado un producto | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales_w_lines.py#L296-L304 | null | class Customer(GenRole, CodenerixModel):
class CodenerixMeta:
abstract = ABSTRACT_GenCustomer
rol_groups = {
'Customer': CDNX_INVOICING_PERMISSIONS['customer'],
}
rol_permissions = [
'add_city',
'add_citygeonameen',
'add_citygeonamees',... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_cash.py | CashDiary.find | python | def find(pos, user):
'''
Get a valid CashDiary for today from the given POS, it will return:
- None: if no CashDiary is available today and older one was already closed
- New CashDiary: if no CashDiary is available today but there is an older one which it was opened
-... | Get a valid CashDiary for today from the given POS, it will return:
- None: if no CashDiary is available today and older one was already closed
- New CashDiary: if no CashDiary is available today but there is an older one which it was opened
- Existing CashDiary: if a CashDiary is av... | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_cash.py#L73-L128 | null | class CashDiary(CodenerixModel):
pos = models.ForeignKey(POS, related_name='cash_movements', verbose_name=_("Point of Sales"), null=True, on_delete=models.CASCADE)
opened_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='opened_cash_diarys', verbose_name=_("User"), on_delete=models.CASCADE)
o... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_sales_original.py | GenLineProduct.save | python | def save(self, *args, **kwargs):
if self.pk is None:
if hasattr(self, 'product'):
if not self.description:
self.description = self.product
self.price_recommended = self.product.price_base
elif hasattr(self, 'line_order'):
... | si al guardar una linea asociada a un documento bloqueado (lock==True), duplicar el documento en una nueva versiΓ³n | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales_original.py#L816-L843 | null | class GenLineProduct(GenLineProductBasic): # META: Abstract class
class Meta(GenLineProductBasic.Meta):
abstract = True
price_recommended = models.DecimalField(_("Recomended price base"), blank=False, null=False, max_digits=CURRENCY_MAX_DIGITS, decimal_places=CURRENCY_DECIMAL_PLACES)
# valores apl... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_sales_original.py | GenLineProduct.create_document_from_another | python | def create_document_from_another(pk, list_lines,
MODEL_SOURCE, MODEL_FINAL, MODEL_LINE_SOURCE, MODEL_LINE_FINAL,
url_reverse, related_line, related_object,
msg_error_relation, msg_error_not_found, unique):
... | pk: pk del documento origen
list_lines: listado de pk de lineas de origen
MODEL_SOURCE: modelo del documento origen
MODEL_FINAL: model del documento final
MODEL_LINE_SOURCE: modelo de la linea origen
MODEL_LINE_FINAL: modelo de la linea final
url_reverse: url del destino
... | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales_original.py#L856-L952 | null | class GenLineProduct(GenLineProductBasic): # META: Abstract class
class Meta(GenLineProductBasic.Meta):
abstract = True
price_recommended = models.DecimalField(_("Recomended price base"), blank=False, null=False, max_digits=CURRENCY_MAX_DIGITS, decimal_places=CURRENCY_DECIMAL_PLACES)
# valores apl... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_sales_original.py | GenLineProduct.create_albaran_automatic | python | def create_albaran_automatic(pk, list_lines):
line_bd = SalesLineAlbaran.objects.filter(line_order__pk__in=list_lines).values_list('line_order__pk')
if line_bd.count() == 0 or len(list_lines) != len(line_bd[0]):
# solo aquellas lineas de pedidos que no estan ya albarandas
if line... | creamos de forma automatica el albaran | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales_original.py#L1009-L1020 | null | class GenLineProduct(GenLineProductBasic): # META: Abstract class
class Meta(GenLineProductBasic.Meta):
abstract = True
price_recommended = models.DecimalField(_("Recomended price base"), blank=False, null=False, max_digits=CURRENCY_MAX_DIGITS, decimal_places=CURRENCY_DECIMAL_PLACES)
# valores apl... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_sales_original.py | GenLineProduct.create_invoice_from_albaran | python | def create_invoice_from_albaran(pk, list_lines):
context = {}
if list_lines:
new_list_lines = [x[0] for x in SalesLineAlbaran.objects.values_list('line_order__pk').filter(
pk__in=[int(x) for x in list_lines]
).exclude(invoiced=True)]
if new_list_lines:... | la pk y list_lines son de albaranes, necesitamos la info de las lineas de pedidos | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales_original.py#L1201-L1227 | null | class GenLineProduct(GenLineProductBasic): # META: Abstract class
class Meta(GenLineProductBasic.Meta):
abstract = True
price_recommended = models.DecimalField(_("Recomended price base"), blank=False, null=False, max_digits=CURRENCY_MAX_DIGITS, decimal_places=CURRENCY_DECIMAL_PLACES)
# valores apl... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_sales_original.py | GenLineProduct.create_invoice_from_ticket | python | def create_invoice_from_ticket(pk, list_lines):
context = {}
if list_lines:
new_list_lines = [x[0] for x in SalesLineTicket.objects.values_list('line_order__pk').filter(pk__in=[int(x) for x in list_lines])]
if new_list_lines:
lo = SalesLineOrder.objects.values_lis... | la pk y list_lines son de ticket, necesitamos la info de las lineas de pedidos | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales_original.py#L1230-L1249 | null | class GenLineProduct(GenLineProductBasic): # META: Abstract class
class Meta(GenLineProductBasic.Meta):
abstract = True
price_recommended = models.DecimalField(_("Recomended price base"), blank=False, null=False, max_digits=CURRENCY_MAX_DIGITS, decimal_places=CURRENCY_DECIMAL_PLACES)
# valores apl... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_sales_original.py | SalesLineBasket.set_options | python | def set_options(self, options):
with transaction.atomic():
for option in options:
opt = self.line_basket_option_sales.filter(
product_option=option['product_option']
).first()
if opt: # edit
change = False
... | options = [{
'product_option': instance of ProductFinalOption,
'product_final': instance of ProductFinal,
'quantity': Float
}, ] | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales_original.py#L1627-L1658 | null | class SalesLineBasket(GenLineProduct):
basket = models.ForeignKey(SalesBasket, related_name='line_basket_sales', verbose_name=_("Basket"), on_delete=models.CASCADE)
product = models.ForeignKey(ProductFinal, related_name='line_basket_sales', verbose_name=_("Product"), on_delete=models.CASCADE)
def __fields_... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/views_sales.py | ShoppingCartManagement.get | python | def get(self, request, *args, **kwargs):
cart = ShoppingCartProxy(request)
return JsonResponse(cart.get_products(onlypublic=request.GET.get('onlypublic', True))) | List all products in the shopping cart | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/views_sales.py#L1842-L1847 | null | class ShoppingCartManagement(View):
http_method_names = ['get', 'post', 'put', 'delete']
def post(self, request, *args, **kwargs):
"""
Adds new product to the current shopping cart
"""
POST = json.loads(request.body.decode('utf-8'))
if 'product_pk' in POST and 'quantit... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/views_sales.py | ShoppingCartManagement.post | python | def post(self, request, *args, **kwargs):
POST = json.loads(request.body.decode('utf-8'))
if 'product_pk' in POST and 'quantity' in POST:
cart = ShoppingCartProxy(request)
cart.add(
product_pk=int(POST['product_pk']),
quantity=int(POST['quantity']... | Adds new product to the current shopping cart | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/views_sales.py#L1849-L1863 | null | class ShoppingCartManagement(View):
http_method_names = ['get', 'post', 'put', 'delete']
def get(self, request, *args, **kwargs):
"""
List all products in the shopping cart
"""
cart = ShoppingCartProxy(request)
return JsonResponse(cart.get_products(onlypublic=request.GET... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/views_sales.py | LinesUpdateModalBasket.dispatch | python | def dispatch(self, *args, **kwargs):
self.__line_pk = kwargs.get('pk', None)
return super(LinesUpdateModalBasket, self).dispatch(*args, **kwargs) | if SalesLineBasketOption.objects.filter(line_budget__pk=self.__line_pk).exists():
self.form_class = LineBasketFormPack
self.__is_pack = True
else:
self.__is_pack = False | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/views_sales.py#L2190-L2199 | null | class LinesUpdateModalBasket(GenUpdateModal, LinesUpdateBasket):
# form_class = LineBasketForm
@method_decorator(login_required)
def get_form(self, form_class=None):
# form_kwargs = super(LineBasketUpdateModal, self).get_form_kwargs(*args, **kwargs)
form = super(LinesUpdateModalBasket, se... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/views_sales.py | LinesUpdateModalBasket.get_form | python | def get_form(self, form_class=None):
# form_kwargs = super(LineBasketUpdateModal, self).get_form_kwargs(*args, **kwargs)
form = super(LinesUpdateModalBasket, self).get_form(form_class)
initial = form.initial
initial['type_tax'] = self.object.product_final.product.tax.pk
initial['... | if self.__is_pack:
options = []
lang = get_language_database()
for option in SalesLineBasketOption.objects.filter(line_budget__pk=self.__line_pk):
initial['packs[{}]'.format(option.product_option.pk)] = option.product_final.pk
a = {
... | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/views_sales.py#L2201-L2225 | null | class LinesUpdateModalBasket(GenUpdateModal, LinesUpdateBasket):
# form_class = LineBasketForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
self.__line_pk = kwargs.get('pk', None)
"""
if SalesLineBasketOption.objects.filter(line_budget__pk=self.__line_pk).e... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/views_sales.py | LinesUpdateModalBasket.form_valid | python | def form_valid(self, form):
# lb = SalesLines.objects.filter(pk=self.__line_pk).first()
# product_old = lb.product_final
product_pk = self.request.POST.get("product_final", None)
quantity = self.request.POST.get("quantity", None)
product_final = ProductFinal.objects.filter(pk=pr... | if product:
is_pack = product.is_pack()
else:
is_pack = False | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/views_sales.py#L2227-L2306 | null | class LinesUpdateModalBasket(GenUpdateModal, LinesUpdateBasket):
# form_class = LineBasketForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
self.__line_pk = kwargs.get('pk', None)
"""
if SalesLineBasketOption.objects.filter(line_budget__pk=self.__line_pk).e... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_sales.py | Customer.buy_product | python | def buy_product(self, product_pk):
if self.invoice_sales.filter(lines_sales__product_final__pk=product_pk).exists() \
or self.ticket_sales.filter(lines_sales__product_final__pk=product_pk).exists():
return True
else:
return False | determina si el customer ha comprado un producto | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales.py#L288-L296 | null | class Customer(GenRole, CodenerixModel):
class CodenerixMeta:
abstract = ABSTRACT_GenCustomer
rol_groups = {
'Customer': CDNX_INVOICING_PERMISSIONS['customer'],
}
rol_permissions = [
'add_city',
'add_citygeonameen',
'add_citygeonamees',... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_sales.py | SalesLines.create_ticket_from_albaran | python | def create_ticket_from_albaran(pk, list_lines):
MODEL_SOURCE = SalesAlbaran
MODEL_FINAL = SalesTicket
url_reverse = 'CDNX_invoicing_ticketsaless_list'
# type_doc
msg_error_relation = _("Hay lineas asignadas a ticket")
msg_error_not_found = _('Sales albaran not found')
... | context = {}
if list_lines:
new_list_lines = SalesLines.objects.filter(
pk__in=[int(x) for x in list_lines]
).exclude(
invoice__isnull=True
).values_list('pk')
if new_list_lines:
new_pk = SalesLines.objects.values_l... | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales.py#L2372-L2407 | null | class SalesLines(CodenerixModel):
basket = models.ForeignKey(SalesBasket, related_name='lines_sales', verbose_name=_("Basket"), on_delete=models.CASCADE)
tax_basket_fk = models.ForeignKey(TypeTax, related_name='lines_sales_basket', verbose_name=_("Tax Basket"), on_delete=models.CASCADE)
order = models.Forei... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_sales.py | SalesLines.create_invoice_from_albaran | python | def create_invoice_from_albaran(pk, list_lines):
MODEL_SOURCE = SalesAlbaran
MODEL_FINAL = SalesInvoice
url_reverse = 'CDNX_invoicing_invoicesaless_list'
# type_doc
msg_error_relation = _("Hay lineas asignadas a facturas")
msg_error_not_found = _('Sales albaran not found'... | context = {}
if list_lines:
new_list_lines = SalesLines.objects.filter(
pk__in=[int(x) for x in list_lines]
).exclude(
invoice__isnull=False
)
if new_list_lines:
new_pk = new_list_lines.first()
if ne... | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales.py#L2410-L2447 | null | class SalesLines(CodenerixModel):
basket = models.ForeignKey(SalesBasket, related_name='lines_sales', verbose_name=_("Basket"), on_delete=models.CASCADE)
tax_basket_fk = models.ForeignKey(TypeTax, related_name='lines_sales_basket', verbose_name=_("Tax Basket"), on_delete=models.CASCADE)
order = models.Forei... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_sales.py | SalesLines.create_invoice_from_ticket | python | def create_invoice_from_ticket(pk, list_lines):
MODEL_SOURCE = SalesTicket
MODEL_FINAL = SalesInvoice
url_reverse = 'CDNX_invoicing_invoicesaless_list'
# type_doc
msg_error_relation = _("Hay lineas asignadas a facturas")
msg_error_not_found = _('Sales ticket not found')
... | context = {}
if list_lines:
new_list_lines = SalesLines.objects.filter(
pk__in=[int(x) for x in list_lines]
).exclude(
invoice__isnull=T... | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales.py#L2450-L2486 | null | class SalesLines(CodenerixModel):
basket = models.ForeignKey(SalesBasket, related_name='lines_sales', verbose_name=_("Basket"), on_delete=models.CASCADE)
tax_basket_fk = models.ForeignKey(TypeTax, related_name='lines_sales_basket', verbose_name=_("Tax Basket"), on_delete=models.CASCADE)
order = models.Forei... |
codenerix/django-codenerix-invoicing | codenerix_invoicing/views_purchases.py | LineAlbaranCreate.form_valid | python | def form_valid(self, form):
if self.__pk:
obj = PurchasesAlbaran.objects.get(pk=self.__pk)
self.request.albaran = obj
form.instance.albaran = obj
form.instance.validator_user = self.request.user
raise Exception("revisar StorageBatch")
# comprueba si... | batch = StorageBatch.objects.filter(pk=form.data['batch']).first()
if not batch:
errors = form._errors.setdefault("batch", ErrorList())
errors.append(_("Batch invalid"))
return super(LineAlbaranCreate, self).form_invalid(form) | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/views_purchases.py#L669-L780 | null | class LineAlbaranCreate(GenLineAlbaranUrl, GenCreate):
model = PurchasesLineAlbaran
form_class = LineAlbaranForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
self.__pk = kwargs.get('pk', None)
return super(LineAlbaranCreate, self).dispatch(*args, **kwargs)
|
codenerix/django-codenerix-invoicing | codenerix_invoicing/views_purchases.py | LineAlbaranUpdate.get_form | python | def get_form(self, form_class=None):
form = super(LineAlbaranUpdate, self).get_form(form_class)
raise Exception("Cambiar ProductStock por ProductUnique")
return form | ps = ProductStock.objects.filter(line_albaran=self.object).first()
if ps:
# initial field
form.fields['storage'].initial = ps.batch.zone.storage
form.fields['zone'].initial = ps.batch.zone
form.fields['batch'].initial = ps.batch | train | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/views_purchases.py#L796-L808 | null | class LineAlbaranUpdate(GenLineAlbaranUrl, GenUpdate):
model = PurchasesLineAlbaran
form_class = LineAlbaranForm
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
self.__pk = kwargs.get('pk', None)
return super(LineAlbaranUpdate, self).dispatch(*args, **kwargs)
... |
xtream1101/cutil | cutil/custom_terminal.py | CustomTerminal.cprint | python | def cprint(self, cstr):
cstr = str(cstr) # Force it to be a string
cstr_len = len(cstr)
prev_cstr_len = len(self._prev_cstr)
num_spaces = 0
if cstr_len < prev_cstr_len:
num_spaces = abs(prev_cstr_len - cstr_len)
try:
print(cstr + " " * num_spaces,... | Clear line, then reprint on same line
:param cstr: string to print on current line | train | https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/custom_terminal.py#L30-L46 | null | class CustomTerminal:
def __init__(self):
self._prev_cstr = ''
self._bprint_disable = False
self._proxy_list = []
self._current_proxy = None
self._custom_proxy = False
self._apikey_list = []
self._current_apikey = None
# Block print display messages... |
xtream1101/cutil | cutil/database.py | _check_values | python | def _check_values(in_values):
out_values = []
for value in in_values:
# if isinstance(value, (dict, list)):
# out_values.append(json.dumps(value))
# else:
out_values.append(value)
return tuple(out_values) | Check if values need to be converted before they get mogrify'd | train | https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/database.py#L10-L20 | null | import sys
import copy
import json
import logging
from contextlib import contextmanager
logger = logging.getLogger(__name__)
class Database:
def __init__(self, db_config, table_raw=None, max_connections=10):
from psycopg2.pool import ThreadedConnectionPool
self.table_raw = table_raw
tr... |
xtream1101/cutil | cutil/database.py | Database.insert | python | def insert(self, table, data_list, return_cols='id'):
data_list = copy.deepcopy(data_list) # Create deepcopy so the original list does not get modified
# Make sure that `data_list` is a list
if not isinstance(data_list, list):
data_list = [data_list]
# Make sure data_list ha... | Create a bulk insert statement which is much faster (~2x in tests with 10k & 100k rows and n cols)
for inserting data then executemany()
TODO: Is there a limit of length the query can be? If so handle it. | train | https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/database.py#L61-L114 | [
"def _check_values(in_values):\n \"\"\" Check if values need to be converted before they get mogrify'd\n \"\"\"\n out_values = []\n for value in in_values:\n # if isinstance(value, (dict, list)):\n # out_values.append(json.dumps(value))\n # else:\n ... | class Database:
def __init__(self, db_config, table_raw=None, max_connections=10):
from psycopg2.pool import ThreadedConnectionPool
self.table_raw = table_raw
try:
# Set default port is port is not passed
if 'db_port' not in db_config:
db_config['db_... |
xtream1101/cutil | cutil/database.py | Database.upsert | python | def upsert(self, table, data_list, on_conflict_fields, on_conflict_action='update',
update_fields=None, return_cols='id'):
data_list = copy.deepcopy(data_list) # Create deepcopy so the original list does not get modified
# Make sure that `data_list` is a list
if not isinstance(da... | Create a bulk upsert statement which is much faster (~6x in tests with 10k & 100k rows and n cols)
for upserting data then executemany()
TODO: Is there a limit of length the query can be? If so handle it. | train | https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/database.py#L116-L211 | [
"def _check_values(in_values):\n \"\"\" Check if values need to be converted before they get mogrify'd\n \"\"\"\n out_values = []\n for value in in_values:\n # if isinstance(value, (dict, list)):\n # out_values.append(json.dumps(value))\n # else:\n ... | class Database:
def __init__(self, db_config, table_raw=None, max_connections=10):
from psycopg2.pool import ThreadedConnectionPool
self.table_raw = table_raw
try:
# Set default port is port is not passed
if 'db_port' not in db_config:
db_config['db_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.