code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
elements = self._get_elements(resource_name, eclass, id=id) if not elements: raise ValueError("No resource matching: {0}".format(id)) if len(elements) == 1: return elements[0] raise ValueError("Multiple resources matching: {0}".format(id))
def _get_element_by_id(self, resource_name, eclass, id)
Get a single element matching an id
2.449218
2.317106
1.057016
# Domains are fixed and actually only one per REST api. if self._domains is None: self._domains = self._get_elements('domains', Domain) return self._domains
def get_domains(self)
Retrieves available domains. Returns: :py:obj:`list` of :py:class:`~.rest_primitives.Domain`: List of available domains
11.684687
13.394174
0.872371
json_resources = self.rest_client.make_request(self.resource_url)['resources'] return [RestResource(resource, self.rest_client) for resource in json_resources]
def get_resources(self)
Retrieves a list of all known Streams high-level REST resources. Returns: :py:obj:`list` of :py:class:`~.rest_primitives.RestResource`: List of all Streams high-level REST resources.
4.457269
4.361383
1.021985
vcap_services = streamsx.topology.context._vcap_from_service_definition(service_def) service_name = streamsx.topology.context._name_from_service_definition(service_def) return StreamingAnalyticsConnection(vcap_services, service_name)
def of_definition(service_def)
Create a connection to a Streaming Analytics service. The single service is defined by `service_def` which can be one of * The `service credentials` copied from the `Service credentials` page of the service console (not the Streams console). Credentials are provided in JSON format. They contain ...
4.252898
3.735532
1.138499
if self._iam: self._resource_url = self._resource_url or _get_iam_rest_api_url_from_creds(self.rest_client, self.credentials) else: self._resource_url = self._resource_url or _get_rest_api_url_from_creds(self.session, self.credentials) return self._resource_url
def resource_url(self)
str: Root URL for IBM Streams REST API
3.490887
3.087622
1.130607
log.info("OAuth20Authentication") try: key = request.GET.get('oauth_consumer_key') if not key: for header in ['Authorization', 'HTTP_AUTHORIZATION']: auth_header_value = request.META.get(header) if auth_header_value...
def is_authenticated(self, request, **kwargs)
Verify 2-legged oauth request. Parameters accepted as values in the "Authorization" header, as a GET request parameter, or in a POST body.
2.826156
2.73109
1.034809
http_method = request.method if not hasattr(self, http_method): raise OAuthError("HTTP method is not recognized") required_scopes = getattr(self, http_method) # a None scope means always allowed if required_scopes is None: return True # fo...
def check_scope(self, token, request)
The required scope is either a string or an iterable. If string, check if it is allowed for our access token otherwise, iterate through the required_scopes to see which scopes are allowed
4.208157
3.509417
1.199104
if not args: return False elif args[0] is 0: return True elif isinstance(args[0], int): return True else: return False
def _is_args_eightbit(*args) -> bool
Check if input matches type: renderer.eightbit.
3.915689
3.264975
1.199302
items: Dict[str, str] = {} for k, v in self.items(): if type(v) is str: items.update({k: v}) return items
def as_dict(self) -> Dict[str, str]
Export color register as dict.
3.538329
2.956271
1.196889
d = self.as_dict() return namedtuple('ColorRegister', d.keys())(*d.values())
def as_namedtuple(self)
Export color register as namedtuple.
6.897742
3.046911
2.263847
try: return extract_attrs(x, n) except (ValueError, IndexError): if PANDOCVERSION < '1.16': # Look for attributes attached to the image path, as occurs with # image references for pandoc < 1.16 (pandoc-fignos Issue #14). # See http://pandoc.org/MANUAL.h...
def _extract_attrs(x, n)
Extracts attributes for an image. n is the index where the attributes begin. Extracted elements are deleted from the element list x. Attrs are returned in pandoc format.
7.331879
6.879519
1.065754
# pylint: disable=global-statement global Nreferences # Global references counter global has_unnumbered_figures # Flags unnumbered figures were found global cursec # Current section # Parse the image attrs, caption = value[0]['c'][:2] # Initialize the re...
def _process_figure(value, fmt)
Processes the figure. Returns a dict containing figure properties.
3.732229
3.689521
1.011576
# Inspect the image if len(value[0]['c']) == 2: # Unattributed, bail out has_unnumbered_figures = True if fmt == 'latex': return [RawBlock('tex', r'\begin{no-prefix-figure-caption}'), Para(value), RawBlock('tex', r...
def process_figures(key, value, fmt, meta): # pylint: disable=unused-argument global has_unnumbered_figures # pylint: disable=global-statement # Process figures wrapped in Para elements if key == 'Para' and len(value) == 1 and \ value[0]['t'] == 'Image' and value[0]['c'][-1][1].startswith('fig...
Processes the figures.
4.392263
4.39697
0.99893
# pylint: disable=global-statement global PANDOCVERSION global Image # Get the output format and document fmt = args.fmt doc = json.loads(STDIN.read()) # Initialize pandocxnos # pylint: disable=too-many-function-args PANDOCVERSION = pandocxnos.init(args.pandocversion, doc) ...
def main()
Filters the document AST.
4.89492
4.797528
1.0203
if settings.USE_I18N: from django.views.i18n import javascript_catalog else: from django.views.i18n import null_javascript_catalog as javascript_catalog return javascript_catalog(request, packages=['media_tree'])
def i18n_javascript(self, request)
Displays the i18n JavaScript that the Django admin requires. This takes into account the USE_I18N setting. If it's set to False, the generated JavaScript will be leaner and faster.
2.817368
3.039111
0.927037
result = [] kwargs = get_kwargs_for_file_link(opts) for item in items: if isinstance(item, FileNode): result.append(get_file_link(item, **kwargs)) else: result.append(file_links(item, kwargs)) return result
def file_links(items, opts=None)
Turns a (optionally nested) list of FileNode objects into a list of strings, linking to the associated files.
2.663121
2.383893
1.117131
super(MediaTreeChangeList, self).get_results(request) try: reduce_levels = abs(int(get_request_attr(request, 'reduce_levels', 0))) except TypeError: reduce_levels = 0 is_filtered = self.is_filtered(request) if is_filtered or reduce_levels: ...
def get_results(self, request)
Temporarily decreases the `level` attribute of all search results in order to prevent indendation when displaying them.
3.437153
3.308443
1.038903
"Write your forwards methods here." for node in orm.FileNode.objects.all(): node.save()
def forwards(self, orm)
Write your forwards methods here.
14.188537
10.748125
1.320094
backends = app_settings.MEDIA_TREE_MEDIA_BACKENDS if not len(backends): if not fail_silently: raise ImproperlyConfigured('There is no media backend configured.' \ + ' Please define `MEDIA_TREE_MEDIA_BACKENDS` in your settings.') else:...
def get_media_backend(fail_silently=True, handles_media_types=None, handles_file_extensions=None, supports_thumbnails=None)
Returns the MediaBackend subclass that is configured for use with media_tree.
3.072833
2.967877
1.035364
args = token.split_contents() tag = args.pop(0) if len(args) >= 2 and args[-2] == 'as': context_name = args[-1] args = args[:-2] else: context_name = None if len(args) > 1: raise template.TemplateSyntaxError("Invalid syntax. Expected " "'{%% %s ...
def thumbnail_size(parser, token)
Returns a pre-configured thumbnail size, or assigns it to a context variable. Basic tag syntax:: {% thumbnail_size [size_name] [as var_name] %} The ``size`` parameter can be any of the size names configured using the setting ``MEDIA_TREE_THUMBNAIL_SIZES``. If omitted, the default size...
2.158555
2.290481
0.942403
body = None if data is not None: body = json.dumps(data, cls=utils.DateTimeEncoder) headers = { 'accept': 'application/json', 'content-type': 'application/json', 'user-agent': analyzere.user_agent, } resp = request_raw(method, path, params=params, body=body, hea...
def request(method, path, params=None, data=None, auto_retry=True)
method - HTTP method. e.g. get, put, post, etc. path - Path to resource. e.g. /loss_sets/1234 params - Parameter to pass in the query string data - Dictionary of parameters to pass in the request body
2.830927
3.017866
0.938056
file_obj.seek(0, 2) length = file_obj.tell() file_obj.seek(0) return length
def file_length(file_obj)
Returns the length in bytes of a given file object. Necessary because os.fstat only works on real files and not file-like objects. This works on more types of streams, primarily StringIO.
2.072425
2.021735
1.025073
offset = 0 while True: data = file_obj.read(chunk_size) if not data: break yield data, offset offset += len(data)
def read_in_chunks(file_obj, chunk_size)
Generator to read a file piece by piece.
2.156095
2.034425
1.059806
url = urlparse(href) path = url.path.split('/') collection_name = path[1] id_ = path[2] return collection_name, id_
def parse_href(href)
Parses an Analyze Re href into collection name and ID
3.260914
2.397405
1.360185
if isinstance(values, list): return ','.join(str(v) for v in values) return values
def vectorize(values)
Takes a value or list of values and returns a single result, joined by "," if necessary.
3.80305
2.748238
1.383814
if isinstance(values, tuple): return '_'.join(str(i) for i in values) if isinstance(values, list): if not all([isinstance(item, tuple) for item in values]): raise TypeError('Items in the list must be tuples') return ','.join('_'.join(str(i) for i in v) for v in values) ...
def vectorize_range(values)
This function is for url encoding. Takes a value or a tuple or list of tuples and returns a single result, tuples are joined by "," if necessary, elements in tuple are joined by '_'
2.628372
2.120253
1.23965
return u'%s %s %i' % (self.level_indicator * (getattr(obj, 'depth') - 1), smart_unicode(obj), obj.depth)
def label_from_instance(self, obj)
Creates labels which represent the tree level of each node when generating option labels.
8.243526
6.682643
1.233573
if not callable(upload_callback): raise Exception('provided upload_callback is not callable') if not callable(commit_callback): raise Exception('provided commit_callback is not callable') file_obj = StringIO(file_or_str) if isinstance( file_or_str, s...
def upload_data(self, file_or_str, chunk_size=analyzere.upload_chunk_size, poll_interval=analyzere.upload_poll_interval, upload_callback=lambda x: None, commit_callback=lambda x: None)
Accepts a file-like object or string and uploads it. Files are automatically uploaded in chunks. The default chunk size is 16MiB and can be overwritten by specifying the number of bytes in the ``chunk_size`` variable. Accepts an optional poll_interval for temporarily overriding the ...
3.300996
3.35309
0.984464
execute = request.POST.get('execute') storage = get_media_storage() broken_node_links = [] orphaned_files_choices = [] broken_nodes, orphaned_files = get_broken_media() for node in broken_nodes: link = mark_safe('<a href="%s">%s</a>' % (node.get_admin_url(), node.__unico...
def delete_orphaned_files(modeladmin, request, queryset=None)
Deletes orphaned files, i.e. media files existing in storage that are not in the database.
2.769986
2.737551
1.011848
tree = FileNode.tree.rebuild() messages.success(request, message=_('The node tree was rebuilt.')) return HttpResponseRedirect('')
def rebuild_tree(modeladmin, request, queryset=None)
Rebuilds whole tree in database using `parent` link.
8.497155
8.413203
1.009979
execute = request.POST.get('execute') files_in_storage = [] storage = get_media_storage() cache_files_choices = [] for storage_name in get_cache_files(): link = mark_safe('<a href="%s">%s</a>' % ( storage.url(storage_name), storage_name)) cache_files_choice...
def clear_cache(modeladmin, request, queryset=None)
Clears media cache files such as thumbnails.
2.884214
2.8683
1.005548
"Returns a suitable description of this field for South." from south.modelsinspector import introspector field_class = "django.db.models.fields.CharField" args, kwargs = introspector(self) return (field_class, args, kwargs)
def south_field_triple(self)
Returns a suitable description of this field for South.
3.839848
2.5297
1.517906
import copy from django.conf import settings from django.utils.module_loading import module_has_submodule for app in settings.INSTALLED_APPS: mod = import_module(app) try: import_module('%s.media_extension' % app) except: if module_has_submodule(mod,...
def autodiscover_media_extensions()
Auto-discover INSTALLED_APPS media_extensions.py modules and fail silently when not present. This forces an import on them to register any media extension bits they may want. Rip of django.contrib.admin.autodiscover()
2.118466
2.051731
1.032526
groups = list(RE_SPLITEXT.match(basename).groups()) if not groups[2]: groups[2] = groups[1] return groups
def multi_splitext(basename)
Similar to os.path.slittext(), but with special handling for files with multiple extensions, such as "archive.tar.gz": Returns a list containg three elements, the first being the name without any extensions (taking into account hidden files/leading periods), the second being the "full" extension, the third ...
4.34932
5.825298
0.746626
if condition is None: condition = text and new_text add_text = new_text if escape: add_text = conditional_escape(add_text) if add_text: add_text = format % add_text glue_format = glue_format_if_true if condition else glue_format_if_false return glue_format % (text, a...
def join_formatted(text, new_text, glue_format_if_true = u'%s%s', glue_format_if_false = u'%s%s', condition=None, format = u'%s', escape=False)
Joins two strings, optionally escaping the second, and using one of two string formats for glueing them together, depending on whether a condition is True or False. This function is a shorthand for complicated code blocks when you want to format some strings and link them together. A typical use case m...
2.348238
2.721149
0.862958
ratio = float(value) / float(max_value) return int(round(ratio * max_width))
def widthratio(value, max_value, max_width)
Does the same like Django's `widthratio` template tag (scales max_width to factor value/max_value)
2.779168
2.710126
1.025476
# Find the tree root root = os.path.abspath(path) try: while ".fmf" not in next(os.walk(root))[1]: if root == "/": raise utils.RootError( "Unable to find tree root for '{0}'.".format( os....
def _initialize(self, path)
Find metadata tree root, detect format version
2.721376
2.491953
1.092065
# Check parent, append source files if parent is None: parent = self.parent if parent is None: return self.sources = parent.sources + self.sources # Merge child data with parent data data = copy.deepcopy(parent.data) for key, value...
def merge(self, parent=None)
Merge parent data
4.04173
3.927944
1.028968
# Preserve original data and merge parent # (original data needed for custom inheritance extensions) self.original_data = self.data self.merge() log.debug("Data for '{0}' inherited.".format(self)) log.data(pretty(self.data)) # Apply inheritance to all chi...
def inherit(self)
Apply inheritance
10.065123
9.592123
1.049311
# Nothing to do if no data if data is None: return for key, value in sorted(data.items()): # Handle child attributes if key.startswith('/'): name = key.lstrip('/') # Handle deeper nesting (e.g. keys like /one/two/three)...
def update(self, data)
Update metadata, handle virtual hierarchy
4.717463
4.731238
0.997089
# Return the whole dictionary if no attribute specified if name is None: return self.data if not isinstance(name, list): name = [name] data = self.data try: for key in name: data = data[key] except KeyError: ...
def get(self, name=None, default=None)
Get attribute value or return default Whole data dictionary is returned when no attribute provided. Supports direct values retrieval from deep dictionaries as well. Dictionary path should be provided as list. The following two examples are equal: tree.data['hardware']['memory']...
3.153651
2.72519
1.157222
try: if isinstance(data, dict): self.children[name].update(data) else: self.children[name].grow(data) except KeyError: self.children[name] = Tree(data, name, parent=self) # Save source file if source is not None...
def child(self, name, data, source=None)
Create or update child with given data
2.888981
2.873984
1.005218
if path is None: return path = path.rstrip("/") log.info("Walking through directory {0}".format( os.path.abspath(path))) dirpath, dirnames, filenames = next(os.walk(path)) # Investigate main.fmf as the first file (for correct inheritance) ...
def grow(self, path)
Grow the metadata tree for the given directory path Note: For each path, grow() should be run only once. Growing the tree from the same path multiple times with attribute adding using the "+" sign leads to adding the value more than once!
3.873438
3.88553
0.996888
if whole or not self.children: yield self for name, child in self.children.items(): for node in child.climb(whole): yield node
def climb(self, whole=False)
Climb through the tree (iterate leaf/all nodes)
3.747253
3.266551
1.147159
for node in self.climb(whole=True): if node.name == name: return node return None
def find(self, name)
Find node with given name
6.985136
6.205303
1.125672
for node in self.climb(whole): # Select only nodes with key content if not all([key in node.data for key in keys]): continue # Select nodes with name matching regular expression if names and not any( [re.search(name, no...
def prune(self, whole=False, keys=[], names=[], filters=[])
Filter tree nodes based on given criteria
5.788839
5.614911
1.030976
# Show nothing if there's nothing if not self.data: return None # Custom formatting if formatting is not None: formatting = re.sub("\\\\n", "\n", formatting) name = self.name data = self.data root = self.root ...
def show(self, brief=False, formatting=None, values=[])
Show metadata
3.740737
3.698264
1.011485
level = getattr(obj, obj._mptt_meta.level_attr) level_indicator = mark_safe(conditional_escape(self.level_indicator) * level) return mark_safe(u'%s %s' % (level_indicator, conditional_escape(smart_unicode(obj))))
def label_from_instance(self, obj)
Creates labels which represent the tree level of each node when generating option labels.
4.20374
4.042497
1.039887
try: self.node.move_to(self.cleaned_data['target'], self.cleaned_data['position']) return self.node except InvalidMove, e: self.errors[NON_FIELD_ERRORS] = ErrorList(e) raise
def save(self)
Attempts to move the node using the selected target and position. If an invalid move is attempted, the related error message will be added to the form's non-field errors and the error will be re-raised. Callers should attempt to catch ``InvalidNode`` to redisplay the form with t...
5.310752
3.096969
1.714823
if not isinstance(names, list) or isinstance(names, tuple): names = (names,) for dir_name in dirs: for name in names: path = os.path.join(dir_name, name + file_ext) if not path in EXISTING_PATHS: # check on file system,...
def find(names, dirs, file_ext)
Iterating a set of dirs under the static root, this method tries to find a file named like one of the names and file ext passed, and returns the storage path to the first file it encounters. Usage this method makes it possible to override static files (such as icon sets) in a s...
3.595231
3.425099
1.049672
names = [] for attr_name in ('extension', 'mimetype', 'mime_supertype'): attr = getattr(file_node, attr_name) if attr: names.append(attr) if default_name: names.append(default_name) icon_path = StaticPathFinder.find(names, dirs...
def find(file_node, dirs=ICON_DIRS, default_name=None, file_ext='.png')
Iterating all icon dirs, try to find a file called like the node's extension / mime subtype / mime type (in that order). For instance, for an MP3 file ("audio/mpeg"), this would look for: "mp3.png" / "audio/mpeg.png" / "audio.png"
3.516201
3.400254
1.0341
return { #'filtered': is_filtered_cl(cl, request), 'results': (th_for_result(cl, res) for res in list(cl.result_list)), }
def result_tree_flat(context, cl, request)
Added 'filtered' param, so the template's js knows whether the results have been affected by a GET param or not. Only when the results are not filtered you can drag and sort the tree
11.421078
10.199392
1.11978
# Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None: queryset = self.get_queryset() path = self.kwargs.get('path', None) # Next, try looking up by path. if path is not None: quer...
def get_object(self, queryset=None)
Returns the object the view is displaying. By default this requires `self.queryset` and a `pk` or `path` argument in the URLconf, but subclasses can override this to return any object.
2.746262
2.619511
1.048387
view = self.get_view(request, self.view_class, opts) view.object = object return view
def get_detail_view(self, request, object, opts=None)
Instantiates and returns the view class that will generate the actual context for this plugin.
4.579274
4.558131
1.004639
view = self.get_view(request, self.view_class, opts) view.queryset = queryset return view
def get_listing_view(self, request, queryset, opts=None)
Instantiates and returns the view class that will generate the actual context for this plugin. ``queryset`` can be an actual QuerySet or any iterable.
4.752772
5.910433
0.804133
kwargs = {} if opts: if not isinstance(opts, dict): opts = opts.__dict__ else: opts = {} if not view_class in VALID_MIXIN_OPTIONS: valid_options = view_class.__dict__.keys() for cls in view_class.__bases__: ...
def get_view(self, request, view_class, opts=None)
Instantiates and returns the view class that will generate the actual context for this plugin.
2.348349
2.355347
0.997029
group = self.parser.add_argument_group("Format") group.add_argument( "--format", dest="formatting", default=None, help="Custom output format using the {} expansion") group.add_argument( "--value", dest="values", action="append", default=[], ...
def options_formatting(self)
Formating options
5.238022
4.926081
1.063324
group = self.parser.add_argument_group("Utils") group.add_argument( "--path", action="append", dest="paths", help="Path to the metadata tree (default: current directory)") group.add_argument( "--verbose", action="store_true", help="Print i...
def options_utils(self)
Utilities
3.749961
3.750769
0.999785
self.parser = argparse.ArgumentParser( description="List names of available objects") self.options_select() self.options_utils() self.options = self.parser.parse_args(self.arguments[2:]) self.show(brief=True)
def command_ls(self)
List names
7.550155
7.220366
1.045675
self.parser = argparse.ArgumentParser( description="Show metadata of available objects") self.options_select() self.options_formatting() self.options_utils() self.options = self.parser.parse_args(self.arguments[2:]) self.show(brief=False)
def command_show(self)
Show metadata
7.324999
6.517368
1.12392
self.parser = argparse.ArgumentParser( description="Initialize a new metadata tree") self.options_utils() self.options = self.parser.parse_args(self.arguments[2:]) # For each path create an .fmf directory and version file for path in self.options.paths or ["....
def command_init(self)
Initialize tree
3.655144
3.518679
1.038783
output = [] for path in self.options.paths or ["."]: if self.options.verbose: utils.info("Checking {0} for metadata.".format(path)) tree = fmf.Tree(path) for node in tree.prune( self.options.whole, self.options.keys, self.o...
def show(self, brief=False)
Show metadata for each path given
3.843687
3.684015
1.043342
colors = {"black": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "magenta": 35, "cyan": 36, "white": 37} # Nothing do do if coloring disabled if enabled == "auto": enabled = Coloring().enabled() if not enabled: return text # Prepare colors (strip 'light' if...
def color(text, color=None, background=None, light=False, enabled="auto")
Return text in desired color if coloring enabled Available colors: black red green yellow blue magenta cyan white. Alternatively color can be prefixed with "light", e.g. lightgreen.
2.845746
2.819331
1.009369
# Create logger, handler and formatter logger = logging.getLogger(name) handler = logging.StreamHandler() handler.setFormatter(Logging.ColoredFormatter()) logger.addHandler(handler) # Save log levels in the logger itself (backward compatibility) for level...
def _create_logger(name='fmf', level=None)
Create fmf logger
3.544763
3.46969
1.021637
if 'path' in kwargs: kwargs = self.get_filter_args_with_path(False, **kwargs) return super(FileNodeManager, self).filter(*args, **kwargs)
def filter(self, *args, **kwargs)
Works just like the default Manager's :func:`filter` method, but you can pass an additional keyword argument named ``path`` specifying the full **path of the folder whose immediate child objects** you want to retrieve, e.g. ``"path/to/folder"``.
5.273456
4.581061
1.151143
if 'path' in kwargs: kwargs = self.get_filter_args_with_path(False, **kwargs) return super(FileNodeManager, self).exclude(*args, **kwargs)
def exclude(self, *args, **kwargs)
Works just like the default Manager's :func:`exclude` method, but you can pass an additional keyword argument named ``path`` specifying the full **path of the folder whose immediate child objects** you want to exclude, e.g. ``"path/to/folder"``.
5.352072
4.680706
1.143433
if 'path' in kwargs: kwargs = self.get_filter_args_with_path(True, **kwargs) return super(FileNodeManager, self).get( *args, **kwargs)
def get(self, *args, **kwargs)
Works just like the default Manager's :func:`get` method, but you can pass an additional keyword argument named ``path`` specifying the full path of the object you want to retrieve, e.g. ``"path/to/folder/readme.txt"``.
6.059829
5.231122
1.158419
if not self.editable: # Skip validation for non-editable fields. return if self._choices and value: print(value) l = value if type(value) != list: l = [ value ] for v in value: for option_key...
def validate(self, value, model_instance)
Validates value and throws ValidationError. Subclasses should override this to provide validation logic.
2.715668
2.59816
1.045228
url = getattr(self, field_name).url if '://' in url: # `MEDIA_URL` already contains domain return url protocol = getattr(settings, 'PROTOCOL', 'http') domain = Site.objects.get_current().domain port = getattr(settings, 'PORT', '') return '...
def get_qualified_file_url(self, field_name='file')
Returns a fully qualified URL for the :attr:`file` field, including protocol, domain and port. In most cases, you can just use ``file.url`` instead, which (depending on your ``MEDIA_URL``) may or may not contain the domain. In some cases however, you always need a fully qualified URL. Th...
2.841948
2.482105
1.144975
if not query_params: query_params = {} url = '' if self.is_top_node(): url = reverse('admin:media_tree_filenode_changelist'); elif use_path and (self.is_folder() or self.pk): url = reverse('admin:media_tree_filenode_open_path', args=(self.ge...
def get_admin_url(self, query_params=None, use_path=False)
Returns the URL for viewing a FileNode in the admin.
2.35684
2.23155
1.056144
def field_format(field): if field in field_formats: return field_formats[field] return u'%s' t = join_formatted('', self.title, format=field_format('title'), escape=escape) t = join_formatted(t, self.description, u'%s: %s', escape=escape) ...
def get_metadata_display(self, field_formats = {}, escape=True)
Returns object metadata that has been selected to be displayed to users, compiled as a string.
3.063705
3.115137
0.98349
if self.override_caption != '': return self.override_caption else: return mark_safe(self.get_metadata_display(field_formats, escape=escape))
def get_caption_formatted(self, field_formats = app_settings.MEDIA_TREE_METADATA_FORMATS, escape=True)
Returns object metadata that has been selected to be displayed to users, compiled as a string including default formatting, for example bold titles. You can use this method in templates where you want to output image captions.
3.734141
4.140335
0.901893
if self.override_alt != '' and self.override_alt is not None: return self.override_alt elif self.override_caption != '' and self.override_caption is not None: return self.override_caption else: return self.get_metadata_display()
def alt(self)
Returns object metadata suitable for use as the HTML ``alt`` attribute. You can use this method in templates:: <img src="{{ node.file.url }}" alt="{{ node.alt }}" />
3.310123
3.254319
1.017148
self.success_count = 0 for node in self.get_selected_nodes(): self.move_node(node, self.cleaned_data['target_node'])
def save(self)
Attempts to move the nodes using the selected target and position. If an invalid move is attempted, the related error message will be added to the form's non-field errors and the error will be re-raised. Callers should attempt to catch ``InvalidMove`` to redisplay the form with ...
6.784341
4.970112
1.365028
storage = get_media_storage() for storage_name in self.cleaned_data['selected_files']: full_path = storage.path(storage_name) try: storage.delete(storage_name) self.success_files.append(full_path) except OSError: ...
def save(self)
Deletes the selected files from storage
3.732367
3.005686
1.241769
return __get_filenode_list(nodes, filter_media_types=filter_media_types, exclude_media_types=exclude_media_types, filter=filter, ordering=ordering, processors=processors, list_method='extend', max_depth=max_depth, max_nodes=max_nodes)
def get_merged_filenode_list(nodes, filter_media_types=None, exclude_media_types=None, filter=None, ordering=None, processors=None, max_depth=None, max_nodes=None)
Almost the same as :func:`get_nested_filenode_list`, but returns a flat (one-dimensional) list. Using the same QuerySet as in the example for `get_nested_filenode_list`, this method would return:: [ <FileNode: Empty folder>, <FileNode: Photo folder>, <FileNode: photo1.jp...
2.070545
2.37469
0.871922
link_text = None if use_metadata: link_text = node.get_metadata_display() if not link_text: link_text = node.__unicode__() if node.node_type != media_types.FOLDER: if include_extension: if extra != '': extra += ' ' extra = '<span class...
def get_file_link(node, use_metadata=False, include_size=False, include_extension=False, include_icon=False, href=None, extra_class='', extra='')
Returns a formatted HTML link tag to the FileNode's file, optionally including some meta information about the file.
2.071957
2.033411
1.018956
# If the user has not yet confirmed the deletion, call the regular delete # action that will present a confirmation page if not request.POST.get('post'): return actions.delete_selected(modeladmin, request, queryset) # Otherwise, delete objects one by one n = ...
def delete_selected_tree(self, modeladmin, request, queryset)
Deletes multiple instances and makes sure the MPTT fields get recalculated properly. (Because merely doing a bulk delete doesn't trigger the post_delete hooks.)
4.380529
4.269609
1.025979
if ':' not in target_name: raise ValueError( "Must provide fully-qualified target name (with `:') to avoid " "possible ambiguity - `{}' not valid".format(target_name)) mod, name = split(target_name) return '{}:{}'.format( PurePath(norm_proj_path(mod, build_modul...
def norm_name(build_module: str, target_name: str)
Return a normalized canonical target name for the `target_name` observed in build module `build_module`. A normalized canonical target name is of the form "<build module>:<name>", where <build module> is the relative normalized path from the project root to the target build module (POSIX), and <name...
7.37377
6.950366
1.060918
if target_selector == '**:*': return target_selector if ':' not in target_selector: target_selector += ':*' build_module, target_name = split(target_selector) build_module = normpath(join(conf.get_rel_work_dir(), build_module)) return '{}:{}'.format(PurePath(build_module).as_pos...
def expand_target_selector(target_selector: str, conf: Config)
Return a normalized target name (where `**:*` is the normalized form of itself). Target specifier can be: - `**:*` - means to recursively build all targets under current working dir. - relative path from current working directory to another directory - means to build all targets defin...
5.681744
4.273429
1.329551
return sorted(build_context.targets[target_name].hash(build_context) for target_name in listify(targets))
def hashify_targets(targets: list, build_context) -> list
Return sorted hashes of `targets`.
7.6584
4.617975
1.658389
return {filepath.replace('\\', '/'): hash_tree(filepath) for filepath in listify(files)}
def hashify_files(files: list) -> dict
Return mapping from file path to file hash.
12.621466
7.525156
1.677237
if prop_type in (PT.Target, PT.TargetList): return hashify_targets(value, build_context) elif prop_type in (PT.File, PT.FileList): return hashify_files(value) return value
def process_prop(prop_type: PT, value, build_context)
Return a cachable representation of the prop `value` given its type.
3.918409
3.506238
1.117554
props = {} test_props = {} for prop in self.props: if prop in self._prop_json_blacklist: continue sig_spec = Plugin.builders[self.builder_name].sig.get(prop) if sig_spec is None: continue if prop in self._pr...
def compute_json(self, build_context)
Compute and store a JSON serialization of this target for caching purposes. The serialization includes: - The build flavor - The builder name - Target tags - Hashes of target dependencies & buildenv - Processed props (where target props are replaced with their...
3.744066
3.383406
1.106597
if self._json is None: self.compute_json(build_context) return self._json
def json(self, build_context) -> str
Return JSON serialization of this target for caching purposes.
5.2925
3.361365
1.574509
m = md5() m.update(self.json(build_context).encode('utf8')) self._hash = m.hexdigest() m = md5() m.update(self.test_json(build_context).encode('utf8')) self._test_hash = m.hexdigest()
def compute_hash(self, build_context)
Compute and store the hash of this target for caching purposes. The hash is computed over the target JSON representation.
2.631427
2.468966
1.065801
if self._hash is None: self.compute_hash(build_context) return self._hash
def hash(self, build_context) -> str
Return the hash of this target for caching purposes.
4.721772
3.025379
1.560721
if icb.pull_if_cached or (icb.pull_if_not_cached and get_cached_image_id(icb.remote_image) is None): try: pull_docker_image(icb.remote_image, conf.docker_pull_cmd) except CalledProcessError: pass local_image = '{}:{}'.format(name, tag) ...
def handle_build_cache( conf: Config, name: str, tag: str, icb: ImageCachingBehavior)
Handle Docker image build cache. Return image ID if image is cached, and there's no need to redo the build. Return None if need to build the image (whether cached locally or not). Raise RuntimeError if not allowed to build the image because of state of local cache. TODO(itamar): figure out a bette...
2.983769
2.74875
1.0855
handler = logging.StreamHandler(stream=stream) # Using Brace Formatter (see # https://docs.python.org/3.5/howto/logging-cookbook.html#use-of-alternative-formatting-styles) formatter = logging.Formatter( '{asctime} {name:24s} {levelname:8s} {message}', style='{') handler.setFormatter(for...
def add_stream_handler(logger, stream)
Add a brace-handler stream-handler using `stream` to `logger`.
2.983369
2.863671
1.041799
root_logger = logging.getLogger() root_logger.setLevel(getattr(logging, conf.loglevel.upper())) if conf.logtostderr: add_stream_handler(root_logger, sys.stderr) if conf.logtostdout: add_stream_handler(root_logger, sys.stdout)
def configure_logging(conf)
Initialize and configure logging.
2.014765
2.009713
1.002514
it = _iglob(pathname, recursive) if recursive and _isrecursive(pathname): s = next(it) # skip empty string assert not s return it
def iglob(pathname, *, recursive=False)
Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. If recursive is true, the pattern '**' wi...
8.141245
16.423969
0.495693
if self.sig is not None: raise KeyError('{} already registered a signature!' .format(builder_name)) self.sig = OrderedDict(name=ArgSpec(PropType.TargetName, Empty)) self.docstring = docstring kwargs_section = False for arg_spec in l...
def register_sig(self, builder_name: str, sig: list, docstring: str, cachable: bool=True, attempts=1)
Register a builder signature & docstring for `builder_name`. The input for the builder signature is a list of "sig-spec"s representing the builder function arguments. Each sig-spec in the list can be: 1. A string. This represents a simple untyped positional argument name, w...
4.077896
2.917754
1.397615
cls.builders.pop(builder_name, None) for hook_spec in cls.hooks.values(): hook_spec.pop(builder_name, None)
def remove_builder(cls, builder_name: str)
Remove a registered builder `builder_name`. No reason to use this except for tests.
4.214623
3.268636
1.289413
build_file = Path(build_file_path) root = Path(conf.project_root) return build_file.resolve().relative_to(root).parent.as_posix().strip('.')
def to_build_module(build_file_path: str, conf: Config) -> str
Return a normalized build module name for `build_file_path`.
4.660259
3.42894
1.359096
import pkg_resources print('This is {} version {}, imported from {}' .format(__oneliner__, __version__, __file__)) if len(Plugin.builders) > 0: print('setuptools registered builders:') for entry_point in pkg_resources.iter_entry_points('yabt.builders'): print(' {0.module_...
def cmd_version(unused_conf)
Print out version information about YABT and detected builders.
6.37627
5.31466
1.199751
for name, builder in sorted(Plugin.builders.items()): if builder.func: print('+- {0:16s} implemented in {1.__module__}.{1.__name__}()' .format(name, builder.func)) else: print('+- {0:16s} loaded with no builder function'.format(name)) for hook_n...
def cmd_list(unused_conf: Config)
Print out information on loaded builders and hooks.
3.85149
3.039994
1.26694
build_context = BuildContext(conf) populate_targets_graph(build_context, conf) build_context.build_graph(run_tests=run_tests) build_context.write_artifacts_metadata()
def cmd_build(conf: Config, run_tests: bool=False)
Build requested targets, and their dependencies.
5.146071
4.498501
1.143952
build_context = BuildContext(conf) populate_targets_graph(build_context, conf) if conf.output_dot_file is None: write_dot(build_context, conf, sys.stdout) else: with open(conf.output_dot_file, 'w') as out_file: write_dot(build_context, conf, out_file)
def cmd_dot(conf: Config)
Print out a neat targets dependency tree based on requested targets. Use graphviz to render the dot file, e.g.: > ybt dot :foo :bar | dot -Tpng -o graph.png
2.986568
3.455445
0.864308
build_context = BuildContext(conf) populate_targets_graph(build_context, conf) def print_target_with_deps(target, depth=2): print('{: >{}}{}'.format('+-', depth, target.name)) for dep in sorted( build_context.target_graph.neighbors(target.name)): print_targe...
def cmd_tree(conf: Config)
Print out a neat targets dependency tree based on requested targets.
2.851166
2.652642
1.07484
conf = init_and_get_conf() logger = make_logger(__name__) logger.info('YaBT version {}', __version__) handlers = { 'build': YabtCommand(func=cmd_build, requires_project=True), 'dot': YabtCommand(func=cmd_dot, requires_project=True), 'test': YabtCommand(func=cmd_test, require...
def main()
Main `ybt` console script entry point - run YABT from command-line.
3.612486
3.324155
1.086738