signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def pdflookup(pdf, allresults, outformat, startpage=None):
|
txt = convert_pdf_to_txt(pdf, startpage)<EOL>txt = re.sub("<STR_LIT>", "<STR_LIT:U+0020>", txt)<EOL>words = txt.strip().split()[:<NUM_LIT:20>]<EOL>gsquery = "<STR_LIT:U+0020>".join(words)<EOL>bibtexlist = query(gsquery, outformat, allresults)<EOL>return bibtexlist<EOL>
|
Look a pdf up on google scholar and return bibtex items.
Paramters
---------
pdf : str
path to the pdf file
allresults : bool
return all results or only the first (i.e. best one)
outformat : int
the output format of the citations
startpage : int
first page to start reading from
Returns
-------
List[str]
the list with citations
|
f517:m3
|
def _get_bib_element(bibitem, element):
|
lst = [i.strip() for i in bibitem.split("<STR_LIT:\n>")]<EOL>for i in lst:<EOL><INDENT>if i.startswith(element):<EOL><INDENT>value = i.split("<STR_LIT:=>", <NUM_LIT:1>)[-<NUM_LIT:1>]<EOL>value = value.strip()<EOL>while value.endswith('<STR_LIT:U+002C>'):<EOL><INDENT>value = value[:-<NUM_LIT:1>]<EOL><DEDENT>while value.startswith('<STR_LIT:{>') or value.startswith('<STR_LIT:">'):<EOL><INDENT>value = value[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL><DEDENT>return value<EOL><DEDENT><DEDENT>return None<EOL>
|
Return element from bibitem or None.
Paramteters
-----------
bibitem :
element :
Returns
-------
|
f517:m4
|
def rename_file(pdf, bibitem):
|
year = _get_bib_element(bibitem, "<STR_LIT>")<EOL>author = _get_bib_element(bibitem, "<STR_LIT>")<EOL>if author:<EOL><INDENT>author = author.split("<STR_LIT:U+002C>")[<NUM_LIT:0>]<EOL><DEDENT>title = _get_bib_element(bibitem, "<STR_LIT:title>")<EOL>l = [i for i in (year, author, title) if i]<EOL>filename = "<STR_LIT:->".join(l) + "<STR_LIT>"<EOL>newfile = pdf.replace(os.path.basename(pdf), filename)<EOL>logger.info('<STR_LIT>'.format(in_=pdf, out=newfile))<EOL>os.rename(pdf, newfile)<EOL>
|
Attempt to rename pdf according to bibitem.
|
f517:m5
|
def loads(data):
|
data += "<STR_LIT>" <EOL>match_dest = RE_HEADER.search(data)<EOL>dest_name = match_dest.group(<NUM_LIT:1>)<EOL>dest_ip = match_dest.group(<NUM_LIT:2>)<EOL>traceroute = Traceroute(dest_name, dest_ip)<EOL>matches_hop = RE_HOP.findall(data)<EOL>for match_hop in matches_hop:<EOL><INDENT>idx = int(match_hop[<NUM_LIT:0>])<EOL>if match_hop[<NUM_LIT:1>]:<EOL><INDENT>asn = int(match_hop[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>asn = None<EOL><DEDENT>hop = Hop(idx, asn)<EOL>probes_data = match_hop[<NUM_LIT:2>].split()<EOL>probes_data = filter(lambda s: s.lower() != '<STR_LIT>', probes_data)<EOL>i = <NUM_LIT:0><EOL>while i < len(probes_data):<EOL><INDENT>name = None<EOL>ip = None<EOL>rtt = None<EOL>anno = '<STR_LIT>'<EOL>if RE_PROBE_RTT.match(probes_data[i]):<EOL><INDENT>rtt = float(probes_data[i])<EOL>i += <NUM_LIT:1><EOL><DEDENT>elif RE_PROBE_NAME.match(probes_data[i]):<EOL><INDENT>name = probes_data[i]<EOL>ip = probes_data[i+<NUM_LIT:1>].strip('<STR_LIT>')<EOL>rtt = float(probes_data[i+<NUM_LIT:2>])<EOL>i += <NUM_LIT:3><EOL><DEDENT>elif RE_PROBE_TIMEOUT.match(probes_data[i]):<EOL><INDENT>rtt = None<EOL>i += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>ext = "<STR_LIT>" % (i, probes_data, name, ip, rtt, anno)<EOL>raise ParseError("<STR_LIT>" % ext)<EOL><DEDENT>try:<EOL><INDENT>if RE_PROBE_ANNOTATION.match(probes_data[i]):<EOL><INDENT>anno = probes_data[i]<EOL>i += <NUM_LIT:1><EOL><DEDENT><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT>probe = Probe(name, ip, rtt, anno)<EOL>hop.add_probe(probe)<EOL><DEDENT>traceroute.add_hop(hop)<EOL><DEDENT>return traceroute<EOL>
|
Parser entry point. Parses the output of a traceroute execution
|
f522:m0
|
def add_probe(self, probe):
|
if self.probes:<EOL><INDENT>probe_last = self.probes[-<NUM_LIT:1>]<EOL>if not probe.ip:<EOL><INDENT>probe.ip = probe_last.ip<EOL>probe.name = probe_last.name<EOL><DEDENT><DEDENT>self.probes.append(probe)<EOL>
|
Adds a Probe instance to this hop's results.
|
f522:c1:m1
|
@property<EOL><INDENT>def page_url(self) -> str:<DEDENT>
|
url = self.attributes['<STR_LIT>']<EOL>assert isinstance(url, str)<EOL>return url<EOL>
|
(:class:`str`) The canonical url of the page.
|
f524:c0:m1
|
@property<EOL><INDENT>def image_url(self) -> Optional[str]:<DEDENT>
|
images = self.attributes.get('<STR_LIT>', [])<EOL>if images and isinstance(images, collections.abc.Sequence):<EOL><INDENT>return images[<NUM_LIT:0>]['<STR_LIT:url>']<EOL><DEDENT>return None<EOL>
|
r"""(:class:`~typing.Optional`\ [:class:`str`]) The image url.
It may be :const:`None` if it's not an image.
|
f524:c0:m2
|
@property<EOL><INDENT>def image_mimetype(self) -> Optional[str]:<DEDENT>
|
images = self.attributes.get('<STR_LIT>', [])<EOL>if images and isinstance(images, collections.abc.Sequence):<EOL><INDENT>return images[<NUM_LIT:0>]['<STR_LIT>']<EOL><DEDENT>return None<EOL>
|
r"""(:class:`~typing.Optional`\ [:class:`str`]) The MIME type of
the image. It may be :const:`None` if it's not an image.
|
f524:c0:m3
|
@property<EOL><INDENT>def image_resolution(self) -> Optional[Tuple[int, int]]:<DEDENT>
|
images = self.attributes.get('<STR_LIT>', [])<EOL>if images and isinstance(images, collections.abc.Sequence):<EOL><INDENT>img = images[<NUM_LIT:0>]<EOL>return img['<STR_LIT:width>'], img['<STR_LIT>']<EOL><DEDENT>return None<EOL>
|
r"""(:class:`~typing.Optional`\ [:class:`~typing.Tuple`\ [:class:`int`,
:class:`int`]]) The (width, height) pair of the image.
It may be :const:`None` if it's not an image.
|
f524:c0:m4
|
@property<EOL><INDENT>def image_size(self) -> Optional[int]:<DEDENT>
|
images = self.attributes.get('<STR_LIT>', [])<EOL>if images and isinstance(images, collections.abc.Sequence):<EOL><INDENT>return images[<NUM_LIT:0>]['<STR_LIT:size>']<EOL><DEDENT>return None<EOL>
|
r"""(:class:`~typing.Optional`\ [:class:`int`]) The size of the image
in bytes. It may be :const:`None` if it's not an image.
|
f524:c0:m5
|
def get(self, key: CacheKey) -> Optional[CacheValue]:
|
raise NotImplementedError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(CachePolicy)<EOL>)<EOL>
|
r"""Look up a cached value by its ``key``.
:param key: The key string to look up a cached value.
:type key: :const:`CacheKey`
:return: The cached value if it exists.
:const:`None` if there's no such ``key``.
:rtype: :class:`~typing.Optional`\ [:const:`CacheValue`]
|
f525:c0:m0
|
def set(self, key: CacheKey, value: Optional[CacheValue]) -> None:
|
raise NotImplementedError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(CachePolicy)<EOL>)<EOL>
|
r"""Create or update a cache.
:param key: A key string to create or update.
:type key: :const:`CacheKey`
:param value: A value to cache. :const:`None` to remove cache.
:type value: :class:`~typing.Optional`\ [:const:`CacheValue`]
|
f525:c0:m1
|
def getlist(self, key: '<STR_LIT>') -> Sequence[object]:
|
if not (isinstance(key, type(self)) and<EOL>key.type is EntityType.property):<EOL><INDENT>return []<EOL><DEDENT>claims_map = self.attributes.get('<STR_LIT>') or {}<EOL>assert isinstance(claims_map, collections.abc.Mapping)<EOL>claims = claims_map.get(key.id, [])<EOL>claims.sort(key=lambda claim: claim['<STR_LIT>'], <EOL>reverse=True)<EOL>logger = logging.getLogger(__name__ + '<STR_LIT>')<EOL>if logger.isEnabledFor(logging.DEBUG):<EOL><INDENT>logger.debug('<STR_LIT>',<EOL>__import__('<STR_LIT>').pformat(claims))<EOL><DEDENT>decode = self.client.decode_datavalue<EOL>return [decode(snak['<STR_LIT>'], snak['<STR_LIT>'])<EOL>for snak in (claim['<STR_LIT>'] for claim in claims)]<EOL>
|
r"""Return all values associated to the given ``key`` property
in sequence.
:param key: The property entity.
:type key: :class:`Entity`
:return: A sequence of all values associated to the given ``key``
property. It can be empty if nothing is associated to
the property.
:rtype: :class:`~typing.Sequence`\ [:class:`object`]
|
f526:c2:m6
|
def lists(self) -> Sequence[Tuple['<STR_LIT>', Sequence[object]]]:
|
return list(self.iterlists())<EOL>
|
Similar to :meth:`items()` except the returning pairs have
each list of values instead of each single value.
:return: The pairs of (key, values) where values is a sequence.
:rtype: :class:`~typing.Sequence`\\ [:class:`~typing.Tuple`\\ \
[:class:`Entity`, :class:`~typing.Sequence`\\ [:class:`object`]]]
|
f526:c2:m8
|
@property<EOL><INDENT>def type(self) -> EntityType:<DEDENT>
|
if self.data is None:<EOL><INDENT>guessed_type = self.client.guess_entity_type(self.id)<EOL>if guessed_type is not None:<EOL><INDENT>return guessed_type<EOL><DEDENT><DEDENT>return EntityType(self.attributes['<STR_LIT:type>'])<EOL>
|
(:class:`EntityType`) The type of entity, :attr:`~EntityType.item`
or :attr:`~EntityType.property`.
.. versionadded:: 0.2.0
|
f526:c2:m11
|
def normalize_locale_code(locale: Union[Locale, str]) -> str:
|
if not isinstance(locale, Locale):<EOL><INDENT>locale = Locale.parse(locale.replace('<STR_LIT:->', '<STR_LIT:_>'))<EOL><DEDENT>return str(locale)<EOL>
|
Determine the normalized locale code string.
>>> normalize_locale_code('ko-kr')
'ko_KR'
>>> normalize_locale_code('zh_TW')
'zh_Hant_TW'
>>> normalize_locale_code(Locale.parse('en_US'))
'en_US'
|
f527:m0
|
@property<EOL><INDENT>def locale(self) -> Locale:<DEDENT>
|
return Locale.parse(self.locale_code)<EOL>
|
(:class:`~babel.core.Locale`) The language (locale) that the text is
written in.
|
f527:c1:m1
|
@property<EOL><INDENT>def datavalue(self):<DEDENT>
|
return self.args[<NUM_LIT:1>]<EOL>
|
The datavalue which caused the decoding error.
|
f528:c0:m1
|
def get(self, entity_id: EntityId, load: bool = False) -> Entity:
|
try:<EOL><INDENT>entity = self.identity_map[entity_id]<EOL><DEDENT>except KeyError:<EOL><INDENT>entity = Entity(entity_id, self)<EOL>self.identity_map[entity_id] = entity<EOL><DEDENT>if load:<EOL><INDENT>entity.load()<EOL><DEDENT>return entity<EOL>
|
Get a Wikidata entity by its :class:`~.entity.EntityId`.
:param entity_id: The :attr:`~.entity.Entity.id` of
the :class:`~.entity.Entity` to find.
:type eneity_id: :class:`~.entity.EntityId`
:param load: Eager loading on :const:`True`.
Lazy loading (:const:`False`) by default.
:type load: :class:`bool`
:return: The found entity.
:rtype: :class:`~.entity.Entity`
.. versionadded:: 0.3.0
The ``load`` option.
|
f529:c0:m1
|
def guess_entity_type(self, entity_id: EntityId) -> Optional[EntityType]:
|
if not self.entity_type_guess:<EOL><INDENT>return None<EOL><DEDENT>if entity_id[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>return EntityType.item<EOL><DEDENT>elif entity_id[<NUM_LIT:0>] == '<STR_LIT:P>':<EOL><INDENT>return EntityType.property<EOL><DEDENT>return None<EOL>
|
r"""Guess :class:`~.entity.EntityType` from the given
:class:`~.entity.EntityId`. It could return :const:`None` when it
fails to guess.
.. note::
It always fails to guess when :attr:`entity_type_guess`
is configued to :const:`False`.
:return: The guessed :class:`~.entity.EntityId`, or :const:`None`
if it fails to guess.
:rtype: :class:`~typing.Optional`\ [:class:`~.entity.EntityType`]
.. versionadded:: 0.2.0
|
f529:c0:m2
|
def decode_datavalue(self,<EOL>datatype: str,<EOL>datavalue: Mapping[str, object]) -> object:
|
decode = cast(Callable[[Client, str, Mapping[str, object]], object],<EOL>self.datavalue_decoder)<EOL>return decode(self, datatype, datavalue)<EOL>
|
Decode the given ``datavalue`` using the configured
:attr:`datavalue_decoder`.
.. versionadded:: 0.3.0
|
f529:c0:m3
|
def add(self, obj):
|
obj.controller = self.controller<EOL>track = self.tracks.get(obj.name)<EOL>if track:<EOL><INDENT>if track == obj:<EOL><INDENT>return<EOL><DEDENT>obj.keys = track.keys<EOL>obj.controller = track.controller<EOL>self.tracks[track.name] = obj<EOL>self.track_index[self.track_index.index(track)] = obj<EOL><DEDENT>else:<EOL><INDENT>obj.controller = self.controller<EOL>self.tracks[obj.name] = obj<EOL>self.track_index.append(obj)<EOL><DEDENT>
|
Add pre-created tracks.
If the tracks are already created, we hijack the data.
This way the pointer to the pre-created tracks are still valid.
|
f546:c0:m4
|
def row_value(self, row):
|
irow = int(row)<EOL>i = self._get_key_index(irow)<EOL>if i == -<NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0.0><EOL><DEDENT>if i == len(self.keys) - <NUM_LIT:1>:<EOL><INDENT>return self.keys[-<NUM_LIT:1>].value<EOL><DEDENT>return TrackKey.interpolate(self.keys[i], self.keys[i + <NUM_LIT:1>], row)<EOL>
|
Get the tracks value at row
|
f546:c1:m2
|
def add_or_update(self, row, value, kind):
|
i = bisect.bisect_left(self.keys, row)<EOL>if i < len(self.keys) and self.keys[i].row == row:<EOL><INDENT>self.keys[i].update(value, kind)<EOL><DEDENT>else:<EOL><INDENT>self.keys.insert(i, TrackKey(row, value, kind))<EOL><DEDENT>
|
Add or update a track value
|
f546:c1:m3
|
def delete(self, row):
|
i = self._get_key_index(row)<EOL>del self.keys[i]<EOL>
|
Delete a track value
|
f546:c1:m4
|
def _get_key_index(self, row):
|
<EOL>if len(self.keys) == <NUM_LIT:0>:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>if row < self.keys[<NUM_LIT:0>].row:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>index = bisect.bisect_left(self.keys, row)<EOL>if index < len(self.keys):<EOL><INDENT>if row < self.keys[index].row:<EOL><INDENT>return index - <NUM_LIT:1><EOL><DEDENT>return index<EOL><DEDENT>return len(self.keys) - <NUM_LIT:1><EOL>
|
Get the key that should be used as the first interpolation value
|
f546:c1:m5
|
@staticmethod<EOL><INDENT>def filename(name):<DEDENT>
|
return "<STR_LIT>".format(name.replace('<STR_LIT::>', '<STR_LIT:#>'), '<STR_LIT>')<EOL>
|
Create a valid file name from track name
|
f546:c1:m6
|
@staticmethod<EOL><INDENT>def trackname(name):<DEDENT>
|
return name.replace('<STR_LIT:#>', '<STR_LIT::>').replace('<STR_LIT>', '<STR_LIT>')<EOL>
|
Create track name from file name
|
f546:c1:m7
|
def load(self, filepath):
|
with open(filepath, '<STR_LIT:rb>') as fd:<EOL><INDENT>num_keys = struct.unpack("<STR_LIT>", fd.read(<NUM_LIT:4>))[<NUM_LIT:0>]<EOL>for i in range(num_keys):<EOL><INDENT>row, value, kind = struct.unpack('<STR_LIT>', fd.read(<NUM_LIT:9>))<EOL>self.keys.append(TrackKey(row, value, kind))<EOL><DEDENT><DEDENT>
|
Load the track file
|
f546:c1:m8
|
def save(self, path):
|
name = Track.filename(self.name)<EOL>with open(os.path.join(path, name), '<STR_LIT:wb>') as fd:<EOL><INDENT>fd.write(struct.pack('<STR_LIT>', len(self.keys)))<EOL>for k in self.keys:<EOL><INDENT>fd.write(struct.pack('<STR_LIT>', k.row, k.value, k.kind))<EOL><DEDENT><DEDENT>
|
Save the track
|
f546:c1:m9
|
def __init__(self, track_path, controller=None, tracks=None):
|
logger.info("<STR_LIT>")<EOL>self.controller = controller<EOL>self.tracks = tracks<EOL>self.path = track_path<EOL>self.controller.connector = self<EOL>self.tracks.connector = self<EOL>if self.path is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not os.path.exists(self.path):<EOL><INDENT>raise ValueError("<STR_LIT>".format(self.path))<EOL><DEDENT>logger.info("<STR_LIT>", self.path)<EOL>for f in os.listdir(self.path):<EOL><INDENT>if not f.endswith("<STR_LIT>"):<EOL><INDENT>continue<EOL><DEDENT>name = Track.trackname(f)<EOL>logger.info("<STR_LIT>", name)<EOL>t = self.tracks.get_or_create(name)<EOL>t.load(os.path.join(self.path, f))<EOL><DEDENT>
|
Load binary track files
:param path: Path to track directory
:param controller: The controller
:param tracks: Track container
|
f547:c0:m0
|
def update(self):
|
while self.read_command():<EOL><INDENT>pass<EOL><DEDENT>
|
Process all queued incoming commands
|
f548:c1:m4
|
def read_command(self):
|
<EOL>comm = self.reader.byte(blocking=False)<EOL>if comm is None:<EOL><INDENT>return False<EOL><DEDENT>cmds = {<EOL>SET_KEY: self.handle_set_key,<EOL>DELETE_KEY: self.handle_delete_key,<EOL>SET_ROW: self.handle_set_row,<EOL>PAUSE: self.handle_pause,<EOL>SAVE_TRACKS: self.handle_save_tracks<EOL>}<EOL>func = cmds.get(comm)<EOL>if func:<EOL><INDENT>func()<EOL><DEDENT>else:<EOL><INDENT>logger.error("<STR_LIT>", comm)<EOL><DEDENT>return True<EOL>
|
Attempt to read the next command from the editor/server
:return: boolean. Did we actually read a command?
|
f548:c1:m6
|
def handle_set_key(self):
|
track_id = self.reader.int()<EOL>row = self.reader.int()<EOL>value = self.reader.float()<EOL>kind = self.reader.byte()<EOL>logger.info("<STR_LIT>", track_id, row, value, kind)<EOL>track = self.tracks.get_by_id(track_id)<EOL>track.add_or_update(row, value, kind)<EOL>
|
Read incoming key from server
|
f548:c1:m7
|
def handle_delete_key(self):
|
track_id = self.reader.int()<EOL>row = self.reader.int()<EOL>logger.info("<STR_LIT>", track_id, row)<EOL>track = self.tracks.get_by_id(track_id)<EOL>track.delete(row)<EOL>
|
Read incoming delete key event from server
|
f548:c1:m8
|
def handle_set_row(self):
|
row = self.reader.int()<EOL>logger.info("<STR_LIT>", row)<EOL>self.controller.row = row<EOL>
|
Read incoming row change from server
|
f548:c1:m9
|
def handle_pause(self):
|
flag = self.reader.byte()<EOL>if flag > <NUM_LIT:0>:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>self.controller.playing = False<EOL><DEDENT>else:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>self.controller.playing = True<EOL><DEDENT>
|
Read pause signal from server
|
f548:c1:m10
|
def __init__(self, controller, track_path=None, log_level=logging.ERROR):
|
<EOL>sh = logging.StreamHandler()<EOL>sh.setLevel(log_level)<EOL>formatter = logging.Formatter('<STR_LIT>')<EOL>sh.setFormatter(formatter)<EOL>logger.addHandler(sh)<EOL>logger.setLevel(log_level)<EOL>self.controller = controller<EOL>self.connector = None<EOL>self.tracks = TrackContainer(track_path)<EOL>self.tracks.controller = self.controller<EOL>
|
Create rocket instance without a connector
|
f552:c0:m0
|
@staticmethod<EOL><INDENT>def from_files(controller, track_path, log_level=logging.ERROR):<DEDENT>
|
rocket = Rocket(controller, track_path=track_path, log_level=log_level)<EOL>rocket.connector = FilesConnector(track_path,<EOL>controller=controller,<EOL>tracks=rocket.tracks)<EOL>return rocket<EOL>
|
Create rocket instance using project file connector
|
f552:c0:m1
|
@staticmethod<EOL><INDENT>def from_project_file(controller, project_file, track_path=None, log_level=logging.ERROR):<DEDENT>
|
rocket = Rocket(controller, track_path=track_path, log_level=log_level)<EOL>rocket.connector = ProjectFileConnector(project_file,<EOL>controller=controller,<EOL>tracks=rocket.tracks)<EOL>return rocket<EOL>
|
Create rocket instance using project file connector
|
f552:c0:m2
|
@staticmethod<EOL><INDENT>def from_socket(controller, host=None, port=None, track_path=None, log_level=logging.ERROR):<DEDENT>
|
rocket = Rocket(controller, track_path=track_path, log_level=log_level)<EOL>rocket.connector = SocketConnector(controller=controller,<EOL>tracks=rocket.tracks,<EOL>host=host,<EOL>port=port)<EOL>return rocket<EOL>
|
Create rocket instance using socket connector
|
f552:c0:m3
|
def value(self, name):
|
return self.tracks.get(name).row_value(self.controller.row)<EOL>
|
get value of a track at the current time
|
f552:c0:m8
|
def acceptNavigationRequest(self, url, kind, is_main_frame):
|
ready_url = url.toEncoded().data().decode()<EOL>is_clicked = kind == self.NavigationTypeLinkClicked<EOL>if is_clicked and self.root_url not in ready_url:<EOL><INDENT>QtGui.QDesktopServices.openUrl(url)<EOL>return False<EOL><DEDENT>return super(WebPage, self).acceptNavigationRequest(url, kind, is_main_frame)<EOL>
|
Open external links in browser and internal links in the webview
|
f555:c1:m2
|
def transactional(*, adapter=None, retries=<NUM_LIT:3>, propagation=Transaction.Propagation.Nested):
|
def decorator(fn):<EOL><INDENT>@wraps(fn)<EOL>def inner(*args, **kwargs):<EOL><INDENT>nonlocal adapter<EOL>adapter = adapter or get_adapter()<EOL>attempts, cause = <NUM_LIT:0>, None<EOL>while attempts <= retries:<EOL><INDENT>attempts += <NUM_LIT:1><EOL>transaction = adapter.transaction(propagation)<EOL>try:<EOL><INDENT>transaction.begin()<EOL>res = fn(*args, **kwargs)<EOL>transaction.commit()<EOL>return res<EOL><DEDENT>except TransactionFailed as e:<EOL><INDENT>cause = e<EOL>continue<EOL><DEDENT>except Exception as e:<EOL><INDENT>transaction.rollback()<EOL>raise e<EOL><DEDENT>finally:<EOL><INDENT>transaction.end()<EOL><DEDENT><DEDENT>raise RetriesExceeded(cause)<EOL><DEDENT>return inner<EOL><DEDENT>return decorator<EOL>
|
Decorates functions so that all of their operations (except for
queries) run inside a Datastore transaction.
Parameters:
adapter(Adapter, optional): The Adapter to use when running the
transaction. Defaults to the current adapter.
retries(int, optional): The number of times to retry the
transaction if it couldn't be committed.
propagation(Transaction.Propagation, optional): The propagation
strategy to use. By default, transactions are nested, but you
can force certain transactions to always run independently.
Raises:
anom.RetriesExceeded: When the decorator runbs out of retries
while trying to commit the transaction.
Returns:
callable: The decorated function.
|
f576:m0
|
def begin(self):
|
raise NotImplementedError<EOL>
|
Start this transaction.
|
f576:c0:m0
|
def commit(self):
|
raise NotImplementedError<EOL>
|
Commit this Transaction to Datastore.
|
f576:c0:m1
|
def rollback(self):
|
raise NotImplementedError<EOL>
|
Roll this Transaction back.
|
f576:c0:m2
|
def end(self):
|
raise NotImplementedError<EOL>
|
Clean up this Transaction object.
|
f576:c0:m3
|
def get_adapter():
|
if _adapter is None:<EOL><INDENT>from .adapters import DatastoreAdapter<EOL>return set_adapter(DatastoreAdapter())<EOL><DEDENT>return _adapter<EOL>
|
Get the current global Adapter instance.
Returns:
Adapter: The global adapter. If no global adapter was set, this
instantiates a :class:`adapters.DatastoreAdapter` and makes it
the default.
|
f577:m0
|
def set_adapter(adapter):
|
global _adapter<EOL>_adapter = adapter<EOL>return _adapter<EOL>
|
Set the global Adapter instance.
Parameters:
adapter(Adapter): The instance to set as the global adapter.
Model-specific adapters will not be replaced.
Returns:
Adapter: The input adapter.
|
f577:m1
|
def delete_multi(self, keys):
|
raise NotImplementedError<EOL>
|
Delete a list of entities from the Datastore by their
respective keys.
Parameters:
keys(list[anom.Key]): A list of datastore Keys to delete.
|
f577:c2:m0
|
def get_multi(self, keys):
|
raise NotImplementedError<EOL>
|
Get multiple entities from the Datastore by their
respective keys.
Parameters:
keys(list[anom.Key]): A list of datastore Keys to get.
Returns:
list[dict]: A list of dictionaries of data that can be loaded
into individual Models. Entries for Keys that cannot be
found are going to be ``None``.
|
f577:c2:m1
|
def put_multi(self, requests):
|
raise NotImplementedError<EOL>
|
Store multiple entities into the Datastore.
Parameters:
requests(list[PutRequest]): A list of datastore requets to
persist a set of entities.
Returns:
list[anom.Key]: The list of full keys for each stored
entity.
|
f577:c2:m2
|
def query(self, query, options):
|
raise NotImplementedError<EOL>
|
Run a query against the datastore.
Parameters:
query(Query): The query to run.
options(QueryOptions): Options that determine how the data
should be fetched.
Returns:
QueryResponse: The query response from Datastore.
|
f577:c2:m3
|
def transaction(self, propagation):
|
raise NotImplementedError<EOL>
|
Create a new Transaction object.
Parameters:
propagation(Transaction.Propagation): How the new
transaction should be propagated with regards to any
previously-created transactions.
Returns:
Transaction: The transaction.
|
f577:c2:m4
|
@property<EOL><INDENT>def in_transaction(self):<DEDENT>
|
raise NotImplementedError<EOL>
|
bool: True if the adapter is currently in a Transaction.
|
f577:c2:m5
|
@property<EOL><INDENT>def current_transaction(self):<DEDENT>
|
raise NotImplementedError<EOL>
|
Transaction: The current Transaction or None.
|
f577:c2:m6
|
def classname(ob):
|
return type(ob).__name__<EOL>
|
Returns the name of ob's class.
|
f578:m0
|
def lookup_model_by_kind(kind):
|
model = _known_models.get(kind)<EOL>if model is None:<EOL><INDENT>raise RuntimeError(f"<STR_LIT>")<EOL><DEDENT>return model<EOL>
|
Look up the model instance for a given Datastore kind.
Parameters:
kind(str)
Raises:
RuntimeError: If a model for the given kind has not been
defined.
Returns:
model: The model class.
|
f578:m1
|
def delete_multi(keys):
|
if not keys:<EOL><INDENT>return<EOL><DEDENT>adapter = None<EOL>for key in keys:<EOL><INDENT>if key.is_partial:<EOL><INDENT>raise RuntimeError(f"<STR_LIT>")<EOL><DEDENT>model = lookup_model_by_kind(key.kind)<EOL>if adapter is None:<EOL><INDENT>adapter = model._adapter<EOL><DEDENT>model.pre_delete_hook(key)<EOL><DEDENT>adapter.delete_multi(keys)<EOL>for key in keys:<EOL><INDENT>model = _known_models[key.kind]<EOL>model.post_delete_hook(key)<EOL><DEDENT>
|
Delete a set of entitites from Datastore by their
respective keys.
Note:
This uses the adapter that is tied to the first model in the list.
If the keys have disparate adapters this function may behave in
unexpected ways.
Warning:
You must pass a **list** and not a generator or some other kind
of iterable to this function as it has to iterate over the list
of keys multiple times.
Parameters:
keys(list[anom.Key]): The list of keys whose entities to delete.
Raises:
RuntimeError: If the given set of keys have models that use
a disparate set of adapters or if any of the keys are
partial.
|
f578:m2
|
def get_multi(keys):
|
if not keys:<EOL><INDENT>return []<EOL><DEDENT>adapter = None<EOL>for key in keys:<EOL><INDENT>if key.is_partial:<EOL><INDENT>raise RuntimeError(f"<STR_LIT>")<EOL><DEDENT>model = lookup_model_by_kind(key.kind)<EOL>if adapter is None:<EOL><INDENT>adapter = model._adapter<EOL><DEDENT>model.pre_get_hook(key)<EOL><DEDENT>entities_data, entities = adapter.get_multi(keys), []<EOL>for key, entity_data in zip(keys, entities_data):<EOL><INDENT>if entity_data is None:<EOL><INDENT>entities.append(None)<EOL>continue<EOL><DEDENT>model = _known_models[key.kind]<EOL>entity = model._load(key, entity_data)<EOL>entities.append(entity)<EOL>entity.post_get_hook()<EOL><DEDENT>return entities<EOL>
|
Get a set of entities from Datastore by their respective keys.
Note:
This uses the adapter that is tied to the first model in the
list. If the keys have disparate adapters this function may
behave in unexpected ways.
Warning:
You must pass a **list** and not a generator or some other kind
of iterable to this function as it has to iterate over the list
of keys multiple times.
Parameters:
keys(list[anom.Key]): The list of keys whose entities to get.
Raises:
RuntimeError: If the given set of keys have models that use
a disparate set of adapters or if any of the keys are
partial.
Returns:
list[Model]: Entities that do not exist are going to be None
in the result list. The order of results matches the order
of the input keys.
|
f578:m3
|
def put_multi(entities):
|
if not entities:<EOL><INDENT>return []<EOL><DEDENT>adapter, requests = None, []<EOL>for entity in entities:<EOL><INDENT>if adapter is None:<EOL><INDENT>adapter = entity._adapter<EOL><DEDENT>entity.pre_put_hook()<EOL>requests.append(PutRequest(entity.key, entity.unindexed_properties, entity))<EOL><DEDENT>keys = adapter.put_multi(requests)<EOL>for key, entity in zip(keys, entities):<EOL><INDENT>entity.key = key<EOL>entity.post_put_hook()<EOL><DEDENT>return entities<EOL>
|
Persist a set of entities to Datastore.
Note:
This uses the adapter that is tied to the first Entity in the
list. If the entities have disparate adapters this function may
behave in unexpected ways.
Warning:
You must pass a **list** and not a generator or some other kind
of iterable to this function as it has to iterate over the list
of entities multiple times.
Parameters:
entities(list[Model]): The list of entities to persist.
Raises:
RuntimeError: If the given set of models use a disparate set of
adapters.
Returns:
list[Model]: The list of persisted entitites.
|
f578:m4
|
@classmethod<EOL><INDENT>def from_path(cls, *path, namespace=None):<DEDENT>
|
parent = None<EOL>for i in range(<NUM_LIT:0>, len(path), <NUM_LIT:2>):<EOL><INDENT>parent = cls(*path[i:i + <NUM_LIT:2>], parent=parent, namespace=namespace)<EOL><DEDENT>return parent<EOL>
|
Build up a Datastore key from a path.
Parameters:
\*path(tuple[str or int]): The path segments.
namespace(str): An optional namespace for the key. This is
applied to each key in the tree.
Returns:
anom.Key: The Datastore represented by the given path.
|
f578:c1:m1
|
@property<EOL><INDENT>def path(self):<DEDENT>
|
prefix = ()<EOL>if self.parent:<EOL><INDENT>prefix = self.parent.path<EOL><DEDENT>if self.id_or_name:<EOL><INDENT>return prefix + (self.kind, self.id_or_name)<EOL><DEDENT>return prefix + (self.kind,)<EOL>
|
tuple: The full Datastore path represented by this key.
|
f578:c1:m2
|
@property<EOL><INDENT>def is_partial(self):<DEDENT>
|
return len(self.path) % <NUM_LIT:2> != <NUM_LIT:0><EOL>
|
bool: ``True`` if this key doesn't have an id yet.
|
f578:c1:m3
|
@property<EOL><INDENT>def int_id(self):<DEDENT>
|
id_or_name = self.id_or_name<EOL>if id_or_name is not None and isinstance(id_or_name, int):<EOL><INDENT>return id_or_name<EOL><DEDENT>return None<EOL>
|
int: This key's numeric id.
|
f578:c1:m4
|
@property<EOL><INDENT>def str_id(self):<DEDENT>
|
id_or_name = self.id_or_name<EOL>if id_or_name is not None and isinstance(id_or_name, str):<EOL><INDENT>return id_or_name<EOL><DEDENT>return None<EOL>
|
str: This key's string id.
|
f578:c1:m5
|
def get_model(self):
|
return lookup_model_by_kind(self.kind)<EOL>
|
Get the model class for this Key.
Raises:
RuntimeError: If a model isn't registered for the Key's
kind.
Returns:
type: A Model class.
|
f578:c1:m6
|
def delete(self):
|
return delete_multi([self])<EOL>
|
Delete the entity represented by this Key from Datastore.
|
f578:c1:m7
|
def get(self):
|
return get_multi([self])[<NUM_LIT:0>]<EOL>
|
Get the entity represented by this Key from Datastore.
Returns:
Model: The entity or ``None`` if it does not exist.
|
f578:c1:m8
|
@property<EOL><INDENT>def name_on_entity(self):<DEDENT>
|
return self._name_on_entity<EOL>
|
str: The name of this Property inside the Datastore entity.
|
f578:c2:m1
|
@property<EOL><INDENT>def name_on_model(self):<DEDENT>
|
return self._name_on_model<EOL>
|
str: The name of this Property on the Model instance.
|
f578:c2:m2
|
@property<EOL><INDENT>def is_none(self):<DEDENT>
|
if not self.optional:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return self == None<EOL>
|
PropertyFilter: A filter that checks if this value is None.
|
f578:c2:m3
|
def validate(self, value):
|
if isinstance(value, self._types):<EOL><INDENT>return value<EOL><DEDENT>elif self.optional and value is None:<EOL><INDENT>return [] if self.repeated else None<EOL><DEDENT>elif self.repeated and isinstance(value, (tuple, list)) and all(isinstance(x, self._types) for x in value):<EOL><INDENT>return value<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(f"<STR_LIT>")<EOL><DEDENT>
|
Validates that `value` can be assigned to this Property.
Parameters:
value: The value to validate.
Raises:
TypeError: If the type of the assigned value is invalid.
Returns:
The value that should be assigned to the entity.
|
f578:c2:m4
|
def prepare_to_load(self, entity, value):
|
return value<EOL>
|
Prepare `value` to be loaded into a Model. Called by the
model for each Property, value pair contained in the persisted
data when loading it from an adapter.
Parameters:
entity(Model): The entity to which the value belongs.
value: The value being loaded.
Returns:
The value that should be assigned to the entity.
|
f578:c2:m5
|
def prepare_to_store(self, entity, value):
|
if value is None and not self.optional:<EOL><INDENT>raise RuntimeError(f"<STR_LIT>")<EOL><DEDENT>return value<EOL>
|
Prepare `value` for storage. Called by the Model for each
Property, value pair it contains before handing the data off
to an adapter.
Parameters:
entity(Model): The entity to which the value belongs.
value: The value being stored.
Raises:
RuntimeError: If this property is required but no value was
assigned to it.
Returns:
The value that should be persisted.
|
f578:c2:m6
|
def get_unindexed_properties(self, entity):
|
raise NotImplementedError<EOL>
|
tuple[str]: The set of unindexed properties belonging to
the underlying model and all nested models.
|
f578:c3:m0
|
@property<EOL><INDENT>def _is_polymorphic(self):<DEDENT>
|
return self._is_root or self._is_child<EOL>
|
bool: True if this child belongs to a polymorphic hierarchy.
|
f578:c5:m1
|
@property<EOL><INDENT>def unindexed_properties(self):<DEDENT>
|
properties = ()<EOL>for name, prop in self._properties.items():<EOL><INDENT>if isinstance(prop, EmbedLike):<EOL><INDENT>embedded_entity = getattr(self, name, None)<EOL>if embedded_entity:<EOL><INDENT>properties += prop.get_unindexed_properties(embedded_entity)<EOL><DEDENT><DEDENT>elif not prop.indexed or prop.indexed_if and not prop.indexed_if(self, prop, name):<EOL><INDENT>properties += (prop.name_on_entity,)<EOL><DEDENT><DEDENT>return properties<EOL>
|
tuple[str]: The names of all the unindexed properties on this entity.
|
f578:c6:m3
|
@classmethod<EOL><INDENT>def pre_get_hook(cls, key):<DEDENT>
|
A hook that runs before an entity is loaded from Datastore.
Raising an exception here will prevent the entity from being
loaded.
Parameters:
key(anom.Key): The datastore Key of the entity being loaded.
|
f578:c6:m4
|
|
def post_get_hook(self):
|
A hook that runs after an entity has been loaded from
Datastore.
|
f578:c6:m5
|
|
@classmethod<EOL><INDENT>def get(cls, id_or_name, *, parent=None, namespace=None):<DEDENT>
|
return Key(cls, id_or_name, parent=parent, namespace=namespace).get()<EOL>
|
Get an entity by id.
Parameters:
id_or_name(int or str): The entity's id.
parent(anom.Key, optional): The entity's parent Key.
namespace(str, optional): The entity's namespace.
Returns:
Model: An entity or ``None`` if the entity doesn't exist in
Datastore.
|
f578:c6:m6
|
@classmethod<EOL><INDENT>def pre_delete_hook(cls, key):<DEDENT>
|
A hook that runs before an entity is deleted. Raising an
exception here will prevent the entity from being deleted.
Parameters:
key(anom.Key): The datastore Key of the entity being deleted.
|
f578:c6:m7
|
|
@classmethod<EOL><INDENT>def post_delete_hook(cls, key):<DEDENT>
|
A hook that runs after an entity has been deleted.
Parameters:
key(anom.Key): The datastore Key of the entity being deleted.
|
f578:c6:m8
|
|
def delete(self):
|
return delete_multi([self.key])<EOL>
|
Delete this entity from Datastore.
Raises:
RuntimeError: If this entity was never stored (i.e. if its
key is partial).
|
f578:c6:m9
|
def pre_put_hook(self):
|
A hook that runs before this entity is persisted. Raising
an exception here will prevent the entity from being persisted.
|
f578:c6:m10
|
|
def post_put_hook(self):
|
A hook that runs after this entity has been persisted.
|
f578:c6:m11
|
|
def put(self):
|
return put_multi([self])[<NUM_LIT:0>]<EOL>
|
Persist this entity to Datastore.
|
f578:c6:m12
|
@classmethod<EOL><INDENT>def query(cls, **options):<DEDENT>
|
return Query(cls, **options)<EOL>
|
Return a new query for this Model.
Parameters:
\**options(dict): Parameters to pass to the :class:`Query`
constructor.
Returns:
Query: The new query.
|
f578:c6:m13
|
@property<EOL><INDENT>def is_true(self):<DEDENT>
|
return self == True<EOL>
|
PropertyFilter: A filter that checks if this value is True.
|
f579:c4:m0
|
@property<EOL><INDENT>def is_false(self):<DEDENT>
|
return self == False<EOL>
|
PropertyFilter: A filter that checks if this value is False.
|
f579:c4:m1
|
def start(self, *, timeout=<NUM_LIT:15>, inject=False):
|
try:<EOL><INDENT>self._thread.start()<EOL>env_vars = self._queue.get(block=True, timeout=timeout)<EOL>if inject:<EOL><INDENT>os.environ.update(env_vars)<EOL><DEDENT>return env_vars<EOL><DEDENT>except Empty: <EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>
|
Start the emulator process and wait for it to initialize.
Parameters:
timeout(int): The maximum number of seconds to wait for the
Emulator to start up.
inject(bool): Whether or not to inject the emulator env vars
into the current process.
Returns:
dict: A dictionary of env vars that can be used to access
the Datastore emulator.
|
f580:c0:m1
|
def stop(self):
|
if self._proc is not None:<EOL><INDENT>if self._proc.poll() is None:<EOL><INDENT>try:<EOL><INDENT>os.killpg(self._proc.pid, signal.SIGTERM)<EOL>_, returncode = os.waitpid(self._proc.pid, <NUM_LIT:0>)<EOL>_logger.debug("<STR_LIT>", returncode)<EOL>return returncode<EOL><DEDENT>except ChildProcessError: <EOL><INDENT>return self._proc.returncode<EOL><DEDENT><DEDENT>return self._proc.returncode <EOL><DEDENT>return None<EOL>
|
Stop the emulator process.
Returns:
int: The process return code or None if the process isn't
currently running.
|
f580:c0:m2
|
@property<EOL><INDENT>def _transactions(self):<DEDENT>
|
transactions = getattr(self._state, "<STR_LIT>", None)<EOL>if transactions is None:<EOL><INDENT>transactions = self._state.transactions = []<EOL><DEDENT>return transactions<EOL>
|
list[Transaction]: The current stack of Transactions.
|
f583:c2:m1
|
@property<EOL><INDENT>def _transactions(self):<DEDENT>
|
transactions = getattr(self._state, "<STR_LIT>", None)<EOL>if transactions is None:<EOL><INDENT>transactions = self._state.transactions = []<EOL><DEDENT>return transactions<EOL>
|
list[Transaction]: The current stack of Transactions.
|
f584:c3:m1
|
def replace(self, **options):
|
self.update(options)<EOL>return self<EOL>
|
Update this options object in place.
Parameters:
\**options(QueryOptions)
Returns:
QueryOptions: The updated instance.
|
f585:c1:m1
|
@property<EOL><INDENT>def batch_size(self):<DEDENT>
|
batch_size = self.get("<STR_LIT>", DEFAULT_BATCH_SIZE)<EOL>if self.limit is not None:<EOL><INDENT>return min(self.limit, batch_size)<EOL><DEDENT>return batch_size<EOL>
|
int: The number of results to fetch per batch. Clamped to
limit if limit is set and is smaller than the given batch
size.
|
f585:c1:m2
|
@property<EOL><INDENT>def keys_only(self):<DEDENT>
|
return self.get("<STR_LIT>", False)<EOL>
|
bool: Whether or not the results should be Keys or Entities.
|
f585:c1:m3
|
@property<EOL><INDENT>def limit(self):<DEDENT>
|
return self.get("<STR_LIT>", self.query.limit)<EOL>
|
int: The maximum number of results to return.
|
f585:c1:m4
|
@property<EOL><INDENT>def offset(self):<DEDENT>
|
return self.get("<STR_LIT>", self.query.offset)<EOL>
|
int: The number of results to skip.
|
f585:c1:m5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.