_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q242900 | Frame.insert | train | def insert(self):
"""Insert this document"""
from mongoframes.queries import to_refs
# Send insert signal
signal('insert').send(self.__class__, frames=[self])
# Prepare the document to be inserted
document = to_refs(self._document)
# Insert the document and upd... | python | {
"resource": ""
} |
q242901 | Frame.update | train | def update(self, *fields):
"""
Update this document. Optionally a specific list of fields to update can
be specified.
"""
from mongoframes.queries import to_refs
assert '_id' in self._document, "Can't update documents without `_id`"
# Send update signal
... | python | {
"resource": ""
} |
q242902 | Frame.upsert | train | def upsert(self, *fields):
"""
Update or Insert this document depending on whether it exists or not.
The presense of an `_id` value in the document is used to determine if
the document exists.
NOTE: This method is not the same as specifying the `upsert` flag when
calling... | python | {
"resource": ""
} |
q242903 | Frame.delete | train | def delete(self):
"""Delete this document"""
assert '_id' in self._document, "Can't delete documents without `_id`"
# Send delete signal
signal('delete').send(self.__class__, frames=[self])
# Delete the document
self.get_collection().delete_one({'_id': self._id})
... | python | {
"resource": ""
} |
q242904 | Frame.insert_many | train | def insert_many(cls, documents):
"""Insert a list of documents"""
from mongoframes.queries import to_refs
# Ensure all documents have been converted to frames
frames = cls._ensure_frames(documents)
# Send insert signal
signal('insert').send(cls, frames=frames)
... | python | {
"resource": ""
} |
q242905 | Frame.update_many | train | def update_many(cls, documents, *fields):
"""
Update multiple documents. Optionally a specific list of fields to
update can be specified.
"""
from mongoframes.queries import to_refs
# Ensure all documents have been converted to frames
frames = cls._ensure_frames(... | python | {
"resource": ""
} |
q242906 | Frame.delete_many | train | def delete_many(cls, documents):
"""Delete multiple documents"""
# Ensure all documents have been converted to frames
frames = cls._ensure_frames(documents)
all_count = len(documents)
assert len([f for f in frames if '_id' in f._document]) == all_count, \
"Can't... | python | {
"resource": ""
} |
q242907 | Frame._ensure_frames | train | def _ensure_frames(cls, documents):
"""
Ensure all items in a list are frames by converting those that aren't.
"""
frames = []
for document in documents:
if not isinstance(document, Frame):
frames.append(cls(document))
else:
... | python | {
"resource": ""
} |
q242908 | Frame.reload | train | def reload(self, **kwargs):
"""Reload the document"""
frame = self.one({'_id': self._id}, **kwargs)
self._document = frame._document | python | {
"resource": ""
} |
q242909 | Frame.count | train | def count(cls, filter=None, **kwargs):
"""Return a count of documents matching the filter"""
from mongoframes.queries import Condition, Group, to_refs
if isinstance(filter, (Condition, Group)):
filter = filter.to_dict()
return cls.get_collection().count(to_refs(filter), **k... | python | {
"resource": ""
} |
q242910 | Frame.ids | train | def ids(cls, filter=None, **kwargs):
"""Return a list of Ids for documents matching the filter"""
from mongoframes.queries import Condition, Group, to_refs
# Find the documents
if isinstance(filter, (Condition, Group)):
filter = filter.to_dict()
documents = cls.get_... | python | {
"resource": ""
} |
q242911 | Frame.one | train | def one(cls, filter=None, **kwargs):
"""Return the first document matching the filter"""
from mongoframes.queries import Condition, Group, to_refs
# Flatten the projection
kwargs['projection'], references, subs = \
cls._flatten_projection(
kwargs.get(... | python | {
"resource": ""
} |
q242912 | Frame.many | train | def many(cls, filter=None, **kwargs):
"""Return a list of documents matching the filter"""
from mongoframes.queries import Condition, Group, to_refs
# Flatten the projection
kwargs['projection'], references, subs = \
cls._flatten_projection(
kwargs.ge... | python | {
"resource": ""
} |
q242913 | Frame._apply_sub_frames | train | def _apply_sub_frames(cls, documents, subs):
"""Convert embedded documents to sub-frames for one or more documents"""
# Dereference each reference
for path, projection in subs.items():
# Get the SubFrame class we'll use to wrap the embedded document
sub = None
... | python | {
"resource": ""
} |
q242914 | Frame._dereference | train | def _dereference(cls, documents, references):
"""Dereference one or more documents"""
# Dereference each reference
for path, projection in references.items():
# Check there is a $ref in the projection, else skip it
if '$ref' not in projection:
continue
... | python | {
"resource": ""
} |
q242915 | Frame.listen | train | def listen(cls, event, func):
"""Add a callback for a signal against the class"""
signal(event).connect(func, sender=cls) | python | {
"resource": ""
} |
q242916 | Frame.stop_listening | train | def stop_listening(cls, event, func):
"""Remove a callback for a signal against the class"""
signal(event).disconnect(func, sender=cls) | python | {
"resource": ""
} |
q242917 | Frame.get_db | train | def get_db(cls):
"""Return the database for the collection"""
if cls._db:
return getattr(cls._client, cls._db)
return cls._client.get_default_database() | python | {
"resource": ""
} |
q242918 | ImageURL._default_service_formatter | train | def _default_service_formatter(
service_url,
width,
height,
background,
foreground,
options
):
"""Generate an image URL for a service"""
# Build the base URL
image_tmp = '{service_url}/{width}x{height}/{background}/{foreground}/'
i... | python | {
"resource": ""
} |
q242919 | Markov._body | train | def _body(self, paragraphs):
"""Generate a body of text"""
body = []
for i in range(paragraphs):
paragraph = self._paragraph(random.randint(1, 10))
body.append(paragraph)
return '\n'.join(body) | python | {
"resource": ""
} |
q242920 | Markov._paragraph | train | def _paragraph(self, sentences):
"""Generate a paragraph"""
paragraph = []
for i in range(sentences):
sentence = self._sentence(random.randint(5, 16))
paragraph.append(sentence)
return ' '.join(paragraph) | python | {
"resource": ""
} |
q242921 | Markov._sentence | train | def _sentence(self, words):
"""Generate a sentence"""
db = self.database
# Generate 2 words to start a sentence with
seed = random.randint(0, db['word_count'] - 3)
seed_word, next_word = db['words'][seed], db['words'][seed + 1]
w1, w2 = seed_word, next_word
# Ge... | python | {
"resource": ""
} |
q242922 | Markov.init_word_db | train | def init_word_db(cls, name, text):
"""Initialize a database of words for the maker with the given name"""
# Prep the words
text = text.replace('\n', ' ').replace('\r', ' ')
words = [w.strip() for w in text.split(' ') if w.strip()]
assert len(words) > 2, \
'Databa... | python | {
"resource": ""
} |
q242923 | SomeOf.p | train | def p(i, sample_size, weights):
"""
Given a weighted set and sample size return the probabilty that the
weight `i` will be present in the sample.
Created to test the output of the `SomeOf` maker class. The math was
provided by Andy Blackshaw - thank you dad :)
"""
... | python | {
"resource": ""
} |
q242924 | Faker.get_fake | train | def get_fake(locale=None):
"""Return a shared faker factory used to generate fake data"""
if locale is None:
locale = Faker.default_locale
if not hasattr(Maker, '_fake_' + locale):
Faker._fake = faker.Factory.create(locale)
return Faker._fake | python | {
"resource": ""
} |
q242925 | Unique._get_unique | train | def _get_unique(self, *args):
"""Generate a unique value using the assigned maker"""
# Generate a unique values
value = ''
attempts = 0
while True:
attempts += 1
value = self._maker(*args)
if value not in self._used_values:
bre... | python | {
"resource": ""
} |
q242926 | Blueprint.assemble | train | def assemble(cls):
"""Assemble a single document using the blueprint"""
document = {}
for field_name, maker in cls._instructions.items():
with maker.target(document):
document[field_name] = maker()
return document | python | {
"resource": ""
} |
q242927 | Blueprint.finish | train | def finish(cls, document):
"""
Take a assembled document and convert all assembled values to
finished values.
"""
target_document = {}
document_copy = {}
for field_name, value in document.items():
maker = cls._instructions[field_name]
targe... | python | {
"resource": ""
} |
q242928 | Blueprint.reassemble | train | def reassemble(cls, fields, document):
"""
Take a previously assembled document and reassemble the given set of
fields for it in place.
"""
for field_name in cls._instructions:
if field_name in fields:
maker = cls._instructions[field_name]
... | python | {
"resource": ""
} |
q242929 | ChangeLogEntry.is_diff | train | def is_diff(self):
"""Return True if there are any differences logged"""
if not isinstance(self.details, dict):
return False
for key in ['additions', 'updates', 'deletions']:
if self.details.get(key, None):
return True
return False | python | {
"resource": ""
} |
q242930 | ChangeLogEntry.diff_to_html | train | def diff_to_html(cls, details):
"""Return an entry's details in HTML format"""
changes = []
# Check that there are details to convert to HMTL
if not details:
return ''
def _frame(value):
"""
Handle converted `Frame` references where the human... | python | {
"resource": ""
} |
q242931 | ChangeLogEntry.diff_safe | train | def diff_safe(cls, value):
"""Return a value that can be safely stored as a diff"""
if isinstance(value, Frame):
return {'_str': str(value), '_id': value._id}
elif isinstance(value, (list, tuple)):
return [cls.diff_safe(v) for v in value]
return value | python | {
"resource": ""
} |
q242932 | ComparableFrame.comparable | train | def comparable(self):
"""Return a dictionary that can be compared"""
document_dict = self.compare_safe(self._document)
# Remove uncompared fields
self._remove_keys(document_dict, self._uncompared_fields)
# Remove any empty values
clean_document_dict = {}
for k, ... | python | {
"resource": ""
} |
q242933 | ComparableFrame.logged_delete | train | def logged_delete(self, user):
"""Delete the document and log the event in the change log"""
self.delete()
# Log the change
entry = ChangeLogEntry({
'type': 'DELETED',
'documents': [self],
'user': user
})
entry.insert()
r... | python | {
"resource": ""
} |
q242934 | ComparableFrame.logged_insert | train | def logged_insert(self, user):
"""Create and insert the document and log the event in the change log"""
# Insert the frame's document
self.insert()
# Log the insert
entry = ChangeLogEntry({
'type': 'ADDED',
'documents': [self],
'user': user
... | python | {
"resource": ""
} |
q242935 | ComparableFrame.logged_update | train | def logged_update(self, user, data, *fields):
"""
Update the document with the dictionary of data provided and log the
event in the change log.
"""
# Get a copy of the frames comparable data before the update
original = self.comparable
# Update the frame
... | python | {
"resource": ""
} |
q242936 | ComparableFrame.compare_safe | train | def compare_safe(cls, value):
"""Return a value that can be safely compared"""
# Date
if type(value) == date:
return str(value)
# Lists
elif isinstance(value, (list, tuple)):
return [cls.compare_safe(v) for v in value]
# Dictionaries
eli... | python | {
"resource": ""
} |
q242937 | ElemMatch | train | def ElemMatch(q, *conditions):
"""
The ElemMatch operator matches documents that contain an array field with at
least one element that matches all the specified query criteria.
"""
new_condition = {}
for condition in conditions:
deep_merge(condition.to_dict(), new_condition)
return ... | python | {
"resource": ""
} |
q242938 | SortBy | train | def SortBy(*qs):
"""Convert a list of Q objects into list of sort instructions"""
sort = []
for q in qs:
if q._path.endswith('.desc'):
sort.append((q._path[:-5], DESCENDING))
else:
sort.append((q._path, ASCENDING))
return sort | python | {
"resource": ""
} |
q242939 | deep_merge | train | def deep_merge(source, dest):
"""
Deep merges source dict into dest dict.
This code was taken directly from the mongothon project:
https://github.com/gamechanger/mongothon/tree/master/mongothon
"""
for key, value in source.items():
if key in dest:
if isinstance(value, dict) ... | python | {
"resource": ""
} |
q242940 | to_refs | train | def to_refs(value):
"""Convert all Frame instances within the given value to Ids"""
from mongoframes.frames import Frame, SubFrame
# Frame
if isinstance(value, Frame):
return value._id
# SubFrame
elif isinstance(value, SubFrame):
return to_refs(value._document)
# Lists
... | python | {
"resource": ""
} |
q242941 | Factory.assemble | train | def assemble(self, blueprint, quota):
"""Assemble a quota of documents"""
# Reset the blueprint
blueprint.reset()
# Assemble the documents
documents = []
for i in range(0, int(quota)):
documents.append(blueprint.assemble())
return documents | python | {
"resource": ""
} |
q242942 | Factory.finish | train | def finish(self, blueprint, documents):
"""Finish a list of pre-assembled documents"""
# Reset the blueprint
blueprint.reset()
# Finish the documents
finished = []
for document in documents:
finished.append(blueprint.finish(document))
return finishe... | python | {
"resource": ""
} |
q242943 | Factory.populate | train | def populate(self, blueprint, documents):
"""Populate the database with documents"""
# Finish the documents
documents = self.finish(blueprint, documents)
# Convert the documents to frame instances
frames = []
for document in documents:
# Separate out any met... | python | {
"resource": ""
} |
q242944 | Factory.reassemble | train | def reassemble(self, blueprint, fields, documents):
"""
Reassemble the given set of fields for a list of pre-assembed documents.
NOTE: Reassembly is done in place, since the data you send the method
should be JSON type safe, if you need to retain the existing document
it is reco... | python | {
"resource": ""
} |
q242945 | PublisherFrame.can_publish | train | def can_publish(self):
"""
Return True if there is a draft version of the document that's ready to
be published.
"""
with self.published_context():
published = self.one(
Q._uid == self._uid,
projection={'revision': True}
... | python | {
"resource": ""
} |
q242946 | PublisherFrame.can_revert | train | def can_revert(self):
"""
Return True if we can revert the draft version of the document to the
currently published version.
"""
if self.can_publish:
with self.published_context():
return self.count(Q._uid == self._uid) > 0
return False | python | {
"resource": ""
} |
q242947 | PublisherFrame.get_publisher_doc | train | def get_publisher_doc(self):
"""Return a publish safe version of the frame's document"""
with self.draft_context():
# Select the draft document from the database
draft = self.one(Q._uid == self._uid)
publisher_doc = draft._document
# Remove any keys from ... | python | {
"resource": ""
} |
q242948 | PublisherFrame.publish | train | def publish(self):
"""
Publish the current document.
NOTE: You must have saved any changes to the draft version of the
document before publishing, unsaved changes wont be published.
"""
publisher_doc = self.get_publisher_doc()
with self.published_context():
... | python | {
"resource": ""
} |
q242949 | PublisherFrame.new_revision | train | def new_revision(self, *fields):
"""Save a new revision of the document"""
# Ensure this document is a draft
if not self._id:
assert g.get('draft'), \
'Only draft documents can be assigned new revisions'
else:
with self.draft_context():
... | python | {
"resource": ""
} |
q242950 | PublisherFrame.delete | train | def delete(self):
"""Delete this document and any counterpart document"""
with self.draft_context():
draft = self.one(Q._uid == self._uid)
if draft:
super(PublisherFrame, draft).delete()
with self.published_context():
published = self.one(Q._... | python | {
"resource": ""
} |
q242951 | PublisherFrame.revert | train | def revert(self):
"""Revert the document to currently published version"""
with self.draft_context():
draft = self.one(Q._uid == self._uid)
with self.published_context():
published = self.one(Q._uid == self._uid)
for field, value in draft._document.items():
... | python | {
"resource": ""
} |
q242952 | PublisherFrame.get_collection | train | def get_collection(cls):
"""Return a reference to the database collection for the class"""
# By default the collection returned will be the published collection,
# however if the `draft` flag has been set against the global context
# (e.g `g`) then the collection returned will contain d... | python | {
"resource": ""
} |
q242953 | PublisherFrame.draft_context | train | def draft_context(cls):
"""Set the context to draft"""
previous_state = g.get('draft')
try:
g.draft = True
yield
finally:
g.draft = previous_state | python | {
"resource": ""
} |
q242954 | PublisherFrame.published_context | train | def published_context(cls):
"""Set the context to published"""
previous_state = g.get('draft')
try:
g.draft = False
yield
finally:
g.draft = previous_state | python | {
"resource": ""
} |
q242955 | initialize_registry | train | def initialize_registry(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
"""
Initialize the registry and the index.
:param args: :class:`argparse.Namespace` with "backend", "args", "force" and "log_level".
:param backend: Backend which is responsible for working with model files... | python | {
"resource": ""
} |
q242956 | publish_model | train | def publish_model(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
"""
Push the model to Google Cloud Storage and updates the index file.
:param args: :class:`argparse.Namespace` with "model", "backend", "args", "force", "meta" \
"update_default", "username", "passw... | python | {
"resource": ""
} |
q242957 | list_models | train | def list_models(args: argparse.Namespace):
"""
Output the list of known models in the registry.
:param args: :class:`argparse.Namespace` with "username", "password", "remote_repo" and \
"log_level"
:return: None
"""
try:
git_index = GitIndex(remote=args.index_rep... | python | {
"resource": ""
} |
q242958 | install_environment | train | def install_environment(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
"""
Install the packages mentioned in the model's metadata.
:param args: :param args: :class:`argparse.Namespace` with "input", "reproduce", "backend", \
"args", "username", "password", "remote... | python | {
"resource": ""
} |
q242959 | dump_model | train | def dump_model(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
"""
Print the information about the model.
:param args: :class:`argparse.Namespace` with "input", "backend", "args", "username", \
"password", "remote_repo" and "log_level".
:param backend: Backend ... | python | {
"resource": ""
} |
q242960 | register_backend | train | def register_backend(cls: Type[StorageBackend]):
"""Decorator to register another StorageBackend using it's `NAME`."""
if not issubclass(cls, StorageBackend):
raise TypeError("cls must be a subclass of StorageBackend")
__registry__[cls.NAME] = cls
return cls | python | {
"resource": ""
} |
q242961 | create_backend | train | def create_backend(name: str=None, git_index: GitIndex=None, args: str=None) -> StorageBackend:
"""Initialize a new StorageBackend by it's name and the specified model registry."""
if name is None:
name = config.BACKEND
if not args:
args = config.BACKEND_ARGS
if args:
try:
... | python | {
"resource": ""
} |
q242962 | create_backend_noexc | train | def create_backend_noexc(log: logging.Logger, name: str=None, git_index: GitIndex=None,
args: str=None) -> Optional[StorageBackend]:
"""Initialize a new Backend, return None if there was a known problem."""
try:
return create_backend(name, git_index, args)
except KeyError:
... | python | {
"resource": ""
} |
q242963 | supply_backend | train | def supply_backend(optional: Union[callable, bool]=False, index_exists: bool=True):
"""
Decorator to pass the initialized backend to the decorated callable. \
Used by command line entries. If the backend cannot be created, return 1.
:param optional: Either a decorated function or a value which indicate... | python | {
"resource": ""
} |
q242964 | generate_new_meta | train | def generate_new_meta(name: str, description: str, vendor: str, license: str) -> dict:
"""
Create the metadata tree for the given model name and the list of dependencies.
:param name: Name of the model.
:param description: Description of the model.
:param vendor: Name of the party which is responsi... | python | {
"resource": ""
} |
q242965 | extract_model_meta | train | def extract_model_meta(base_meta: dict, extra_meta: dict, model_url: str) -> dict:
"""
Merge the metadata from the backend and the extra metadata into a dict which is suitable for \
`index.json`.
:param base_meta: tree["meta"] :class:`dict` containing data from the backend.
:param extra_meta: dict ... | python | {
"resource": ""
} |
q242966 | squeeze_bits | train | def squeeze_bits(arr: numpy.ndarray) -> numpy.ndarray:
"""Return a copy of an integer numpy array with the minimum bitness."""
assert arr.dtype.kind in ("i", "u")
if arr.dtype.kind == "i":
assert arr.min() >= 0
mlbl = int(arr.max()).bit_length()
if mlbl <= 8:
dtype = numpy.uint8
... | python | {
"resource": ""
} |
q242967 | Model.metaprop | train | def metaprop(name: str, doc: str, readonly=False):
"""Temporary property builder."""
def get(self):
return self.meta[name]
get.__doc__ = "Get %s%s." % (doc, " (readonly)" if readonly else "")
if not readonly:
def set(self, value):
self.meta[name] ... | python | {
"resource": ""
} |
q242968 | Model.derive | train | def derive(self, new_version: Union[tuple, list]=None) -> "Model":
"""
Inherit the new model from the current one - used for versioning. \
This operation is in-place.
:param new_version: The version of the new model.
:return: The derived model - self.
"""
meta = ... | python | {
"resource": ""
} |
q242969 | Model.cache_dir | train | def cache_dir() -> str:
"""Return the default cache directory where downloaded models are stored."""
if config.VENDOR is None:
raise RuntimeError("modelforge is not configured; look at modelforge.configuration. "
"Depending on your objective you may or may not ... | python | {
"resource": ""
} |
q242970 | Model.get_dep | train | def get_dep(self, name: str) -> str:
"""
Return the uuid of the dependency identified with "name".
:param name:
:return: UUID
"""
deps = self.meta["dependencies"]
for d in deps:
if d["model"] == name:
return d
raise KeyError("%... | python | {
"resource": ""
} |
q242971 | Model.set_dep | train | def set_dep(self, *deps) -> "Model":
"""
Register the dependencies for this model.
:param deps: The parent models: objects or meta dicts.
:return: self
"""
self.meta["dependencies"] = [
(d.meta if not isinstance(d, dict) else d) for d in deps]
return ... | python | {
"resource": ""
} |
q242972 | Model.save | train | def save(self, output: Union[str, BinaryIO], series: Optional[str] = None,
deps: Iterable=tuple(), create_missing_dirs: bool=True) -> "Model":
"""
Serialize the model to a file.
:param output: Path to the file or a file object.
:param series: Name of the model series. If it... | python | {
"resource": ""
} |
q242973 | Model._write_tree | train | def _write_tree(self, tree: dict, output: Union[str, BinaryIO], file_mode: int=0o666) -> None:
"""
Write the model to disk.
:param tree: The data dict - will be the ASDF tree.
:param output: The output file path or a file object.
:param file_mode: The output file's permissions.
... | python | {
"resource": ""
} |
q242974 | refresh | train | def refresh():
"""Scan over all the involved directories and load configs from them."""
override_files = []
for stack in traceback.extract_stack():
f = os.path.join(os.path.dirname(stack[0]), OVERRIDE_FILE)
if f not in override_files:
override_files.insert(0, f)
if OVERRIDE_F... | python | {
"resource": ""
} |
q242975 | GCSBackend.create_client | train | def create_client(self) -> "google.cloud.storage.Client":
"""
Construct GCS API client.
"""
# Client should be imported here because grpc starts threads during import
# and if you call fork after that, a child process will be hang during exit
from google.cloud.storage imp... | python | {
"resource": ""
} |
q242976 | GCSBackend.connect | train | def connect(self) -> "google.cloud.storage.Bucket":
"""
Connect to the assigned bucket.
"""
log = self._log
log.info("Connecting to the bucket...")
client = self.create_client()
return client.lookup_bucket(self.bucket_name) | python | {
"resource": ""
} |
q242977 | GCSBackend.reset | train | def reset(self, force):
"""Connect to the assigned bucket or create if needed. Clear all the blobs inside."""
client = self.create_client()
bucket = client.lookup_bucket(self.bucket_name)
if bucket is not None:
if not force:
self._log.error("Bucket already exi... | python | {
"resource": ""
} |
q242978 | GCSBackend.upload_model | train | def upload_model(self, path: str, meta: dict, force: bool):
"""Put the model to GCS."""
bucket = self.connect()
if bucket is None:
raise BackendRequiredError
blob = bucket.blob("models/%s/%s.asdf" % (meta["model"], meta["uuid"]))
if blob.exists() and not force:
... | python | {
"resource": ""
} |
q242979 | GCSBackend.fetch_model | train | def fetch_model(self, source: str, file: Union[str, BinaryIO],
chunk_size: int=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> None:
"""Download the model from GCS."""
download_http(source, file, self._log, chunk_size) | python | {
"resource": ""
} |
q242980 | GCSBackend.delete_model | train | def delete_model(self, meta: dict):
"""Delete the model from GCS."""
bucket = self.connect()
if bucket is None:
raise BackendRequiredError
blob_name = "models/%s/%s.asdf" % (meta["model"], meta["uuid"])
self._log.info(blob_name)
try:
self._log.info... | python | {
"resource": ""
} |
q242981 | download_http | train | def download_http(source: str, file: Union[str, BinaryIO], log: logging.Logger,
chunk_size: int=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> None:
"""
Download a file from an HTTP source.
:param source: URL to fetch.
:param file: Where to store the downloaded data.
:param log: Logger.
:par... | python | {
"resource": ""
} |
q242982 | StorageBackend.upload_model | train | def upload_model(self, path: str, meta: dict, force: bool) -> str:
"""
Put the given file to the remote storage.
:param path: Path to the model file.
:param meta: Metadata of the model.
:param force: Overwrite an existing model.
:return: URL of the uploaded model.
... | python | {
"resource": ""
} |
q242983 | setup | train | def setup(level: Union[str, int], structured: bool, config_path: str = None):
"""
Make stdout and stderr unicode friendly in case of misconfigured \
environments, initializes the logging, structured logging and \
enables colored logs if it is appropriate.
:param level: The global logging level.
... | python | {
"resource": ""
} |
q242984 | set_context | train | def set_context(context):
"""Assign the logging context - an abstract object - to the current thread."""
try:
handler = logging.getLogger().handlers[0]
except IndexError:
# logging is not initialized
return
if not isinstance(handler, StructuredHandler):
return
handler... | python | {
"resource": ""
} |
q242985 | add_logging_args | train | def add_logging_args(parser: argparse.ArgumentParser, patch: bool = True,
erase_args: bool = True) -> None:
"""
Add command line flags specific to logging.
:param parser: `argparse` parser where to add new flags.
:param erase_args: Automatically remove logging-related flags from pa... | python | {
"resource": ""
} |
q242986 | NumpyLogRecord.array2string | train | def array2string(arr: numpy.ndarray) -> str:
"""Format numpy array as a string."""
shape = str(arr.shape)[1:-1]
if shape.endswith(","):
shape = shape[:-1]
return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape) | python | {
"resource": ""
} |
q242987 | NumpyLogRecord.getMessage | train | def getMessage(self):
"""
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied \
arguments with the message.
"""
if isinstance(self.msg, numpy.ndarray):
msg = self.array2string(self.msg)
else:
... | python | {
"resource": ""
} |
q242988 | AwesomeFormatter.formatMessage | train | def formatMessage(self, record: logging.LogRecord) -> str:
"""Convert the already filled log record to a string."""
level_color = "0"
text_color = "0"
fmt = ""
if record.levelno <= logging.DEBUG:
fmt = "\033[0;37m" + logging.BASIC_FORMAT + "\033[0m"
elif recor... | python | {
"resource": ""
} |
q242989 | StructuredHandler.emit | train | def emit(self, record: logging.LogRecord):
"""Print the log record formatted as JSON to stdout."""
created = datetime.datetime.fromtimestamp(record.created, timezone)
obj = {
"level": record.levelname.lower(),
"msg": record.msg % record.args,
"source": "%s:%d"... | python | {
"resource": ""
} |
q242990 | register_model | train | def register_model(cls: Type[Model]):
"""
Include the given model class into the registry.
:param cls: The class of the registered model.
:return: None
"""
if not issubclass(cls, Model):
raise TypeError("model bust be a subclass of Model")
if issubclass(cls, GenericModel):
r... | python | {
"resource": ""
} |
q242991 | GitIndex.fetch | train | def fetch(self):
"""Load from the associated Git repository."""
os.makedirs(os.path.dirname(self.cached_repo), exist_ok=True)
if not os.path.exists(self.cached_repo):
self._log.warning("Index not found, caching %s in %s", self.repo, self.cached_repo)
git.clone(self.remote... | python | {
"resource": ""
} |
q242992 | GitIndex.update_readme | train | def update_readme(self, template_readme: Template):
"""Generate the new README file locally."""
readme = os.path.join(self.cached_repo, "README.md")
if os.path.exists(readme):
os.remove(readme)
links = {model_type: {} for model_type in self.models.keys()}
for model_ty... | python | {
"resource": ""
} |
q242993 | GitIndex.reset | train | def reset(self):
"""Initialize the remote Git repository."""
paths = []
for filename in os.listdir(self.cached_repo):
if filename.startswith(".git"):
continue
path = os.path.join(self.cached_repo, filename)
if os.path.isfile(path):
... | python | {
"resource": ""
} |
q242994 | GitIndex.upload | train | def upload(self, cmd: str, meta: dict):
"""Push the current state of the registry to Git."""
index = os.path.join(self.cached_repo, self.INDEX_FILE)
if os.path.exists(index):
os.remove(index)
self._log.info("Writing the new index.json ...")
with open(index, "w") as _o... | python | {
"resource": ""
} |
q242995 | GitIndex.load_template | train | def load_template(self, template: str) -> Template:
"""Load a Jinja2 template from the source directory."""
env = dict(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False)
jinja2_ext = ".jinja2"
if not template.endswith(jinja2_ext):
self._log.error("Template fil... | python | {
"resource": ""
} |
q242996 | progress_bar | train | def progress_bar(enumerable, logger, **kwargs):
"""
Show the progress bar in the terminal, if the logging level matches and we are interactive.
:param enumerable: The iterator of which we indicate the progress.
:param logger: The bound logging.Logger.
:param kwargs: Keyword arguments to pass to cli... | python | {
"resource": ""
} |
q242997 | collect_environment | train | def collect_environment(no_cache: bool = False) -> dict:
"""
Return the version of the Python executable, the versions of the currently loaded packages \
and the running platform.
The result is cached unless `no_cache` is True.
"""
global _env
if _env is None or no_cache:
_env = col... | python | {
"resource": ""
} |
q242998 | collect_loaded_packages | train | def collect_loaded_packages() -> List[Tuple[str, str]]:
"""
Return the currently loaded package names and their versions.
"""
dists = get_installed_distributions()
get_dist_files = DistFilesFinder()
file_table = {}
for dist in dists:
for file in get_dist_files(dist):
file... | python | {
"resource": ""
} |
q242999 | Gourde.setup_blueprint | train | def setup_blueprint(self):
"""Initialize the blueprint."""
# Register endpoints.
self.blueprint.add_url_rule("/", "status", self.status)
self.blueprint.add_url_rule("/healthy", "health", self.healthy)
self.blueprint.add_url_rule("/ready", "ready", self.ready)
self.bluepr... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.