code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
def comparator_wrapper(self, other):
try:
# [PATCH] The code was originally the following:
#
# assert self.enumtype == other.enumtype
# result = func(self.index, other.index)
#
# which first statement causes an issue when s... | def _comparator(func) | Decorator for EnumValue rich comparison methods. | 9.063528 | 9.302414 | 0.97432 |
this = copy.deepcopy(self)
value_type = kwargs.get('value_type', EnumValue)
if not keys:
raise EnumEmptyError()
keys = tuple(keys)
values = [None] * len(keys)
for i, key in enumerate(keys):
value = value_type(this, i, key)
... | def extend(self, *keys, **kwargs) | Return a new enumeration object extended with the specified items. | 3.441226 | 3.139679 | 1.096044 |
''' Verifies that the preview is a valid filetype '''
if not preview:
return False
if mimetype(preview) not in [ExportMimeType.PNG, ExportMimeType.PDF]:
return False
return True | def is_valid_preview(preview) | Verifies that the preview is a valid filetype | 8.425986 | 6.551007 | 1.286212 |
''' Generates a preview of src_path in the requested format.
:returns: A list of preview paths, one for each page. Blank list if unsupported.
'''
preview = embedded_preview(src_path)
if not is_valid_preview(preview):
preview = generator_preview(src_path)
if not is_valid_preview(preview):
preview =... | def preview(src_path) | Generates a preview of src_path in the requested format.
:returns: A list of preview paths, one for each page. Blank list if unsupported. | 5.21418 | 3.274033 | 1.592586 |
if self.mapping_key(data) in self.keys:
yield next(i for i in self.folders if i.metadata == data)
else:
index = bisect.bisect_left(self.keys, self.mapping_key(data))
posns = sorted(set([max(0, index - 1), index]))
yield from (self.folders[i] for i... | def options(self, data) | Generate folders to best match metadata.
The results will be a single, perfectly matched folder, or the two nearest
neighbours of an imperfect match.
:param dict data: metadata matching criteria.
This method is a generator. It yields
:py:class:`turberfield.dialogue.model.Scene... | 5.173153 | 4.967925 | 1.041311 |
field_type = field_cfg[Field.FIELD_TYPE]
field_key = field_cfg[Field.FIELD_KEY] if Field.FIELD_KEY in field_cfg else None
field_ext_id = field_cfg[Field.FIELD_EXT_ID] if Field.FIELD_EXT_ID in field_cfg else field_key
if field_type == Types.TYPE_ARRAY:
if isinstance(t... | def parse_field(data, field_cfg, target, is_optional=False) | Recursively parses response according to configuration
:param data: response or its part
:param field_cfg: field configuration
:param target: target object for parsed data
:param is_optional: optional sign | 2.203393 | 2.227242 | 0.989292 |
if request_type == ExportRequest.TYPE_SET_FIELD_VALUE:
return SetFieldValueRequest(cfg, login, pswd)
elif request_type == ExportRequest.TYPE_CREATE_ENTITY:
return CreateEntityRequest(cfg, login, pswd)
elif request_type == ExportRequest.TYPE_DELETE_ENTITY:
... | def factory(cfg, login, pswd, request_type) | Instantiate ExportRequest
:param cfg: request configuration, should consist of request description (url and optional parameters)
:param login:
:param pswd:
:param request_type: TYPE_SET_FIELD_VALUE || TYPE_CREATE_ENTITY || TYPE_DELETE_ENTITY || TYPE_CREATE_RELATION
:return: Expor... | 1.99955 | 1.460937 | 1.368677 |
if request_type == ImportRequest.TYPE_GET_LIST:
return ListImportRequest(cfg, login, pswd)
elif request_type == ImportRequest.TYPE_GET_SINGLE_OBJECT:
return SingleObjectImportRequest(cfg, login, pswd)
else:
raise NotImplementedError('Not supported req... | def factory(cfg, login, pswd, request_type) | Instantiate ImportRequest
:param cfg: request configuration, should consist of request description (url and parameters) and response for parsing result
:param login:
:param pswd:
:param request_type: TYPE_GET_SINGLE_OBJECT or TYPE_GET_LIST = 'list'
:return: ImportRequest instance | 2.846902 | 1.958899 | 1.453317 |
view_type = _view_type_for_element(element)
if view_type is None:
raise KeyError('No view type for %r' % element)
builder = view_widgets.get(view_type)
if builder is None:
raise KeyError('No widget type for %r' % view_type)
return builder(element) | def widget_for(element) | Create a widget for a schema item | 2.821028 | 2.792712 | 1.010139 |
# grid
x = np.arange(grid_size[0]).reshape(-1, 1)
y = np.arange(grid_size[1]).reshape(1, -1)
cx, cy = center
# sphere location
rpx = radius / pixel_size
r = rpx**2 - (x - cx)**2 - (y - cy)**2
# distance
z = np.zeros_like(r)
rvalid = r > 0
z[rvalid] = 2 * np.sqrt(r[rvalid... | def projection(radius=5e-6, sphere_index=1.339, medium_index=1.333,
wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80),
center=(39.5, 39.5)) | Optical path difference projection of a dielectric sphere
Parameters
----------
radius: float
Radius of the sphere [m]
sphere_index: float
Refractive index of the sphere
medium_index: float
Refractive index of the surrounding medium
wavelength: float
Vacuum wavel... | 3.165693 | 3.06177 | 1.033942 |
for obj in builder.get_objects():
if isinstance(obj, gtk.Window):
# first window
return obj | def get_first_builder_window(builder) | Get the first toplevel widget in a gtk.Builder hierarchy.
This is mostly used for guessing purposes, and an explicit naming is
always going to be a better situation. | 5.777647 | 5.191595 | 1.112885 |
self.display_widget = gtk.Window()
self.display_widget.add(self.widget)
self.display_widget.show()
BaseDelegate.show_and_run(self) | def show_and_run(self) | Show the main widget in a window and run the gtk loop | 5.421926 | 4.401563 | 1.231818 |
toplevel = builder.get_object(self.toplevel_name)
if not gobject.type_is_a(toplevel, gtk.Window):
toplevel = None
if toplevel is None:
toplevel = get_first_builder_window(builder)
return toplevel | def get_builder_toplevel(self, builder) | Get the toplevel widget from a gtk.Builder file.
The main view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, or not
a gtk.Window, the first toplevel window found in the gtk.Builder is
used. | 4.73876 | 3.335853 | 1.420554 |
if isinstance(call_cmd, basestring): # FIXME python 3 unsafe
call_cmd = [call_cmd]
return [self._trickle_cmd, "-s"] + self._settings.to_argument_list() + list(call_cmd) | def wrap_call(self, call_cmd) | "wraps" the call_cmd so it can be executed by subprocess.call (and related flavors) as "args" argument
:param call_cmd: original args like argument (string or sequence)
:return: a sequence with the original command "executed" under trickle | 8.776424 | 6.622436 | 1.325256 |
encoding = encoding or 'utf-8'
if is_unicode(s):
return s
elif is_strlike(s):
return s.decode(encoding, errors)
else:
if six.PY2:
return str(s).decode(encoding, errors)
else:
return str(s) | def to_unicode(s, encoding=None, errors='strict') | Make unicode string from any value
:param s:
:param encoding:
:param errors:
:return: unicode | 2.521109 | 2.874201 | 0.877151 |
encoding = encoding or 'utf-8'
if is_strlike(s):
if six.PY2:
return s.encode(encoding, errors) if isinstance(s, unicode) else s
else:
return s.decode(encoding, errors) if isinstance(s, bytes) else s
else:
return str(s) | def to_str(s, encoding=None, errors='strict') | Make str from any value
:param s:
:param encoding:
:param errors:
:return: str (not unicode in Python2, nor bytes in Python3) | 2.379532 | 2.479312 | 0.959755 |
encoding = encoding or 'utf-8'
if is_unicode(s):
return s.encode(encoding, errors)
elif is_strlike(s):
return s
else:
if six.PY2:
return str(s)
else:
return str(s).encode(encoding, errors) | def to_bytes(s, encoding=None, errors='strict') | Convert string to bytes. | 2.562769 | 2.436462 | 1.05184 |
assert unicode_width(fillchar) == 1, 'fillchar must be single-width char'
padding = fillchar * max(min_padding_length, width - unicode_width(left + right))
return left + padding + right | def edge_just(left, right, width, fillchar=' ', min_padding_length=1) | :param left:
:param right:
:param width:
:param fillchar:
:param min_padding_length: minimum padding length
:return: | 3.690026 | 3.553941 | 1.038291 |
i = 0
j = 0
for ch in s:
j += __unicode_width_mapping[east_asian_width(ch)]
if width < j:
break
i += 1
return s[:i] | def unicode_left(s, width) | Cut unicode string from left to fit a given width. | 4.396382 | 4.391335 | 1.001149 |
i = len(s)
j = 0
for ch in reversed(s):
j += __unicode_width_mapping[east_asian_width(ch)]
if width < j:
break
i -= 1
return s[i:] | def unicode_right(s, width) | Cut unicode string from right to fit a given width. | 4.286332 | 4.389036 | 0.9766 |
assert encoding_list, 'encodings must not be empty.'
xs = distinct(encoding_list if isinstance(encoding_list, list) else [encoding_list])
first_exp = None
for i, encoding in enumerate(xs):
try:
return data.decode(encoding)
except UnicodeDecodeError as e:
if ... | def unicode_decode(data, encoding_list) | Decode string data with one or more encodings, trying sequentially
:param data: bytes: encoded string data
:param encoding_list: list[string] or string: encoding names
:return: string: decoded string | 3.800964 | 3.610866 | 1.052646 |
delta = diff(a, b)
if not a:
return delta
for item in delta:
if isinstance(a[item], list):
if delta[item] == []:
delta[item] = {JSONUtils.DIFF_DELETE : a[item]}
elif isinstance(delta[item], dict):
... | def diff(a, b) | Compares JSON objects
:param a:
:param b:
:return: difference object a vs b | 3.279103 | 3.050187 | 1.07505 |
schema_dict = dict()
schema_dict.update(schema_nodes)
def cls_repr(self): # pragma: no cover
return "<{} instance at: 0x{:x}>".format(self.__class__, id(self))
def cls_str(self): # pragma: no cover
return "<{} instance, attributes:{}>".format(
self.__class__.__name... | def schema_factory(schema_name, **schema_nodes) | Schema Validation class factory.
Args:
schema_name(str): The namespace of the schema.
schema_nodes(dict): The attr_names / SchemaNodes mapping of schema.
Returns:
A Schema class.
Raises:
SchemaError, for bad attribute setting initialization.
Examples:
>>> fro... | 2.466511 | 2.293726 | 1.07533 |
if fields:
if not set(fields).issubset(self.data_nodes):
raise SchemaError('Invalid field for serialization: {}'.format(set(fields).difference(self.data_nodes)))
return OrderedDict([(k, getattr(self, k)) for k in fields])
return OrderedDict([(k, getattr... | def serialize(self, *fields) | Serialize Nodes and attributes | 2.972841 | 2.818539 | 1.054745 |
if debug:
log_level = logging.DEBUG
else:
log_level = logging.INFO
logger = logging.getLogger('exifread')
stream = Handler(log_level, debug, color)
logger.addHandler(stream)
logger.setLevel(log_level) | def setup_logger(debug, color) | Configure the logger. | 2.988688 | 3.022635 | 0.988769 |
for name, sanitize_fn in _SANITIZERS.items():
sanitize_fn(configuration, lambda warning, n=name: error_fn(n, warning)) | def sanitize(configuration, error_fn) | Run all availalbe sanitizers across a configuration.
Arguments:
configuration - a full project configuration
error_fn - A function to call if a sanitizer check fails. The function
takes a single argument: a description of the problem; provide
specifics if possible, including ... | 6.5184 | 6.963405 | 0.936094 |
deprecated_doc = "Deprecated"
if self.tip_info:
deprecated_doc = "{}: {}".format(deprecated_doc, self.tip_info)
if func_doc:
func_doc = "{}\n{}".format(deprecated_doc, func_doc)
return func_doc | def _update_doc(self, func_doc) | 更新文档信息,把原来的文档信息进行合并格式化,
即第一行为deprecated_doc(Deprecated: tip_info),下一行为原始func_doc | 3.592659 | 2.571086 | 1.397332 |
self.file.seek(self.offset + offset)
sliced = self.file.read(length)
if self.endian == 'I':
val = s2n_intel(sliced)
else:
val = s2n_motorola(sliced)
# Sign extension?
if signed:
msb = 1 << (8 * length - 1)
if va... | def s2n(self, offset, length, signed=0) | Convert slice to integer, based on sign and endian flags.
Usually this offset is assumed to be relative to the beginning of the
start of the EXIF information.
For some cameras that use relative tags, this offset may be relative
to some other starting point. | 3.541721 | 3.455689 | 1.024896 |
s = ''
for dummy in range(length):
if self.endian == 'I':
s += chr(offset & 0xFF)
else:
s = chr(offset & 0xFF) + s
offset = offset >> 8
return s | def n2s(self, offset, length) | Convert offset to string. | 3.380741 | 3.151569 | 1.072717 |
entries = self.s2n(ifd, 2)
next_ifd = self.s2n(ifd + 2 + 12 * entries, 4)
if next_ifd == ifd:
return 0
else:
return next_ifd | def _next_ifd(self, ifd) | Return the pointer to next IFD. | 4.937453 | 4.145602 | 1.19101 |
i = self._first_ifd()
ifds = []
while i:
ifds.append(i)
i = self._next_ifd(i)
return ifds | def list_ifd(self) | Return the list of IFDs in the header. | 3.450763 | 2.503808 | 1.378206 |
thumb = self.tags.get('Thumbnail Compression')
if not thumb or thumb.printable != 'Uncompressed TIFF':
return
entries = self.s2n(thumb_ifd, 2)
# this is header plus offset to IFD ...
if self.endian == 'M':
tiff = 'MM\x00*\x00\x00\x00\x08'
... | def extract_tiff_thumbnail(self, thumb_ifd) | Extract uncompressed TIFF thumbnail.
Take advantage of the pre-existing layout in the thumbnail IFD as
much as possible | 3.615975 | 3.57796 | 1.010625 |
thumb_offset = self.tags.get('Thumbnail JPEGInterchangeFormat')
if thumb_offset:
self.file.seek(self.offset + thumb_offset.values[0])
size = self.tags['Thumbnail JPEGInterchangeFormatLength'].values[0]
self.tags['JPEGThumbnail'] = self.file.read(size)
... | def extract_jpeg_thumbnail(self) | Extract JPEG thumbnail.
(Thankfully the JPEG data is stored as a unit.) | 3.420099 | 3.373741 | 1.013741 |
for i in range(1, len(value)):
tag = mn_tags.get(i, ('Unknown', ))
name = tag[0]
if len(tag) > 1:
val = tag[1].get(value[i], 'Unknown')
else:
val = value[i]
try:
logger.debug(" %s %s %s", i, name... | def _canon_decode_tag(self, value, mn_tags) | Decode Canon MakerNote tag based on offset within tag.
See http://www.burren.cx/david/canon.html by David Burren | 5.078336 | 4.932469 | 1.029573 |
model = self.tags.get('Image Model', None)
if not model:
return
model = str(model.values)
camera_info_tags = None
for (model_name_re, tag_desc) in makernote.canon.CAMERA_INFO_MODEL_MAP.items():
if re.search(model_name_re, model):
... | def _canon_decode_camera_info(self, camera_info_tag) | Decode the variable length encoded camera info section. | 3.464159 | 3.421317 | 1.012522 |
import sys
from argparse import ArgumentParser
from path_helpers import path
if args is None:
args = sys.argv
parser = ArgumentParser(description='Example app for drawing shapes from '
'dataframe, scaled to fit to GTK canvas while '
... | def parse_args(args=None) | Parses arguments, returns (options, args). | 6.030118 | 5.915438 | 1.019386 |
'''
.. versionchanged:: 0.20
Debounce window expose and resize handlers to improve
responsiveness.
.. versionchanged:: X.X.X
Call debounced `_on_expose_event` handler on _leading_ edge to make
UI update more responsive when, e.g., changing window ... | def create_ui(self) | .. versionchanged:: 0.20
Debounce window expose and resize handlers to improve
responsiveness.
.. versionchanged:: X.X.X
Call debounced `_on_expose_event` handler on _leading_ edge to make
UI update more responsive when, e.g., changing window focus.
... | 4.737257 | 2.193629 | 2.159552 |
'''
.. versionchanged:: 0.20
Do not log size change.
'''
if self._dirty_size is None:
if self._dirty_render:
self.render()
self._dirty_render = False
if self._dirty_draw:
self.draw()
self.... | def check_dirty(self) | .. versionchanged:: 0.20
Do not log size change. | 3.570344 | 2.437204 | 1.464935 |
'''
Called when size of drawing area changes.
'''
if event.x < 0 and event.y < 0:
# Widget has not been allocated a size yet, so do nothing.
return
self.resize(event.width, event.height) | def on_widget__configure_event(self, widget, event) | Called when size of drawing area changes. | 6.223897 | 4.508961 | 1.380339 |
'''
.. versionadded:: 0.20
Clear canvas, draw frame off screen, and mark dirty.
..notes::
This method is debounced to improve responsiveness.
'''
self._dirty_size = width, height
self.reset_canvas(width, height)
self.draw()
self._dirt... | def _resize(self, width, height) | .. versionadded:: 0.20
Clear canvas, draw frame off screen, and mark dirty.
..notes::
This method is debounced to improve responsiveness. | 10.472367 | 2.904369 | 3.605729 |
'''
.. versionchanged:: 0.20
Renamed from ``on_widget__expose_event`` to allow wrapping for
debouncing to improve responsiveness.
Called when drawing area is first displayed and, for example, when part
of drawing area is uncovered after being covered up by anothe... | def _on_expose_event(self, widget, event) | .. versionchanged:: 0.20
Renamed from ``on_widget__expose_event`` to allow wrapping for
debouncing to improve responsiveness.
Called when drawing area is first displayed and, for example, when part
of drawing area is uncovered after being covered up by another window.
C... | 14.46389 | 3.272826 | 4.419389 |
'''
Draw label on specified shape.
Parameters
----------
cairo_context : cairo.Context
Cairo context to draw text width. Can be preconfigured, for
example, to set font style, etc.
shape_id : str
Shape identifier.
text : str, o... | def render_label(self, cairo_context, shape_id, text=None, label_scale=.9) | Draw label on specified shape.
Parameters
----------
cairo_context : cairo.Context
Cairo context to draw text width. Can be preconfigured, for
example, to set font style, etc.
shape_id : str
Shape identifier.
text : str, optional
... | 3.543111 | 2.059609 | 1.720283 |
'''
.. versionchanged:: 0.21.2
Load the builder configuration file using :func:`pkgutil.getdata`,
which supports loading from `.zip` archives (e.g., in an app
packaged with Py2Exe).
'''
builder = gtk.Builder()
# Read glade file using `pkgutil` ... | def create_ui(self) | .. versionchanged:: 0.21.2
Load the builder configuration file using :func:`pkgutil.getdata`,
which supports loading from `.zip` archives (e.g., in an app
packaged with Py2Exe). | 2.495552 | 1.912983 | 1.304534 |
self.entry = gtk.Entry()
self.widget.add(self.entry) | def create_ui(self) | Create the user interface
create_ui is a method called during the Delegate's
initialisation process, to create, add to, or modify any UI
created by GtkBuilder files. | 9.292452 | 7.003205 | 1.326886 |
'''
-get row values for (form_name, row_id)
-set affected objectlist item attributes based on row values
'''
if form_name not in self._forms or row_id >= len(self):
return
combined_row = self[row_id]
form_row = combined_row.get_row_fields(form_name)
... | def _update_row_fields(self, form_name, row_id, attrs) | -get row values for (form_name, row_id)
-set affected objectlist item attributes based on row values | 5.530781 | 2.966797 | 1.864226 |
PARAM_FIELD_KEY = 'field.key'
PARAM_FIELD_ARRAY = 'field.array'
PARAM_FIELD_SINGLE = 'field.single'
field_key = params.get(PARAM_FIELD_KEY) if PARAM_FIELD_KEY in params else None
field_array = params.get(PARAM_FIELD_ARRAY)
field_single = params.get(PARAM_FIELD_SINGLE)
if not field_key... | def group_singles2array(input, **params) | Creates array of strings or ints from objects' fields
:param input: list of objects
:param params:
:return: list | 1.949778 | 2.006969 | 0.971503 |
PARAM_FIELD_KEY = 'field.key'
PARAM_FIELD_ARRAY = 'field.array'
PARAM_FIELD_SINGLE = 'field.single'
res = []
field_key = params.get(PARAM_FIELD_KEY) if PARAM_FIELD_KEY in params else None
field_array = params.get(PARAM_FIELD_ARRAY)
field_single = params.get(PARAM_FIELD_SINGLE)
for ... | def ungroup_array2singles(input, **params) | Creates list of objects from array of singles
:param input: list of strings or ints
:param params:
:return: | 2.21395 | 2.341356 | 0.945584 |
PARAM_WHERE = 'where'
return Converter.df2list(pd.DataFrame.from_records(input).query(params.get(PARAM_WHERE))) | def filter_set(input, **params) | Apply WHERE filter to input dataset
:param input:
:param params:
:return: filtered data | 13.594946 | 16.596569 | 0.819142 |
PARAM_SORT_FIELD = 'sort.field'
PARAM_SORT_ORDER = 'sort.order'
df = pd.DataFrame.from_records(input)
sort_field = params.get(PARAM_SORT_FIELD)
sort_order = params.get(PARAM_SORT_ORDER) if PARAM_SORT_ORDER in params else None
if sort_order:
df[sort_field] = df[sort_field].astype('c... | def sort_set(input, **params) | Apply sorting to input dataset
:param input:
:param params:
:return: sorted data | 2.32454 | 2.501208 | 0.929367 |
PARAM_FIELDS = 'fields'
def filter_fields(obj, fields):
return {k:v for k,v in obj.items() if k in fields}
if PARAM_FIELDS in params:
fields = params.get(PARAM_FIELDS)
if isinstance(input, list):
res = []
for row in input:
res.append(fil... | def copy(input, **params) | Copies input or input's selected fields
:param input:
:param params:
:return: input | 2.528906 | 2.338228 | 1.081548 |
PARAM_FIELD_TO_PARSE = 'input.field'
PARAM_PATTERN = 'pattern'
PARAM_OUTPUT = 'output'
OUT_DESC_FIELD = 'field'
OUT_DESC_IDX = 'idx'
OUT_DESC_TYPE = 'type'
res = []
regex = re.compile(params.get(PARAM_PATTERN))
field2parse = params.get(PARAM_FIELD_TO_PARSE)
out_desc = param... | def regexp(input, **params) | Parses input according to pattern
:param input:
:param params:
:return: | 3.141566 | 3.052763 | 1.029089 |
PARAM_FORMAT_STRING = 'format.string'
PARAM_FORMAT_INPUT = 'format.input'
PARAM_RESULT_FIELD = 'result.field'
IN_DESC_FIELD = 'field'
IN_DESC_TYPE = 'type'
format_string = params.get(PARAM_FORMAT_STRING)
format_inputs = params.get(PARAM_FORMAT_INPUT)
result_field = params.get(PARAM... | def format(input, **params) | Appends string formatted value to result
:param input:
:param params:
:return: | 2.810046 | 2.913025 | 0.964649 |
PARAM_COL_RIGHT = 'col.right'
PARAM_COL_LEFT = 'col.left'
PARAM_FIELD_JOIN = 'field.join'
right_df = pd.DataFrame.from_records(input[params.get(PARAM_COL_RIGHT)])
left_df = pd.DataFrame.from_records(input[params.get(PARAM_COL_LEFT)])
join_on = params.get(PARAM_FIELD_JOIN)
res = right_d... | def left_join(input, **params) | Left join transformation
:param input:
:param params:
:return: | 2.726231 | 2.859863 | 0.953273 |
res = []
for col in input:
res.extend(input[col])
return res | def union(input, **params) | Union transformation
:param input:
:param params:
:return: | 6.36986 | 6.376193 | 0.999007 |
PARAM_SOURCE = 'source'
SOURCE_COL = 'src.col'
SOURCE_FIELD = 'src.field'
PARAM_RESULT = 'result'
res = input[params.get(PARAM_RESULT)]
for src in params.get(PARAM_SOURCE):
res[src[SOURCE_FIELD]] = input[src[SOURCE_COL]][src[SOURCE_FIELD]]
return res | def update_doc(input, **params) | Updates document with value from another document
:param input:
:param params:
:return: | 4.627941 | 4.362014 | 1.060964 |
PARAM_TARGET = 'target'
PARAM_UPDATE = 'update'
SOURCE_TYPE = 'src.type'
SOURCE_COL = 'src.col'
SOURCE_FIELD = 'src.field'
DEST_FIELD = 'dest.field'
SOURCE_TYPE_DOC = 'doc'
SOURCE_TYPE_CONST = 'const'
CONST_VALUE = 'const.value'
update_list = params.get(PARAM_UPDATE)
re... | def update_col(input, **params) | Updates document with value from another document/collection/constant
:param input:
:param params:
:return: | 2.639899 | 2.420912 | 1.090456 |
PARAM_REPLACE_LIST = 'replace'
REPLACE_FIELD = 'field'
REPLACE_FIND_VALUE = 'value.to_find'
REPLACE_WITH_VALUE = 'value.replace_with'
replace_list = params.get(PARAM_REPLACE_LIST)
for row in input:
for replace in replace_list:
if row[replace[REPLACE_FIELD]] == replace[R... | def replace(input, **params) | Replaces field value
:param input:
:param params:
:return: | 3.19153 | 3.081981 | 1.035545 |
PARAM_RENAME_LIST = 'rename'
RENAME_SRC_FIELD = 'src.field'
RENAME_DEST_FIELD = 'dest.field'
rename_list = params.get(PARAM_RENAME_LIST)
for row in input:
for rename in rename_list:
row[rename[RENAME_DEST_FIELD]] = row[rename[RENAME_SRC_FIELD]]
row.pop(rename[RE... | def rename_fields(input, **params) | Renames field in collection
:param input:
:param params:
:return: | 2.671931 | 2.71021 | 0.985876 |
PARAM_SOURCE_FIELDS = 'src.fields'
PARAM_DEST_FIELD = 'dest.field'
field_list = params.get(PARAM_SOURCE_FIELDS)
for row in input:
res = []
for field in field_list:
res += row[field]
row[params.get(PARAM_DEST_FIELD)] = res
return input | def list_concat(input, **params) | Concatenates two or more lists and put result into dest field
:param input:
:param params:
:return: | 3.643281 | 3.372024 | 1.080443 |
return obj_for_name(cfg[Transformation.__CFG_KEY_TRANSFORMATION_CLASS])(
cfg[Transformation.CFG_KEY_TRANSFORMATION_CFG], src_db, dest_db) | def factory(cfg, src_db, dest_db) | Instantiate Transformation
:param cfg: transformation configuration
"class": "na3x.transformation.transformer.Col2XTransformation", <Transformation class>
"cfg": {
"src.db.load": {
"src": "sprint.backlog_links" <Collection(s) to be loaded>
},
"transform": {
"func": "ext.transfo... | 10.052809 | 7.945334 | 1.265247 |
self.__src = self._load(cfg[Transformation.__CFG_KEY_LOAD])
self.__transform(cfg[Transformation.__CFG_KEY_TRANSFORM])
self.__cleanup(cfg[Transformation.__CFG_KEY_CLEANUP])
self.__save(cfg[Transformation.__CFG_KEY_SAVE]) | def perform(self, cfg) | Performs transformation according to configuration
:param cfg: transformation configuration | 4.539667 | 4.078393 | 1.113102 |
destinations = self.destinations()
''' FIXME currently we return block whether it was correctly processed or not because MailSenders are chained
and not doing that would mean other wouldn't be able to try.'''
if not set(destinations).issubset(block.destinations):
... | def do_heavy_work(self, block) | Note: Expects Compressor Block like objects | 7.206644 | 7.250345 | 0.993973 |
if hasher is None:
hasher = hashlib.md5()
with open(file_path, 'rb') as f:
while True:
buffer = f.read(block_size)
if len(buffer) <= 0:
break
hasher.update(buffer)
return hasher.hexdigest() | def get_file_hash(file_path, block_size=1024, hasher=None) | Generate hash for given file
:param file_path: Path to file
:type file_path: str
:param block_size: Size of block to be read at once (default: 1024)
:type block_size: int
:param hasher: Use specific hasher, defaults to md5 (default: None)
:type hasher: _hashlib.HASH
:return: Hash of file
... | 1.582519 | 1.770202 | 0.893976 |
if not self._resources:
return self.resource_update_list()
res = []
with self._resource_lock:
for key in self._resources:
res.append((key, self._resources[key]['hash']))
return res | def resource_get_list(self) | Get list of this plugins resources and a hash to check for file changes
(It is recommended to keep a in memory representation of this struct
and not to generate it upon each request)
:return: List of supported resources and hashes
:rtype: list[(unicode, unicode)] | 4.48831 | 3.655901 | 1.227689 |
if not self._resource_path:
raise PluginException("No resource path set")
if not os.path.isdir(self._resource_path):
raise PluginException(
u"Resource path directory '{}' not found".format(
self._resource_path
)
... | def resource_update_list(self, reset=False) | Update internal struct of resource, hash list and get diff
(Warning: Resource names have to be unique!!)
:param reset: Should resources be rebuild from scratch (default: False)
:type reset: bool
:return: List of resources and hashes that changed
:rtype: list[(unicode, unicode)] | 2.435728 | 2.303388 | 1.057454 |
try:
with self._resource_lock:
res = self._resources[resource_name]
except KeyError:
return {}
return res | def resource_get(self, resource_name) | Return resource info
:param resource_name: Resource name as returned by resource_get_list()
:type resource_name: str
:return: Resource information (empty if not found)
name: Resource name
hash: Resource hash
path: Path to resource
checked: Last ti... | 3.832082 | 3.874077 | 0.98916 |
func_name = func.__name__
if func_name in self.exts:
raise DuplicatedExtension
self.exts[func_name] = func
return func | def di(self, func) | Decorator `@di`. | 3.921945 | 4.024589 | 0.974496 |
mode1 = {
0: 'Normal',
1: 'Unknown',
2: 'Fast',
3: 'Panorama',
}
mode2 = {
0: 'Non-panoramic',
1: 'Left to right',
2: 'Right to left',
3: 'Bottom to top',
4: 'Top to bottom',
}
if not v or (v[0] not in mode1 or v[2] not in ... | def special_mode(v) | decode Olympus SpecialMode tag in MakerNote | 3.079206 | 2.835661 | 1.085887 |
params = None
if random:
url = self.RANDOM_URL
else:
params = {'term': term}
url = self.API_URL
async with self.session.get(url, params=params) as response:
if response.status == 200:
response = await response.json... | async def _get(self, term: str = None, random: bool = False) -> dict | Helper method to reduce some boilerplate with :module:`aiohttp`.
Args:
term: The term to search for. Optional if doing a random search.
random: Whether the search should return a random word.
Returns:
The JSON response from the API.
... | 2.902217 | 2.413815 | 1.202336 |
resp = await self._get(term=term)
return Word(resp['list'][0]) | async def get_word(self, term: str) -> 'asyncurban.word.Word' | Gets the first matching word available.
Args:
term: The word to be defined.
Returns:
The closest matching :class:`Word` from UrbanDictionary.
Raises:
UrbanConnectionError: If the response status isn't ``200``.
WordNotFoun... | 5.883156 | 8.490975 | 0.692872 |
resp = await self._get(term=term)
words = resp['list']
return [Word(x) for x in words[:limit]] | async def search(self, term: str, limit: int = 3) -> 'List[Word]' | Performs a search for a term and returns a list of possible matching :class:`Word`
objects.
Args:
term: The term to be defined.
limit (optional): Max amount of results returned.
Defaults to 3.
Note:
The API will relay... | 4.490651 | 6.480146 | 0.692986 |
resp = await self._get(random=True)
return Word(resp['list'][0]) | async def get_random(self) -> Word | Gets a random word.
Returns:
A random :class:`Word`\.
Raises:
UrbanConnectionError: If the response status isn't ``200``. | 7.807116 | 9.804975 | 0.79624 |
return (await self._get(term=term))['list'][:limit] | async def search_raw(self, term: str, limit: int = 3) -> List[dict] | Performs a search for a term and returns the raw response.
Args:
term: The term to be defined.
limit: The maximum amount of results you'd like.
Defaults to 3.
Returns:
A list of :class:`dict`\s which contain word information. | 14.650249 | 22.092922 | 0.66312 |
source_content = self.load_content()
converted = {}
md_extenstions = [
'full_yaml_metadata',
'markdown.extensions.fenced_code',
]
md = markdown.Markdown(md_extenstions)
content = md.convert(source_content)
meta = md.Meta
... | def convert_content(self) -> dict | Convert content of source file into dict result. | 5.036943 | 4.719041 | 1.067366 |
self.log.info('starting the ``get`` method')
cachePath = self.settings["atlas archive path"]
global exposureIds
exposureIds, remaining = self._select_exposures_requiring_dophot_extraction(
batch=int(self.settings["dophot"]["batch size"]))
if remaining == 0:... | def get(self) | *match the orbfit predicted positions of known asteroids against the positions recored in the local cache of dophot files*
**Return:**
- None
**Usage:**
See class docstring | 6.20918 | 5.210108 | 1.191756 |
self.log.info(
'starting the ``_select_exposures_requiring_dophot_extraction`` method')
sqlQuery = u % locals()
rows = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.atlasMoversDBConn,
quiet=False
)
r... | def _select_exposures_requiring_dophot_extraction(
self,
batch=10) | * select exposures requiring dophot extraction*
**Key Arguments:**
- ``batch`` -- the batch size of dophot file to process
**Return:**
- ``expnames`` -- the names of the expsoures in the batch
- ``remaining`` -- the number of exposured remainging that require orbfit... | 4.884647 | 4.093139 | 1.193374 |
self.log.info(
'starting the ``_add_dophot_matches_to_database`` method')
insertList = []
for d in dophotMatches:
insertList += d
dbSettings = self.settings["database settings"]["atlasMovers"]
insert_list_of_dictionaries_into_database_tables(
... | def _add_dophot_matches_to_database(
self,
dophotMatches,
exposureIds) | *add dophot matches to database*
**Key Arguments:**
- ``dophotMatches`` -- a list of lists of dophot matches
- ``exposureIds`` -- the ATLAS exposure IDs these matches were found in
**Return:**
- None | 4.562728 | 4.348336 | 1.049304 |
self.log.info('starting the ``_add_value_to_dophot_table`` method')
# ADD SEPARATION RANK TO DOPHOT TABLE
sqlQuery = % locals()
writequery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.atlasMoversDBConn
)
sqlQuery = % local... | def _add_value_to_dophot_table(
self) | *add value to dophot table* | 4.073652 | 3.860833 | 1.055122 |
meth = getattr(obj, methname, None)
if meth is None or not callable(meth):
return
return meth(*args, **kwargs) | def _safe_call(obj, methname, *args, **kwargs) | Safely calls the method with the given methname on the given
object. Remaining positional and keyword arguments are passed to
the method. The return value is None, if the method is not
available, or the return value of the method. | 3.398614 | 3.161768 | 1.074909 |
for idx in range(len(self)):
resp = _safe_call(self[idx], 'proc_request', req)
# Do we have a response?
if resp is not None:
# Short-circuit
raise exc.ShortCircuit(self.proc_response(resp, idx - 1))
# Return the request we w... | def proc_request(self, req) | Pre-process a request through all processors in the stack, in
order. If any processor's proc_request() method returns a
value other than None, that value is treated as a response and
post-processed through the proc_response() methods of the
processors preceding that processor in the sta... | 6.450652 | 4.72943 | 1.363939 |
# If we're empty, bail out early
if not self:
return resp
# Select appropriate starting index
if startidx is None:
startidx = len(self)
for idx in range(startidx, -1, -1):
_safe_call(self[idx], 'proc_response', resp)
# Retu... | def proc_response(self, resp, startidx=None) | Post-process a response through all processors in the stack,
in reverse order. For convenience, returns the response
passed to the method.
The startidx argument is an internal interface only used by
the proc_request() and proc_exception() methods to process a
response through a... | 4.932287 | 4.59115 | 1.074303 |
# If we're empty, bail out early
if not self:
return
for idx in range(len(self), -1, -1):
# First, process the response...
if hasattr(exc_value, 'response'):
_safe_call(self[idx], 'proc_response', exc_value.response)
res... | def proc_exception(self, exc_type, exc_value, traceback) | Post-process an exception through all processors in the stack,
in reverse order. The exception so post-processed is any
exception raised by the Request object's proc_response()
method; if the httplib2.Http raises an exception, that
exception will not be processed by this mechanism.
... | 4.520189 | 3.897282 | 1.159831 |
puri = urisup.uri_help_split(uri)
#params = __dict_from_query(puri[QUERY])
params = {}
if puri[AUTHORITY]:
user, passwd, host, port = puri[AUTHORITY]
if user:
params['user'] = user
if passwd:
params['password'] = passwd
if host:
p... | def connect_by_uri(uri) | General URI syntax:
postgresql://user:passwd@host:port/db
NOTE: the authority and the path parts of the URI have precedence
over the query part, if an argument is given in both.
conv,quote_conv,cursorclass
are not (yet?) allowed as complex Python objects are needed, hard to
transmit withi... | 3.303485 | 3.271719 | 1.009709 |
previous = ""
current = os.getcwd()
while previous != current:
check_path = os.path.join(current, "build.cache")
if os.path.isfile(check_path):
return check_path
else:
previous = current
current = os.path.dirname(current)
raise Exception("... | def find_config() | Find a build cache somewhere in a parent directory. | 2.874818 | 2.410829 | 1.192461 |
if not cache_file:
cache_file = find_config()
cache_config = devpipeline_configure.parser.read_config(cache_file)
cache = devpipeline_configure.cache._CachedConfig(cache_config, cache_file)
if force or _is_outdated(cache_file, cache):
cache = devpipeline_configure.config.process_con... | def update_cache(force=False, cache_file=None) | Load a build cache, updating it if necessary.
A cache is considered outdated if any of its inputs have changed.
Arguments
force -- Consider a cache outdated regardless of whether its inputs have
been modified. | 4.521158 | 4.701823 | 0.961576 |
r = HttpRequestHandler(environ, start_response, Router).dispatch()
return r | def app(environ, start_response) | Function called by the WSGI server. | 13.273441 | 15.894878 | 0.835077 |
ips_created = 0
if len(ips) > 0:
# for each ip, check if already existent, if not add
for ip in ips:
(s0, s1, s2, s3) = ip.split('.')
(ip_db, is_ip_created) = IP.objects.get_or_create(seg_0=s0, seg_1=s1, seg_2=s2, seg_3=s3, )
... | def batch_add_ips(ips) | Adds the given list of IPs to the database if the IP is not already there.
:param ips: list of IPs
:return: number of created IPs
:type ips: list
:rtype: int | 3.100052 | 3.095897 | 1.001342 |
processed_ips = 0
ips = {}
# query for the IPs, also includes the starred IPs
for ip in IP.objects.raw(
'select distinct a.id, a.seg_0, a.seg_1, a.seg_2 '
'from ip_assembler_ip a, ip_assembler_ip b '
'where a.seg_0 = b.seg_0 and a.seg_1 = b.s... | def unify_ips() | Unifies the currently saved IPs.
Unification is based on last IP segment.
So if there are is e.g. 192.168.128.121 and 192.168.128.122 tthey will be merged to 192.168.128.121.
This is a little aggressive but the spammers are aggressive, too.
:return: number of merged ips
:rtype: i... | 2.317872 | 2.224694 | 1.041883 |
def wraps(func):
kwargs['process'] = func
job = type(job_name, (Job,), kwargs)
globals()[job_name] = job
return job
return wraps | def make_job(job_name, **kwargs) | Decorator to create a Job from a function.
Give a job name and add extra fields to the job.
@make_job("ExecuteDecJob",
command=mongoengine.StringField(required=True),
output=mongoengine.StringField(default=None))
def execute(job: Job):
job.log_info('E... | 4.460162 | 4.524817 | 0.985711 |
writer = output.buffer if hasattr(output, 'buffer') else output
# When the input type is bytes, verify it can be decoded with the specified encoding.
decoded = str_or_bytes if is_unicode(str_or_bytes) else to_unicode(str_or_bytes, encoding, errors)
encoded = to_bytes(decoded, encoding, errors)
... | def print_safe(str_or_bytes, encoding='utf-8', errors='ignore', output=sys.stdout, newline='\n') | Print unicode or bytes universally.
:param str_or_bytes: string
:param encoding: encoding
:param output: output file handler
:param errors: error handling scheme. Refer to codecs.register_error. | 3.510055 | 3.721403 | 0.943207 |
assert hasattr(msg_info, 'files_containers_id')
with self._session_resource as session:
session.execute(
update(FilesDestinations)
.where(FilesDestinations.file_containers_id == msg_info.files_containers_id)
.values(verificatio... | def set_verified(self, msg_info) | expects "msg_info" to have the field 'files_containers_id'
This call already executes "update_last_checked_time" so it doesn't need to be called separately | 5.398831 | 3.576943 | 1.509342 |
results = {
'BAD': -1,
'NOT_FCB': 0,
'OK': 1
}
for part in msg_info.msg_body.walk():
if part.is_multipart():
continue
if part.get_content_type() == 'text/plain':
if self._is_conten... | def is_uploaded_container(self, msg_info) | returns 0 if it doesn't correspond to an uploaded container
-1 if it corresponds to an uploaded container but it is corrupted
1 if it corresponds to an uploaded container and is OK | 2.881049 | 2.803512 | 1.027657 |
self.log.info('starting the ``get`` method')
if singleExposure:
batchSize = 1
else:
batchSize = int(self.settings["orbfit"]["batch size"])
exposureCount = 1
while exposureCount > 0:
expsoureObjects, astorbString, exposureCount = self... | def get(self,
singleExposure=False) | *get the orbfitPositions object*
**Key Arguments:**
- ``singleExposure`` -- only execute fot a single exposure (useful for debugging)
**Return:**
- None
**Usage:**
See class docstring | 4.572109 | 4.318405 | 1.05875 |
self.log.info(
'starting the ``_get_exposures_requiring_orbfit_positions`` method')
if self.dev_flag == True:
dev_flag = " and dev_flag = 1"
else:
dev_flag = ""
sqlQuery = u % locals()
rows = readquery(
log=self.log,
... | def _get_exposures_requiring_orbfit_positions(
self,
batchSize=25) | *get next batch of exposures requiring orbfit positions*
**Key Arguments:**
- ``batchSize`` -- number of exposures to process per batch
**Return:**
- ``expsoureObjects`` -- a dictionary with exposure names as keys and a dictionary of exposure ra, dec and moving object names/mpc... | 3.35807 | 2.896896 | 1.159196 |
self.log.info('starting the ``_get_orbfit_positions`` method')
# WRITE THE CUSTOM ORBFIT DATABASE TO FILE
now = datetime.now()
astorbFilepath = now.strftime("/tmp/astorb-%Y%m%dt%H%M%S%f.dat")
try:
self.log.debug("attempting to open the file %s" %
... | def _get_orbfit_positions(
self,
expsoureObjects,
astorbString) | * get orbfit positions*
**Key Arguments:**
- ``expsoureObjects`` -- a dictionary with exposure names as keys and a dictionary of exposure ra, dec and moving object names/mpc number as values
- ``astorbString`` -- as string of the object orbital elements to be used with orbfit
*... | 2.935494 | 2.660019 | 1.103561 |
self.log.info(
'starting the ``_match_objects_against_atlas_footprint`` method')
# GET THE ORBFIT MAG LIMIT
magLimit = float(self.settings["orbfit"]["magnitude limit"])
tileSide = float(self.settings["orbfit"]["atlas exposure match side"])
pi = (4 * math.at... | def _match_objects_against_atlas_footprint(
self,
orbfitEph,
ra,
dec) | *match the orbfit generated object positions against atlas exposure footprint*
**Key Arguments:**
- ``orbfitEph`` -- the orbfit ephemerides
- ``ra`` -- the ATLAS exposure RA (degrees)
- ``dec`` -- the ATLAS exposure DEC (degrees)
**Return:**
- ``matchedE... | 3.167514 | 3.064259 | 1.033697 |
self.log.info('starting the ``_add_orbfit_eph_to_database`` method')
dbSettings = self.settings["database settings"]["atlasMovers"]
insert_list_of_dictionaries_into_database_tables(
dbConn=self.atlasMoversDBConn,
log=self.log,
dictList=orbfitMatches... | def _add_orbfit_eph_to_database(
self,
orbfitMatches,
expsoureObjects) | * add orbfit eph to database*
**Key Arguments:**
- ``orbfitMatches`` -- all of the ephemerides generated by Orbfit that match against the exact ATLAS exposure footprint
- ``expsoureObjects`` -- the dictionary of original exposure objects
**Return:**
- None | 3.352726 | 3.132043 | 1.07046 |
'''
Send an abort sequence using CAN bytes.
'''
for counter in xrange(0, count):
self.putc(CAN, timeout) | def abort(self, count=2, timeout=60) | Send an abort sequence using CAN bytes. | 20.616655 | 8.289763 | 2.487002 |
'''
Receive a stream via the XMODEM protocol.
>>> stream = file('/etc/issue', 'wb')
>>> print modem.recv(stream)
2342
Returns the number of bytes received on success or ``None`` in case of
failure.
'''
# initiate protocol
err... | def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0) | Receive a stream via the XMODEM protocol.
>>> stream = file('/etc/issue', 'wb')
>>> print modem.recv(stream)
2342
Returns the number of bytes received on success or ``None`` in case of
failure. | 3.067337 | 2.762677 | 1.110277 |
'''
Calculate the Cyclic Redundancy Check for a given block of data, can
also be used to update a CRC.
>>> crc = modem.calc_crc('hello')
>>> crc = modem.calc_crc('world', crc)
>>> hex(crc)
'0xd5e3'
'''
for char in data:
... | def calc_crc(self, data, crc=0) | Calculate the Cyclic Redundancy Check for a given block of data, can
also be used to update a CRC.
>>> crc = modem.calc_crc('hello')
>>> crc = modem.calc_crc('world', crc)
>>> hex(crc)
'0xd5e3' | 3.726435 | 1.70162 | 2.189933 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.