nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
home-assistant-libs/pytradfri
ef2614b0ccdf628abc3b9559dc00b95ec6e4bd72
pytradfri/group.py
python
Group.remove_member
(self, memberid)
return self._gateway.remove_group_member( {ATTR_GROUP_ID: self.id, ATTR_ID: [memberid]} )
Remove a member from this group.
Remove a member from this group.
[ "Remove", "a", "member", "from", "this", "group", "." ]
def remove_member(self, memberid): """Remove a member from this group.""" return self._gateway.remove_group_member( {ATTR_GROUP_ID: self.id, ATTR_ID: [memberid]} )
[ "def", "remove_member", "(", "self", ",", "memberid", ")", ":", "return", "self", ".", "_gateway", ".", "remove_group_member", "(", "{", "ATTR_GROUP_ID", ":", "self", ".", "id", ",", "ATTR_ID", ":", "[", "memberid", "]", "}", ")" ]
https://github.com/home-assistant-libs/pytradfri/blob/ef2614b0ccdf628abc3b9559dc00b95ec6e4bd72/pytradfri/group.py#L83-L87
openstack/swift
b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100
swift/proxy/controllers/obj.py
python
ObjectControllerRouter.register
(cls, policy_type)
return register_wrapper
Decorator for Storage Policy implementations to register their ObjectController implementations. This also fills in a policy_type attribute on the class.
Decorator for Storage Policy implementations to register their ObjectController implementations.
[ "Decorator", "for", "Storage", "Policy", "implementations", "to", "register", "their", "ObjectController", "implementations", "." ]
def register(cls, policy_type): """ Decorator for Storage Policy implementations to register their ObjectController implementations. This also fills in a policy_type attribute on the class. """ def register_wrapper(controller_cls): if policy_type in cls.policy_type_to_controller_map: raise PolicyError( '%r is already registered for the policy_type %r' % ( cls.policy_type_to_controller_map[policy_type], policy_type)) cls.policy_type_to_controller_map[policy_type] = controller_cls controller_cls.policy_type = policy_type return controller_cls return register_wrapper
[ "def", "register", "(", "cls", ",", "policy_type", ")", ":", "def", "register_wrapper", "(", "controller_cls", ")", ":", "if", "policy_type", "in", "cls", ".", "policy_type_to_controller_map", ":", "raise", "PolicyError", "(", "'%r is already registered for the policy...
https://github.com/openstack/swift/blob/b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100/swift/proxy/controllers/obj.py#L136-L152
weewx/weewx
cb594fce224560bd8696050fc5c7843c7839320e
bin/weecfg/database.py
python
CalcMissing._progress
(message, overprint=True)
Utility function to show our progress.
Utility function to show our progress.
[ "Utility", "function", "to", "show", "our", "progress", "." ]
def _progress(message, overprint=True): """Utility function to show our progress.""" if overprint: print(message + "\r", end='') else: print(message) sys.stdout.flush()
[ "def", "_progress", "(", "message", ",", "overprint", "=", "True", ")", ":", "if", "overprint", ":", "print", "(", "message", "+", "\"\\r\"", ",", "end", "=", "''", ")", "else", ":", "print", "(", "message", ")", "sys", ".", "stdout", ".", "flush", ...
https://github.com/weewx/weewx/blob/cb594fce224560bd8696050fc5c7843c7839320e/bin/weecfg/database.py#L576-L583
msracver/Deformable-ConvNets
6aeda878a95bcb55eadffbe125804e730574de8d
lib/rpn/rpn.py
python
assign_anchor
(feat_shape, gt_boxes, im_info, cfg, feat_stride=16, scales=(8, 16, 32), ratios=(0.5, 1, 2), allowed_border=0)
return label
assign ground truth boxes to anchor positions :param feat_shape: infer output shape :param gt_boxes: assign ground truth :param im_info: filter out anchors overlapped with edges :param feat_stride: anchor position step :param scales: used to generate anchors, affects num_anchors (per location) :param ratios: aspect ratios of generated anchors :param allowed_border: filter out anchors with edge overlap > allowed_border :return: dict of label 'label': of shape (batch_size, 1) <- (batch_size, num_anchors, feat_height, feat_width) 'bbox_target': of shape (batch_size, num_anchors * 4, feat_height, feat_width) 'bbox_inside_weight': *todo* mark the assigned anchors 'bbox_outside_weight': used to normalize the bbox_loss, all weights sums to RPN_POSITIVE_WEIGHT
assign ground truth boxes to anchor positions :param feat_shape: infer output shape :param gt_boxes: assign ground truth :param im_info: filter out anchors overlapped with edges :param feat_stride: anchor position step :param scales: used to generate anchors, affects num_anchors (per location) :param ratios: aspect ratios of generated anchors :param allowed_border: filter out anchors with edge overlap > allowed_border :return: dict of label 'label': of shape (batch_size, 1) <- (batch_size, num_anchors, feat_height, feat_width) 'bbox_target': of shape (batch_size, num_anchors * 4, feat_height, feat_width) 'bbox_inside_weight': *todo* mark the assigned anchors 'bbox_outside_weight': used to normalize the bbox_loss, all weights sums to RPN_POSITIVE_WEIGHT
[ "assign", "ground", "truth", "boxes", "to", "anchor", "positions", ":", "param", "feat_shape", ":", "infer", "output", "shape", ":", "param", "gt_boxes", ":", "assign", "ground", "truth", ":", "param", "im_info", ":", "filter", "out", "anchors", "overlapped", ...
def assign_anchor(feat_shape, gt_boxes, im_info, cfg, feat_stride=16, scales=(8, 16, 32), ratios=(0.5, 1, 2), allowed_border=0): """ assign ground truth boxes to anchor positions :param feat_shape: infer output shape :param gt_boxes: assign ground truth :param im_info: filter out anchors overlapped with edges :param feat_stride: anchor position step :param scales: used to generate anchors, affects num_anchors (per location) :param ratios: aspect ratios of generated anchors :param allowed_border: filter out anchors with edge overlap > allowed_border :return: dict of label 'label': of shape (batch_size, 1) <- (batch_size, num_anchors, feat_height, feat_width) 'bbox_target': of shape (batch_size, num_anchors * 4, feat_height, feat_width) 'bbox_inside_weight': *todo* mark the assigned anchors 'bbox_outside_weight': used to normalize the bbox_loss, all weights sums to RPN_POSITIVE_WEIGHT """ def _unmap(data, count, inds, fill=0): """" unmap a subset inds of data into original data of size count """ if len(data.shape) == 1: ret = np.empty((count,), dtype=np.float32) ret.fill(fill) ret[inds] = data else: ret = np.empty((count,) + data.shape[1:], dtype=np.float32) ret.fill(fill) ret[inds, :] = data return ret DEBUG = False im_info = im_info[0] scales = np.array(scales, dtype=np.float32) base_anchors = generate_anchors(base_size=feat_stride, ratios=list(ratios), scales=scales) num_anchors = base_anchors.shape[0] feat_height, feat_width = feat_shape[-2:] if DEBUG: print 'anchors:' print base_anchors print 'anchor shapes:' print np.hstack((base_anchors[:, 2::4] - base_anchors[:, 0::4], base_anchors[:, 3::4] - base_anchors[:, 1::4])) print 'im_info', im_info print 'height', feat_height, 'width', feat_width print 'gt_boxes shape', gt_boxes.shape print 'gt_boxes', gt_boxes # 1. generate proposals from bbox deltas and shifted anchors shift_x = np.arange(0, feat_width) * feat_stride shift_y = np.arange(0, feat_height) * feat_stride shift_x, shift_y = np.meshgrid(shift_x, shift_y) shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose() # add A anchors (1, A, 4) to # cell K shifts (K, 1, 4) to get # shift anchors (K, A, 4) # reshape to (K*A, 4) shifted anchors A = num_anchors K = shifts.shape[0] all_anchors = base_anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2)) all_anchors = all_anchors.reshape((K * A, 4)) total_anchors = int(K * A) # only keep anchors inside the image inds_inside = np.where((all_anchors[:, 0] >= -allowed_border) & (all_anchors[:, 1] >= -allowed_border) & (all_anchors[:, 2] < im_info[1] + allowed_border) & (all_anchors[:, 3] < im_info[0] + allowed_border))[0] if DEBUG: print 'total_anchors', total_anchors print 'inds_inside', len(inds_inside) # keep only inside anchors anchors = all_anchors[inds_inside, :] if DEBUG: print 'anchors shape', anchors.shape # label: 1 is positive, 0 is negative, -1 is dont care labels = np.empty((len(inds_inside),), dtype=np.float32) labels.fill(-1) if gt_boxes.size > 0: # overlap between the anchors and the gt boxes # overlaps (ex, gt) overlaps = bbox_overlaps(anchors.astype(np.float), gt_boxes.astype(np.float)) argmax_overlaps = overlaps.argmax(axis=1) max_overlaps = overlaps[np.arange(len(inds_inside)), argmax_overlaps] gt_argmax_overlaps = overlaps.argmax(axis=0) gt_max_overlaps = overlaps[gt_argmax_overlaps, np.arange(overlaps.shape[1])] gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0] if not cfg.TRAIN.RPN_CLOBBER_POSITIVES: # assign bg labels first so that positive labels can clobber them labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0 # fg label: for each gt, anchor with highest overlap labels[gt_argmax_overlaps] = 1 # fg label: above threshold IoU labels[max_overlaps >= cfg.TRAIN.RPN_POSITIVE_OVERLAP] = 1 if cfg.TRAIN.RPN_CLOBBER_POSITIVES: # assign bg labels last so that negative labels can clobber positives labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0 else: labels[:] = 0 # subsample positive labels if we have too many num_fg = int(cfg.TRAIN.RPN_FG_FRACTION * cfg.TRAIN.RPN_BATCH_SIZE) fg_inds = np.where(labels == 1)[0] if len(fg_inds) > num_fg: disable_inds = npr.choice(fg_inds, size=(len(fg_inds) - num_fg), replace=False) if DEBUG: disable_inds = fg_inds[:(len(fg_inds) - num_fg)] labels[disable_inds] = -1 # subsample negative labels if we have too many num_bg = cfg.TRAIN.RPN_BATCH_SIZE - np.sum(labels == 1) bg_inds = np.where(labels == 0)[0] if len(bg_inds) > num_bg: disable_inds = npr.choice(bg_inds, size=(len(bg_inds) - num_bg), replace=False) if DEBUG: disable_inds = bg_inds[:(len(bg_inds) - num_bg)] labels[disable_inds] = -1 bbox_targets = np.zeros((len(inds_inside), 4), dtype=np.float32) if gt_boxes.size > 0: bbox_targets[:] = bbox_transform(anchors, gt_boxes[argmax_overlaps, :4]) bbox_weights = np.zeros((len(inds_inside), 4), dtype=np.float32) bbox_weights[labels == 1, :] = np.array(cfg.TRAIN.RPN_BBOX_WEIGHTS) if DEBUG: _sums = bbox_targets[labels == 1, :].sum(axis=0) _squared_sums = (bbox_targets[labels == 1, :] ** 2).sum(axis=0) _counts = np.sum(labels == 1) means = _sums / (_counts + 1e-14) stds = np.sqrt(_squared_sums / _counts - means ** 2) print 'means', means print 'stdevs', stds # map up to original set of anchors labels = _unmap(labels, total_anchors, inds_inside, fill=-1) bbox_targets = _unmap(bbox_targets, total_anchors, inds_inside, fill=0) bbox_weights = _unmap(bbox_weights, total_anchors, inds_inside, fill=0) if DEBUG: print 'rpn: max max_overlaps', np.max(max_overlaps) print 'rpn: num_positives', np.sum(labels == 1) print 'rpn: num_negatives', np.sum(labels == 0) _fg_sum = np.sum(labels == 1) _bg_sum = np.sum(labels == 0) _count = 1 print 'rpn: num_positive avg', _fg_sum / _count print 'rpn: num_negative avg', _bg_sum / _count labels = labels.reshape((1, feat_height, feat_width, A)).transpose(0, 3, 1, 2) labels = labels.reshape((1, A * feat_height * feat_width)) bbox_targets = bbox_targets.reshape((1, feat_height, feat_width, A * 4)).transpose(0, 3, 1, 2) bbox_weights = bbox_weights.reshape((1, feat_height, feat_width, A * 4)).transpose((0, 3, 1, 2)) label = {'label': labels, 'bbox_target': bbox_targets, 'bbox_weight': bbox_weights} return label
[ "def", "assign_anchor", "(", "feat_shape", ",", "gt_boxes", ",", "im_info", ",", "cfg", ",", "feat_stride", "=", "16", ",", "scales", "=", "(", "8", ",", "16", ",", "32", ")", ",", "ratios", "=", "(", "0.5", ",", "1", ",", "2", ")", ",", "allowed...
https://github.com/msracver/Deformable-ConvNets/blob/6aeda878a95bcb55eadffbe125804e730574de8d/lib/rpn/rpn.py#L78-L241
SanPen/GridCal
d3f4566d2d72c11c7e910c9d162538ef0e60df31
src/GridCal/Engine/Devices/upfc.py
python
UPFC.plot_profiles
(self, time_series=None, my_index=0, show_fig=True)
Plot the time series results of this object :param time_series: TimeSeries Instance :param my_index: index of this object in the simulation :param show_fig: Show the figure?
Plot the time series results of this object :param time_series: TimeSeries Instance :param my_index: index of this object in the simulation :param show_fig: Show the figure?
[ "Plot", "the", "time", "series", "results", "of", "this", "object", ":", "param", "time_series", ":", "TimeSeries", "Instance", ":", "param", "my_index", ":", "index", "of", "this", "object", "in", "the", "simulation", ":", "param", "show_fig", ":", "Show", ...
def plot_profiles(self, time_series=None, my_index=0, show_fig=True): """ Plot the time series results of this object :param time_series: TimeSeries Instance :param my_index: index of this object in the simulation :param show_fig: Show the figure? """ if time_series is not None: fig = plt.figure(figsize=(12, 8)) ax_1 = fig.add_subplot(211) ax_2 = fig.add_subplot(212, sharex=ax_1) x = time_series.results.time # loading y = time_series.results.loading.real * 100.0 df = pd.DataFrame(data=y[:, my_index], index=x, columns=[self.name]) ax_1.set_title('Loading', fontsize=14) ax_1.set_ylabel('Loading [%]', fontsize=11) df.plot(ax=ax_1) # losses y = np.abs(time_series.results.losses) df = pd.DataFrame(data=y[:, my_index], index=x, columns=[self.name]) ax_2.set_title('Losses', fontsize=14) ax_2.set_ylabel('Losses [MVA]', fontsize=11) df.plot(ax=ax_2) plt.legend() fig.suptitle(self.name, fontsize=20) if show_fig: plt.show()
[ "def", "plot_profiles", "(", "self", ",", "time_series", "=", "None", ",", "my_index", "=", "0", ",", "show_fig", "=", "True", ")", ":", "if", "time_series", "is", "not", "None", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "12", ...
https://github.com/SanPen/GridCal/blob/d3f4566d2d72c11c7e910c9d162538ef0e60df31/src/GridCal/Engine/Devices/upfc.py#L235-L269
pyqt/examples
843bb982917cecb2350b5f6d7f42c9b7fb142ec1
src/pyqt-official/ipc/sharedmemory/sharedmemory.py
python
Dialog.loadFromMemory
(self)
This slot function is called in the second Dialog process, when the user presses the "Load Image from Shared Memory" button. First, it attaches the process to the shared memory segment created by the first Dialog process. Then it locks the segment for exclusive access, copies the image data from the segment into a QBuffer, and streams the QBuffer into a QImage. Then it unlocks the shared memory segment, detaches from it, and finally displays the QImage in the Dialog.
This slot function is called in the second Dialog process, when the user presses the "Load Image from Shared Memory" button. First, it attaches the process to the shared memory segment created by the first Dialog process. Then it locks the segment for exclusive access, copies the image data from the segment into a QBuffer, and streams the QBuffer into a QImage. Then it unlocks the shared memory segment, detaches from it, and finally displays the QImage in the Dialog.
[ "This", "slot", "function", "is", "called", "in", "the", "second", "Dialog", "process", "when", "the", "user", "presses", "the", "Load", "Image", "from", "Shared", "Memory", "button", ".", "First", "it", "attaches", "the", "process", "to", "the", "shared", ...
def loadFromMemory(self): """ This slot function is called in the second Dialog process, when the user presses the "Load Image from Shared Memory" button. First, it attaches the process to the shared memory segment created by the first Dialog process. Then it locks the segment for exclusive access, copies the image data from the segment into a QBuffer, and streams the QBuffer into a QImage. Then it unlocks the shared memory segment, detaches from it, and finally displays the QImage in the Dialog. """ if not self.sharedMemory.attach(): self.ui.label.setText( "Unable to attach to shared memory segment.\nLoad an " "image first.") return buf = QBuffer() ins = QDataStream(buf) image = QImage() self.sharedMemory.lock() buf.setData(self.sharedMemory.constData()) buf.open(QBuffer.ReadOnly) ins >> image self.sharedMemory.unlock() self.sharedMemory.detach() self.ui.label.setPixmap(QPixmap.fromImage(image))
[ "def", "loadFromMemory", "(", "self", ")", ":", "if", "not", "self", ".", "sharedMemory", ".", "attach", "(", ")", ":", "self", ".", "ui", ".", "label", ".", "setText", "(", "\"Unable to attach to shared memory segment.\\nLoad an \"", "\"image first.\"", ")", "r...
https://github.com/pyqt/examples/blob/843bb982917cecb2350b5f6d7f42c9b7fb142ec1/src/pyqt-official/ipc/sharedmemory/sharedmemory.py#L135-L162
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/distlib/wheel.py
python
Wheel.build
(self, paths, tags=None, wheel_version=None)
return pathname
Build a wheel from files in specified paths, and use any specified tags when determining the name of the wheel.
Build a wheel from files in specified paths, and use any specified tags when determining the name of the wheel.
[ "Build", "a", "wheel", "from", "files", "in", "specified", "paths", "and", "use", "any", "specified", "tags", "when", "determining", "the", "name", "of", "the", "wheel", "." ]
def build(self, paths, tags=None, wheel_version=None): """ Build a wheel from files in specified paths, and use any specified tags when determining the name of the wheel. """ if tags is None: tags = {} libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0] if libkey == 'platlib': is_pure = 'false' default_pyver = [IMPVER] default_abi = [ABI] default_arch = [ARCH] else: is_pure = 'true' default_pyver = [PYVER] default_abi = ['none'] default_arch = ['any'] self.pyver = tags.get('pyver', default_pyver) self.abi = tags.get('abi', default_abi) self.arch = tags.get('arch', default_arch) libdir = paths[libkey] name_ver = '%s-%s' % (self.name, self.version) data_dir = '%s.data' % name_ver info_dir = '%s.dist-info' % name_ver archive_paths = [] # First, stuff which is not in site-packages for key in ('data', 'headers', 'scripts'): if key not in paths: continue path = paths[key] if os.path.isdir(path): for root, dirs, files in os.walk(path): for fn in files: p = fsdecode(os.path.join(root, fn)) rp = os.path.relpath(p, path) ap = to_posix(os.path.join(data_dir, key, rp)) archive_paths.append((ap, p)) if key == 'scripts' and not p.endswith('.exe'): with open(p, 'rb') as f: data = f.read() data = self.process_shebang(data) with open(p, 'wb') as f: f.write(data) # Now, stuff which is in site-packages, other than the # distinfo stuff. path = libdir distinfo = None for root, dirs, files in os.walk(path): if root == path: # At the top level only, save distinfo for later # and skip it for now for i, dn in enumerate(dirs): dn = fsdecode(dn) if dn.endswith('.dist-info'): distinfo = os.path.join(root, dn) del dirs[i] break assert distinfo, '.dist-info directory expected, not found' for fn in files: # comment out next suite to leave .pyc files in if fsdecode(fn).endswith(('.pyc', '.pyo')): continue p = os.path.join(root, fn) rp = to_posix(os.path.relpath(p, path)) archive_paths.append((rp, p)) # Now distinfo. Assumed to be flat, i.e. os.listdir is enough. files = os.listdir(distinfo) for fn in files: if fn not in ('RECORD', 'INSTALLER', 'SHARED', 'WHEEL'): p = fsdecode(os.path.join(distinfo, fn)) ap = to_posix(os.path.join(info_dir, fn)) archive_paths.append((ap, p)) wheel_metadata = [ 'Wheel-Version: %d.%d' % (wheel_version or self.wheel_version), 'Generator: distlib %s' % __version__, 'Root-Is-Purelib: %s' % is_pure, ] for pyver, abi, arch in self.tags: wheel_metadata.append('Tag: %s-%s-%s' % (pyver, abi, arch)) p = os.path.join(distinfo, 'WHEEL') with open(p, 'w') as f: f.write('\n'.join(wheel_metadata)) ap = to_posix(os.path.join(info_dir, 'WHEEL')) archive_paths.append((ap, p)) # Now, at last, RECORD. # Paths in here are archive paths - nothing else makes sense. self.write_records((distinfo, info_dir), libdir, archive_paths) # Now, ready to build the zip file pathname = os.path.join(self.dirname, self.filename) self.build_zip(pathname, archive_paths) return pathname
[ "def", "build", "(", "self", ",", "paths", ",", "tags", "=", "None", ",", "wheel_version", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "{", "}", "libkey", "=", "list", "(", "filter", "(", "lambda", "o", ":", "o", "in", ...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/distlib/wheel.py#L326-L428
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/lib/pyxmpp/jabber/dataforms.py
python
Form.__init__
(self, xmlnode_or_type = "form", title = None, instructions = None, fields = None, reported_fields = None, items = None, strict=True)
Initialize a `Form` object. :Parameters: - `xmlnode_or_type`: XML element to parse or a form title. - `title`: form title. - `instructions`: instructions for the form. - `fields`: form fields. - `reported_fields`: fields reported in multi-item data. - `items`: items of multi-item data. :Types: - `xmlnode_or_type`: `libxml2.xmlNode` or `str` - `title`: `unicode` - `instructions`: `unicode` - `fields`: `list` of `Field` - `reported_fields`: `list` of `Field` - `items`: `list` of `Item`
Initialize a `Form` object.
[ "Initialize", "a", "Form", "object", "." ]
def __init__(self, xmlnode_or_type = "form", title = None, instructions = None, fields = None, reported_fields = None, items = None, strict=True): """Initialize a `Form` object. :Parameters: - `xmlnode_or_type`: XML element to parse or a form title. - `title`: form title. - `instructions`: instructions for the form. - `fields`: form fields. - `reported_fields`: fields reported in multi-item data. - `items`: items of multi-item data. :Types: - `xmlnode_or_type`: `libxml2.xmlNode` or `str` - `title`: `unicode` - `instructions`: `unicode` - `fields`: `list` of `Field` - `reported_fields`: `list` of `Field` - `items`: `list` of `Item` """ if isinstance(xmlnode_or_type, libxml2.xmlNode): self.__from_xml(xmlnode_or_type, strict) elif xmlnode_or_type not in self.allowed_types: raise ValueError, "Form type %r not allowed." % (xmlnode_or_type,) else: self.type = xmlnode_or_type self.title = title self.instructions = instructions if fields: self.fields = list(fields) else: self.fields = [] if reported_fields: self.reported_fields = list(reported_fields) else: self.reported_fields = [] if items: self.items = list(items) else: self.items = []
[ "def", "__init__", "(", "self", ",", "xmlnode_or_type", "=", "\"form\"", ",", "title", "=", "None", ",", "instructions", "=", "None", ",", "fields", "=", "None", ",", "reported_fields", "=", "None", ",", "items", "=", "None", ",", "strict", "=", "True", ...
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/lib/pyxmpp/jabber/dataforms.py#L490-L528
stevearc/dql
9666cfba19773c20c7b4be29adc7d6179cf00d44
dql/cli.py
python
DQLClient.completedefault
(self, text, line, *_)
Autocomplete table names in queries
Autocomplete table names in queries
[ "Autocomplete", "table", "names", "in", "queries" ]
def completedefault(self, text, line, *_): """Autocomplete table names in queries""" tokens = line.split() try: before = tokens[-2] complete = before.lower() in ("from", "update", "table", "into") if tokens[0].lower() == "dump": complete = True if complete: return [ t + " " for t in self.engine.cached_descriptions if t.startswith(text) ] except KeyError: pass
[ "def", "completedefault", "(", "self", ",", "text", ",", "line", ",", "*", "_", ")", ":", "tokens", "=", "line", ".", "split", "(", ")", "try", ":", "before", "=", "tokens", "[", "-", "2", "]", "complete", "=", "before", ".", "lower", "(", ")", ...
https://github.com/stevearc/dql/blob/9666cfba19773c20c7b4be29adc7d6179cf00d44/dql/cli.py#L704-L719
moloch--/RootTheBox
097272332b9f9b7e2df31ca0823ed10c7b66ac81
handlers/BaseHandlers.py
python
BaseHandler.head
(self, *args, **kwargs)
Ignore it
Ignore it
[ "Ignore", "it" ]
def head(self, *args, **kwargs): """ Ignore it """ logging.warning("%s attempted to use HEAD method" % self.request.remote_ip)
[ "def", "head", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logging", ".", "warning", "(", "\"%s attempted to use HEAD method\"", "%", "self", ".", "request", ".", "remote_ip", ")" ]
https://github.com/moloch--/RootTheBox/blob/097272332b9f9b7e2df31ca0823ed10c7b66ac81/handlers/BaseHandlers.py#L228-L230
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_utils/filter_plugins/oo_filters.py
python
lib_utils_oo_dict_to_list_of_dict
(data, key_title='key', value_title='value')
return rval
Take a dict and arrange them as a list of dicts Input data: {'region': 'infra', 'test_k': 'test_v'} Return data: [{'key': 'region', 'value': 'infra'}, {'key': 'test_k', 'value': 'test_v'}] Written for use of the oc_label module
Take a dict and arrange them as a list of dicts
[ "Take", "a", "dict", "and", "arrange", "them", "as", "a", "list", "of", "dicts" ]
def lib_utils_oo_dict_to_list_of_dict(data, key_title='key', value_title='value'): """Take a dict and arrange them as a list of dicts Input data: {'region': 'infra', 'test_k': 'test_v'} Return data: [{'key': 'region', 'value': 'infra'}, {'key': 'test_k', 'value': 'test_v'}] Written for use of the oc_label module """ if not isinstance(data, dict): # pylint: disable=line-too-long raise errors.AnsibleFilterError("|failed expects first param is a dict. Got %s. Type: %s" % (str(data), str(type(data)))) rval = [] for label in data.items(): rval.append({key_title: label[0], value_title: label[1]}) return rval
[ "def", "lib_utils_oo_dict_to_list_of_dict", "(", "data", ",", "key_title", "=", "'key'", ",", "value_title", "=", "'value'", ")", ":", "if", "not", "isinstance", "(", "data", ",", "dict", ")", ":", "# pylint: disable=line-too-long", "raise", "errors", ".", "Ansi...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_utils/filter_plugins/oo_filters.py#L193-L212
freqtrade/freqtrade-strategies
484569e9c9b662c37563f5490162a0692675162d
user_data/strategies/Strategy002.py
python
Strategy002.populate_sell_trend
(self, dataframe: DataFrame, metadata: dict)
return dataframe
Based on TA indicators, populates the sell signal for the given dataframe :param dataframe: DataFrame :return: DataFrame with buy column
Based on TA indicators, populates the sell signal for the given dataframe :param dataframe: DataFrame :return: DataFrame with buy column
[ "Based", "on", "TA", "indicators", "populates", "the", "sell", "signal", "for", "the", "given", "dataframe", ":", "param", "dataframe", ":", "DataFrame", ":", "return", ":", "DataFrame", "with", "buy", "column" ]
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: """ Based on TA indicators, populates the sell signal for the given dataframe :param dataframe: DataFrame :return: DataFrame with buy column """ dataframe.loc[ ( (dataframe['sar'] > dataframe['close']) & (dataframe['fisher_rsi'] > 0.3) ), 'sell'] = 1 return dataframe
[ "def", "populate_sell_trend", "(", "self", ",", "dataframe", ":", "DataFrame", ",", "metadata", ":", "dict", ")", "->", "DataFrame", ":", "dataframe", ".", "loc", "[", "(", "(", "dataframe", "[", "'sar'", "]", ">", "dataframe", "[", "'close'", "]", ")", ...
https://github.com/freqtrade/freqtrade-strategies/blob/484569e9c9b662c37563f5490162a0692675162d/user_data/strategies/Strategy002.py#L123-L135
yuanwenq/dailyfresh
d834f01a8ec15f880302009e8ffb1eaf0b99177b
apps/order/views.py
python
CheckPayView.post
(self, request)
查询支付结果
查询支付结果
[ "查询支付结果" ]
def post(self, request): """查询支付结果""" # 用户是否登录 user = request.user if not user.is_authenticated(): return JsonResponse({'res': 0, 'errmsg': '用户未邓丽'}) # 接收参数 order_id = request.POST.get('order_id') # 校验参数 if not order_id: return JsonResponse({'res': 1, 'errmsg': '无效的订单id'}) try: order = OrderInfo.objects.get(order_id=order_id, user=user, pay_method=3, order_status=1) except OrderInfo.DoesNotExist: return JsonResponse({'res': 2, 'errmsg': '订单错误'}) app_private_key_string = open(os.path.join(settings.BASE_DIR, 'apps/order/app_private_key.pem')).read() alipay_public_key_string = open(os.path.join(settings.BASE_DIR, 'apps/order/alipay_public_key.pem')).read() # 业务处理:使用Python sdk调用支付宝的支付接口 # 初始化 alipay = AliPay( appid="2016092400581852", # 应用id app_notify_url=None, # 默认回调url app_private_key_string=app_private_key_string, # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥, alipay_public_key_string=alipay_public_key_string, sign_type="RSA2", # RSA 或者 RSA2 debug=True # 默认False True就会访问沙箱地址 ) # 调用支付宝交易查询接口 while True: response = alipay.api_alipay_trade_query(order_id) """ 响应参数 response = { "trade_no": "2017032121001004070200176844", # 支付宝交易号 "code": "10000", # 接口调用是否成功 "invoice_amount": "20.00", "open_id": "20880072506750308812798160715407", "fund_bill_list": [ { "amount": "20.00", "fund_channel": "ALIPAYACCOUNT" } ], "buyer_logon_id": "csq***@sandbox.com", "send_pay_date": "2017-03-21 13:29:17", "receipt_amount": "20.00", "out_trade_no": "out_trade_no15", "buyer_pay_amount": "20.00", "buyer_user_id": "2088102169481075", "msg": "Success", "point_amount": "0.00", "trade_status": "TRADE_SUCCESS", # 支付结果 "total_amount": "20.00" } """ code = response.get('code') if code == '10000' and response.get('trade_status') == 'TRADE_SUCCESS': # 支付成功 # 获取支付宝交易号 trade_no = response.get('trade_no') # 更新订单状态 order.trade_no = trade_no order.order_status = 4 # 待评价状态 order.save() # 返回结果 return JsonResponse({'res': 3, 'message': '支付成功'}) elif code == '40004' or (code == '10000' and response.get('trade_status') == 'WAIT_BUYER_PAY'): # 等待卖家付款 # 业务处理失败,可能一会就会成功 import time time.sleep(5) continue else: # 支付出错 return JsonResponse({'res': 4, 'errmsg': '支付失败'})
[ "def", "post", "(", "self", ",", "request", ")", ":", "# 用户是否登录", "user", "=", "request", ".", "user", "if", "not", "user", ".", "is_authenticated", "(", ")", ":", "return", "JsonResponse", "(", "{", "'res'", ":", "0", ",", "'errmsg'", ":", "'用户未邓丽'})"...
https://github.com/yuanwenq/dailyfresh/blob/d834f01a8ec15f880302009e8ffb1eaf0b99177b/apps/order/views.py#L389-L475
stanford-mast/nn_dataflow
198a5274b9529125c6aa2b8b72b365d60cf83778
nn_dataflow/tools/nn_dataflow_search.py
python
argparser
()
return ap
Argument parser.
Argument parser.
[ "Argument", "parser", "." ]
def argparser(): ''' Argument parser. ''' ap = argparse.ArgumentParser() ap.add_argument('net', help='network name, should be a .py file under "nns". ' 'Choices: {}.'.format(', '.join(all_networks()))) ap.add_argument('--batch', type=int, required=True, help='batch size') ap.add_argument('--word', type=int, default=16, help='word size in bits') ap.add_argument('--nodes', type=int, nargs=2, required=True, metavar=('H', 'W'), help='Parallel node partitioning dimensions') ap.add_argument('--array', type=int, nargs=2, required=True, metavar=('H', 'W'), help='PE array dimensions') ap.add_argument('--regf', type=int, required=True, help='register file size in bytes per PE') ap.add_argument('--gbuf', type=int, required=True, help='global buffer size in bytes') ap.add_argument('--bus-width', type=int, default=0, help='array bus width in bits. set 0 to ignore') ap.add_argument('--dram-bw', type=float, default='inf', help='total DRAM bandwidth in bytes per cycle.') ap.add_argument('--op-cost', type=float, default=1, help='cost of arithmetic operation') ap.add_argument('--hier-cost', type=float, nargs=4, default=[200, 6, 2, 1], metavar=('DRAM_COST', 'GBUF_COST', 'ITCN_COST', 'REGF_COST'), help='cost of access to memory hierarchy') ap.add_argument('--hop-cost', type=float, default=10, help='cost of access through one NoC hop') ap.add_argument('--unit-idle-cost', type=float, default=0, help='static cost over all nodes for unit execution time') ap.add_argument('--mem-type', default='2D', choices=['2D', '3D'], help='memory type. "2D" has memory only on edge nodes; ' '"3D" has memory vertially on top of all nodes.') ap.add_argument('--disable-bypass', nargs='*', default=[], choices=['i', 'o', 'f'], help='whether disallowing gbuf bypass for i (input), o ' '(output), or f (filter)') ap.add_argument('--solve-loopblocking', action='store_true', help='Use analytical solver to choose loop blocking. ' 'Otherwise use exhaustive search.') ap.add_argument('--enable-access-forwarding', action='store_true', help='Each node fetches a subset of data and forwards to ' 'other nodes.') ap.add_argument('--enable-gbuf-sharing', action='store_true', help='Share gbuf capacity across nodes through NoC.') ap.add_argument('--enable-save-writeback', action='store_true', help='Allow to save the writeback to memory for the ' 'intermediate data between layers if able to ' 'store the entire data set in on-chip buffers.') ap.add_argument('--disable-interlayer-opt', '--basic-interlayer-partition', action='store_true', help='Disable optimizations and only allow basic ' 'inter-layer pipeline.') ap.add_argument('--hybrid-partition', '--hybrid-partition2d', # deprecated old name action='store_true', help='Use hybrid partition for layer for node mapping. ' 'Otherwise use naive method based on layer type.') ap.add_argument('--batch-partition', action='store_true', help='Allow partitioning batch, i.e., consider data ' 'parallelism.') ap.add_argument('--ifmaps-partition', '--ifmap-partition', action='store_true', help='Allow partitioning ifmap channel dimension, which ' 'requires extra data synchronization.') ap.add_argument('--interlayer-partition', '--inter-layer-partition', action='store_true', help='Allow partitioning resources across multiple layers ' 'and process them simultaneously as an inter-layer ' 'pipeline.') ap.add_argument('--layer-pipeline-time-overhead', type=float, default=float('inf'), help='maximum allowed execution time overhead due to ' 'layer pipelining.') ap.add_argument('--layer-pipeline-max-degree', type=float, default=float('inf'), help='maximum allowed layer pipelining degree, i.e., ' 'number of vertices in a pipeline segment.') ap.add_argument('-g', '--goal', default='e', choices=['e', 'd', 'ed', 'E', 'D', 'ED'], help='Goal of optimization: E(nergy), D(elay), or ED.') ap.add_argument('-t', '--top', type=int, default=1, help='Number of top schedules to keep during search.') ap.add_argument('-p', '--processes', type=int, default=multiprocessing.cpu_count()//2, help='Number of parallel processes to use for search.') ap.add_argument('-v', '--verbose', action='store_true', help='Show progress and details.') return ap
[ "def", "argparser", "(", ")", ":", "ap", "=", "argparse", ".", "ArgumentParser", "(", ")", "ap", ".", "add_argument", "(", "'net'", ",", "help", "=", "'network name, should be a .py file under \"nns\". '", "'Choices: {}.'", ".", "format", "(", "', '", ".", "join...
https://github.com/stanford-mast/nn_dataflow/blob/198a5274b9529125c6aa2b8b72b365d60cf83778/nn_dataflow/tools/nn_dataflow_search.py#L210-L316
mu-editor/mu
5a5d7723405db588f67718a63a0ec0ecabebae33
mu/modes/pyboard.py
python
PyboardMode.workspace_dir
(self)
Return the default location on the filesystem for opening and closing files.
Return the default location on the filesystem for opening and closing files.
[ "Return", "the", "default", "location", "on", "the", "filesystem", "for", "opening", "and", "closing", "files", "." ]
def workspace_dir(self): """ Return the default location on the filesystem for opening and closing files. """ device_dir = None # Attempts to find the path on the filesystem that represents the # plugged in Pyboard board. if os.name == "posix": # We're on Linux or OSX for mount_command in ["mount", "/sbin/mount"]: try: mount_output = check_output(mount_command).splitlines() mounted_volumes = [x.split()[2] for x in mount_output] for volume in mounted_volumes: if volume.endswith(b"PYBFLASH"): device_dir = volume.decode("utf-8") except FileNotFoundError: next elif os.name == "nt": # We're on Windows. def get_volume_name(disk_name): """ Each disk or external device connected to windows has an attribute called "volume name". This function returns the volume name for the given disk/device. Code from http://stackoverflow.com/a/12056414 """ vol_name_buf = ctypes.create_unicode_buffer(1024) ctypes.windll.kernel32.GetVolumeInformationW( ctypes.c_wchar_p(disk_name), vol_name_buf, ctypes.sizeof(vol_name_buf), None, None, None, None, 0, ) return vol_name_buf.value # # In certain circumstances, volumes are allocated to USB # storage devices which cause a Windows popup to raise if their # volume contains no media. Wrapping the check in SetErrorMode # with SEM_FAILCRITICALERRORS (1) prevents this popup. # old_mode = ctypes.windll.kernel32.SetErrorMode(1) try: for disk in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": path = "{}:\\".format(disk) if ( os.path.exists(path) and get_volume_name(path) == "PYBFLASH" ): return path finally: ctypes.windll.kernel32.SetErrorMode(old_mode) else: # No support for unknown operating systems. raise NotImplementedError('OS "{}" not supported.'.format(os.name)) if device_dir: # Found it! self.connected = True return device_dir else: # Not plugged in? Just return Mu's regular workspace directory # after warning the user. wd = super().workspace_dir() if self.connected: m = _("Could not find an attached PyBoard device.") info = _( "Python files for PyBoard MicroPython devices" " are stored on the device. Therefore, to edit" " these files you need to have the device plugged in." " Until you plug in a device, Mu will use the" " directory found here:\n\n" " {}\n\n...to store your code." ) self.view.show_message(m, info.format(wd)) self.connected = False return wd
[ "def", "workspace_dir", "(", "self", ")", ":", "device_dir", "=", "None", "# Attempts to find the path on the filesystem that represents the", "# plugged in Pyboard board.", "if", "os", ".", "name", "==", "\"posix\"", ":", "# We're on Linux or OSX", "for", "mount_command", ...
https://github.com/mu-editor/mu/blob/5a5d7723405db588f67718a63a0ec0ecabebae33/mu/modes/pyboard.py#L104-L188
gkrizek/bash-lambda-layer
703b0ade8174022d44779d823172ab7ac33a5505
bin/docutils/nodes.py
python
NodeVisitor.dispatch_visit
(self, node)
return method(node)
Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit.
Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit.
[ "Call", "self", ".", "visit_", "+", "node", "class", "name", "with", "node", "as", "parameter", ".", "If", "the", "visit_", "...", "method", "does", "not", "exist", "call", "self", ".", "unknown_visit", "." ]
def dispatch_visit(self, node): """ Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit. """ node_name = node.__class__.__name__ method = getattr(self, 'visit_' + node_name, self.unknown_visit) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_visit calling %s for %s' % (method.__name__, node_name)) return method(node)
[ "def", "dispatch_visit", "(", "self", ",", "node", ")", ":", "node_name", "=", "node", ".", "__class__", ".", "__name__", "method", "=", "getattr", "(", "self", ",", "'visit_'", "+", "node_name", ",", "self", ".", "unknown_visit", ")", "self", ".", "docu...
https://github.com/gkrizek/bash-lambda-layer/blob/703b0ade8174022d44779d823172ab7ac33a5505/bin/docutils/nodes.py#L1871-L1882
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_serviceaccount_secret.py
python
Yedit.update
(self, path, value, index=None, curr_value=None)
return (False, self.yaml_dict)
put path, value into a dict
put path, value into a dict
[ "put", "path", "value", "into", "a", "dict" ]
def update(self, path, value, index=None, curr_value=None): ''' put path, value into a dict ''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError: entry = None if isinstance(entry, dict): # AUDIT:maybe-no-member makes sense due to fuzzy types # pylint: disable=maybe-no-member if not isinstance(value, dict): raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' + 'value=[{}] type=[{}]'.format(value, type(value))) entry.update(value) return (True, self.yaml_dict) elif isinstance(entry, list): # AUDIT:maybe-no-member makes sense due to fuzzy types # pylint: disable=maybe-no-member ind = None if curr_value: try: ind = entry.index(curr_value) except ValueError: return (False, self.yaml_dict) elif index is not None: ind = index if ind is not None and entry[ind] != value: entry[ind] = value return (True, self.yaml_dict) # see if it exists in the list try: ind = entry.index(value) except ValueError: # doesn't exist, append it entry.append(value) return (True, self.yaml_dict) # already exists, return if ind is not None: return (False, self.yaml_dict) return (False, self.yaml_dict)
[ "def", "update", "(", "self", ",", "path", ",", "value", ",", "index", "=", "None", ",", "curr_value", "=", "None", ")", ":", "try", ":", "entry", "=", "Yedit", ".", "get_entry", "(", "self", ".", "yaml_dict", ",", "path", ",", "self", ".", "separa...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_serviceaccount_secret.py#L541-L586
appinho/SARosPerceptionKitti
148683b23bef294762ced937e4386501e56c8d64
pre_processing/kitti2bag.py
python
inv
(transform)
return transform_inv
Invert rigid body transformation matrix
Invert rigid body transformation matrix
[ "Invert", "rigid", "body", "transformation", "matrix" ]
def inv(transform): "Invert rigid body transformation matrix" R = transform[0:3, 0:3] t = transform[0:3, 3] t_inv = -1 * R.T.dot(t) transform_inv = np.eye(4) transform_inv[0:3, 0:3] = R.T transform_inv[0:3, 3] = t_inv return transform_inv
[ "def", "inv", "(", "transform", ")", ":", "R", "=", "transform", "[", "0", ":", "3", ",", "0", ":", "3", "]", "t", "=", "transform", "[", "0", ":", "3", ",", "3", "]", "t_inv", "=", "-", "1", "*", "R", ".", "T", ".", "dot", "(", "t", ")...
https://github.com/appinho/SARosPerceptionKitti/blob/148683b23bef294762ced937e4386501e56c8d64/pre_processing/kitti2bag.py#L211-L219
ocelma/python-recsys
6c6343c6f57271e745773ab6aefea0a5d29f0620
recsys/datamodel/data.py
python
Data.get
(self)
return self._data
:returns: a list of tuples
:returns: a list of tuples
[ ":", "returns", ":", "a", "list", "of", "tuples" ]
def get(self): """ :returns: a list of tuples """ return self._data
[ "def", "get", "(", "self", ")", ":", "return", "self", ".", "_data" ]
https://github.com/ocelma/python-recsys/blob/6c6343c6f57271e745773ab6aefea0a5d29f0620/recsys/datamodel/data.py#L50-L54
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cpdp/v20190820/cpdp_client.py
python
CpdpClient.CheckAcct
(self, request)
商户绑定提现银行卡的验证接口 :param request: Request instance for CheckAcct. :type request: :class:`tencentcloud.cpdp.v20190820.models.CheckAcctRequest` :rtype: :class:`tencentcloud.cpdp.v20190820.models.CheckAcctResponse`
商户绑定提现银行卡的验证接口
[ "商户绑定提现银行卡的验证接口" ]
def CheckAcct(self, request): """商户绑定提现银行卡的验证接口 :param request: Request instance for CheckAcct. :type request: :class:`tencentcloud.cpdp.v20190820.models.CheckAcctRequest` :rtype: :class:`tencentcloud.cpdp.v20190820.models.CheckAcctResponse` """ try: params = request._serialize() body = self.call("CheckAcct", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CheckAcctResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "CheckAcct", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"CheckAcct\"", ",", "params", ")", "response", "=", "json", ".", "loads", "(", "bod...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cpdp/v20190820/cpdp_client.py#L428-L453
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_pvc.py
python
Utils.get_resource_file
(sfile, sfile_type='yaml')
return contents
return the service file
return the service file
[ "return", "the", "service", "file" ]
def get_resource_file(sfile, sfile_type='yaml'): ''' return the service file ''' contents = None with open(sfile) as sfd: contents = sfd.read() if sfile_type == 'yaml': # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage # pylint: disable=no-member if hasattr(yaml, 'RoundTripLoader'): contents = yaml.load(contents, yaml.RoundTripLoader) else: contents = yaml.safe_load(contents) elif sfile_type == 'json': contents = json.loads(contents) return contents
[ "def", "get_resource_file", "(", "sfile", ",", "sfile_type", "=", "'yaml'", ")", ":", "contents", "=", "None", "with", "open", "(", "sfile", ")", "as", "sfd", ":", "contents", "=", "sfd", ".", "read", "(", ")", "if", "sfile_type", "==", "'yaml'", ":", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_pvc.py#L1270-L1286
reviewboard/reviewboard
7395902e4c181bcd1d633f61105012ffb1d18e1b
reviewboard/admin/context_processors.py
python
read_only
(request)
return { 'is_read_only': is_site_read_only_for(request.user), 'read_only_message': siteconfig.get('read_only_message', ''), }
Return a dictionary with the read-only state. Args: request (django.http.HttpRequest): The current HTTP request. Returns: dict: State to add to the context.
Return a dictionary with the read-only state.
[ "Return", "a", "dictionary", "with", "the", "read", "-", "only", "state", "." ]
def read_only(request): """Return a dictionary with the read-only state. Args: request (django.http.HttpRequest): The current HTTP request. Returns: dict: State to add to the context. """ siteconfig = SiteConfiguration.objects.get_current() return { 'is_read_only': is_site_read_only_for(request.user), 'read_only_message': siteconfig.get('read_only_message', ''), }
[ "def", "read_only", "(", "request", ")", ":", "siteconfig", "=", "SiteConfiguration", ".", "objects", ".", "get_current", "(", ")", "return", "{", "'is_read_only'", ":", "is_site_read_only_for", "(", "request", ".", "user", ")", ",", "'read_only_message'", ":", ...
https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/admin/context_processors.py#L11-L27
happinesslz/TANet
2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f
second.pytorch_with_TANet/second/script.py
python
eval_multi_threshold
()
[]
def eval_multi_threshold(): config_path = "./configs/car.fhd.config" ckpt_name = "/path/to/your/model_ckpt" # don't forget to change this. assert "/path/to/your" not in ckpt_name config = pipeline_pb2.TrainEvalPipelineConfig() with open(config_path, "r") as f: proto_str = f.read() text_format.Merge(proto_str, config) model_cfg = config.model.second threshs = [0.3] for thresh in threshs: model_cfg.nms_score_threshold = thresh # don't forget to change this. result_path = Path.home() / f"second_test_eval_{thresh:.2f}" evaluate( config, result_path=result_path, ckpt_path=str(ckpt_name), batch_size=1, measure_time=True)
[ "def", "eval_multi_threshold", "(", ")", ":", "config_path", "=", "\"./configs/car.fhd.config\"", "ckpt_name", "=", "\"/path/to/your/model_ckpt\"", "# don't forget to change this.", "assert", "\"/path/to/your\"", "not", "in", "ckpt_name", "config", "=", "pipeline_pb2", ".", ...
https://github.com/happinesslz/TANet/blob/2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f/second.pytorch_with_TANet/second/script.py#L24-L43
nvaccess/nvda
20d5a25dced4da34338197f0ef6546270ebca5d0
source/NVDAObjects/__init__.py
python
NVDAObject._get_role
(self)
return controlTypes.Role.UNKNOWN
The role or type of control this object represents (example: button, list, dialog).
The role or type of control this object represents (example: button, list, dialog).
[ "The", "role", "or", "type", "of", "control", "this", "object", "represents", "(", "example", ":", "button", "list", "dialog", ")", "." ]
def _get_role(self) -> controlTypes.Role: """The role or type of control this object represents (example: button, list, dialog). """ return controlTypes.Role.UNKNOWN
[ "def", "_get_role", "(", "self", ")", "->", "controlTypes", ".", "Role", ":", "return", "controlTypes", ".", "Role", ".", "UNKNOWN" ]
https://github.com/nvaccess/nvda/blob/20d5a25dced4da34338197f0ef6546270ebca5d0/source/NVDAObjects/__init__.py#L434-L437
DIYer22/boxx
d271bc375a33e01e616a0f74ce028e6d77d1820e
boxx/tool/toolStructObj.py
python
_SliceToInt.__getitem__
(self, index)
return int(round(index))
[]
def __getitem__(self, index): def f(t): if isinstance(t, tuple): return tuple(f(i) for i in t) else: if isinstance(t, slice): return self.__intSlice(t) if isinstance(t, float): return int(round(t)) return t if isinstance(index, (tuple, slice)): return f(index) return int(round(index))
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "def", "f", "(", "t", ")", ":", "if", "isinstance", "(", "t", ",", "tuple", ")", ":", "return", "tuple", "(", "f", "(", "i", ")", "for", "i", "in", "t", ")", "else", ":", "if", "isins...
https://github.com/DIYer22/boxx/blob/d271bc375a33e01e616a0f74ce028e6d77d1820e/boxx/tool/toolStructObj.py#L43-L55
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py
python
DirDBM.__delitem__
(self, k)
C{del dirdbm[foo]} Delete a file in this directory. @type k: bytes @param k: key to delete @raise KeyError: Raised when there is no such key
C{del dirdbm[foo]} Delete a file in this directory.
[ "C", "{", "del", "dirdbm", "[", "foo", "]", "}", "Delete", "a", "file", "in", "this", "directory", "." ]
def __delitem__(self, k): """ C{del dirdbm[foo]} Delete a file in this directory. @type k: bytes @param k: key to delete @raise KeyError: Raised when there is no such key """ if not type(k) == bytes: raise TypeError("DirDBM key must be bytes") k = self._encode(k) try: self._dnamePath.child(k).remove() except (EnvironmentError): raise KeyError(self._decode(k))
[ "def", "__delitem__", "(", "self", ",", "k", ")", ":", "if", "not", "type", "(", "k", ")", "==", "bytes", ":", "raise", "TypeError", "(", "\"DirDBM key must be bytes\"", ")", "k", "=", "self", ".", "_encode", "(", "k", ")", "try", ":", "self", ".", ...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/twisted/persisted/dirdbm.py#L177-L193
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/patches.py
python
FancyArrowPatch.get_mutation_scale
(self)
return self._mutation_scale
Return the mutation scale. Returns ------- scale : scalar
Return the mutation scale.
[ "Return", "the", "mutation", "scale", "." ]
def get_mutation_scale(self): """ Return the mutation scale. Returns ------- scale : scalar """ return self._mutation_scale
[ "def", "get_mutation_scale", "(", "self", ")", ":", "return", "self", ".", "_mutation_scale" ]
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/patches.py#L4195-L4203
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/ssl.py
python
SSLSocket.do_handshake
(self)
Perform a TLS/SSL handshake.
Perform a TLS/SSL handshake.
[ "Perform", "a", "TLS", "/", "SSL", "handshake", "." ]
def do_handshake(self): """Perform a TLS/SSL handshake.""" self._sslobj.do_handshake()
[ "def", "do_handshake", "(", "self", ")", ":", "self", ".", "_sslobj", ".", "do_handshake", "(", ")" ]
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/ssl.py#L292-L296
NoGameNoLife00/mybolg
afe17ea5bfe405e33766e5682c43a4262232ee12
libs/sqlalchemy/connectors/zxJDBC.py
python
ZxJDBCConnector._driver_kwargs
(self)
return {}
Return kw arg dict to be sent to connect().
Return kw arg dict to be sent to connect().
[ "Return", "kw", "arg", "dict", "to", "be", "sent", "to", "connect", "()", "." ]
def _driver_kwargs(self): """Return kw arg dict to be sent to connect().""" return {}
[ "def", "_driver_kwargs", "(", "self", ")", ":", "return", "{", "}" ]
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/sqlalchemy/connectors/zxJDBC.py#L31-L33
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/libs/model_report/report.py
python
ReportAdmin._get_grouper_text
(self, groupby_field, value)
return value
[]
def _get_grouper_text(self, groupby_field, value): try: model_field = [mfield for mfield, field in self.model_fields if field == groupby_field][0] except: model_field = None value = self.get_grouper_text(value, groupby_field, model_field) if value is None or str(value) == u'None': if groupby_field is None or str(groupby_field) == u'None': value = force_text(_('Results')) else: value = force_text(_('Nothing')) return value
[ "def", "_get_grouper_text", "(", "self", ",", "groupby_field", ",", "value", ")", ":", "try", ":", "model_field", "=", "[", "mfield", "for", "mfield", ",", "field", "in", "self", ".", "model_fields", "if", "field", "==", "groupby_field", "]", "[", "0", "...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/libs/model_report/report.py#L378-L389
EricZgw/PyramidBox
03f67d8422f2f03e5ee580e2f92d4040c24bbdb4
nets/np_methods.py
python
bboxes_nms_fast
(classes, scores, bboxes, nms_threshold=0.45)
return classes[keep], scores[keep], bboxes[keep]
Apply non-maximum selection to bounding boxes.
Apply non-maximum selection to bounding boxes.
[ "Apply", "non", "-", "maximum", "selection", "to", "bounding", "boxes", "." ]
def bboxes_nms_fast(classes, scores, bboxes, nms_threshold=0.45): """Apply non-maximum selection to bounding boxes. """ y1 = bboxes[:, 0] x1 = bboxes[:, 1] y2 = bboxes[:, 2] x2 = bboxes[:, 3] areas = (x2 - x1 ) * (y2 - y1 ) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1) h = np.maximum(0.0, yy2 - yy1) inter = w * h ovr = inter / (areas[i] + areas[order[1:]] - inter) inds = np.where(ovr <= nms_threshold)[0] order = order[inds + 1] keep = keep[0:200] return classes[keep], scores[keep], bboxes[keep]
[ "def", "bboxes_nms_fast", "(", "classes", ",", "scores", ",", "bboxes", ",", "nms_threshold", "=", "0.45", ")", ":", "y1", "=", "bboxes", "[", ":", ",", "0", "]", "x1", "=", "bboxes", "[", ":", ",", "1", "]", "y2", "=", "bboxes", "[", ":", ",", ...
https://github.com/EricZgw/PyramidBox/blob/03f67d8422f2f03e5ee580e2f92d4040c24bbdb4/nets/np_methods.py#L235-L263
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/io/pytables.py
python
IndexCol.is_indexed
(self)
return whether I am an indexed column
return whether I am an indexed column
[ "return", "whether", "I", "am", "an", "indexed", "column" ]
def is_indexed(self): """ return whether I am an indexed column """ try: return getattr(self.table.cols, self.cname).is_indexed except AttributeError: False
[ "def", "is_indexed", "(", "self", ")", ":", "try", ":", "return", "getattr", "(", "self", ".", "table", ".", "cols", ",", "self", ".", "cname", ")", ".", "is_indexed", "except", "AttributeError", ":", "False" ]
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/io/pytables.py#L1612-L1617
cltk/cltk
1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1
src/cltk/phonology/non/utils.py
python
Vowel.match
(self, abstract_vowel)
[]
def match(self, abstract_vowel): if isinstance(abstract_vowel, AbstractVowel): res = True if abstract_vowel.height is not None: res = res and abstract_vowel.height == self.height if abstract_vowel.backness is not None: res = res and abstract_vowel.backness == self.backness if abstract_vowel.rounded is not None: res = res and abstract_vowel.rounded == self.rounded if abstract_vowel.length is not None: res = res and abstract_vowel.length == self.length return res elif abstract_vowel is None: return True else: return False
[ "def", "match", "(", "self", ",", "abstract_vowel", ")", ":", "if", "isinstance", "(", "abstract_vowel", ",", "AbstractVowel", ")", ":", "res", "=", "True", "if", "abstract_vowel", ".", "height", "is", "not", "None", ":", "res", "=", "res", "and", "abstr...
https://github.com/cltk/cltk/blob/1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1/src/cltk/phonology/non/utils.py#L254-L269
eliben/pykaleidoscope
977d234e7bffb01e3dc91f6dd862bb03ada1063b
chapter7and8.py
python
TestParser._flatten
(self, ast)
Test helper - flattens the AST into a sexpr-like nested list.
Test helper - flattens the AST into a sexpr-like nested list.
[ "Test", "helper", "-", "flattens", "the", "AST", "into", "a", "sexpr", "-", "like", "nested", "list", "." ]
def _flatten(self, ast): """Test helper - flattens the AST into a sexpr-like nested list.""" if isinstance(ast, NumberExprAST): return ['Number', ast.val] elif isinstance(ast, VariableExprAST): return ['Variable', ast.name] elif isinstance(ast, UnaryExprAST): return ['Unary', ast.op, self._flatten(ast.operand)] elif isinstance(ast, BinaryExprAST): return ['Binop', ast.op, self._flatten(ast.lhs), self._flatten(ast.rhs)] elif isinstance(ast, VarExprAST): vars = [[name, self._flatten(init)] for name, init in ast.vars] return ['Var', vars, self._flatten(ast.body)] elif isinstance(ast, CallExprAST): args = [self._flatten(arg) for arg in ast.args] return ['Call', ast.callee, args] elif isinstance(ast, PrototypeAST): return ['Proto', ast.name, ' '.join(ast.argnames)] elif isinstance(ast, FunctionAST): return ['Function', self._flatten(ast.proto), self._flatten(ast.body)] else: raise TypeError('unknown type in _flatten: {0}'.format(type(ast)))
[ "def", "_flatten", "(", "self", ",", "ast", ")", ":", "if", "isinstance", "(", "ast", ",", "NumberExprAST", ")", ":", "return", "[", "'Number'", ",", "ast", ".", "val", "]", "elif", "isinstance", "(", "ast", ",", "VariableExprAST", ")", ":", "return", ...
https://github.com/eliben/pykaleidoscope/blob/977d234e7bffb01e3dc91f6dd862bb03ada1063b/chapter7and8.py#L988-L1011
scikit-learn/scikit-learn
1d1aadd0711b87d2a11c80aad15df6f8cf156712
sklearn/linear_model/_least_angle.py
python
lars_path
( X, y, Xy=None, *, Gram=None, max_iter=500, alpha_min=0, method="lar", copy_X=True, eps=np.finfo(float).eps, copy_Gram=True, verbose=0, return_path=True, return_n_iter=False, positive=False, )
return _lars_path_solver( X=X, y=y, Xy=Xy, Gram=Gram, n_samples=None, max_iter=max_iter, alpha_min=alpha_min, method=method, copy_X=copy_X, eps=eps, copy_Gram=copy_Gram, verbose=verbose, return_path=return_path, return_n_iter=return_n_iter, positive=positive, )
Compute Least Angle Regression or Lasso path using LARS algorithm [1] The optimization objective for the case method='lasso' is:: (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 in the case of method='lars', the objective function is only known in the form of an implicit equation (see discussion in [1]) Read more in the :ref:`User Guide <least_angle_regression>`. Parameters ---------- X : None or array-like of shape (n_samples, n_features) Input data. Note that if X is None then the Gram matrix must be specified, i.e., cannot be None or False. y : None or array-like of shape (n_samples,) Input targets. Xy : array-like of shape (n_samples,) or (n_samples, n_targets), \ default=None Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed. Gram : None, 'auto', array-like of shape (n_features, n_features), \ default=None Precomputed Gram matrix (X' * X), if ``'auto'``, the Gram matrix is precomputed from the given X, if there are more samples than features. max_iter : int, default=500 Maximum number of iterations to perform, set to infinity for no limit. alpha_min : float, default=0 Minimum correlation along the path. It corresponds to the regularization parameter alpha parameter in the Lasso. method : {'lar', 'lasso'}, default='lar' Specifies the returned model. Select ``'lar'`` for Least Angle Regression, ``'lasso'`` for the Lasso. copy_X : bool, default=True If ``False``, ``X`` is overwritten. eps : float, default=np.finfo(float).eps The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned systems. Unlike the ``tol`` parameter in some iterative optimization-based algorithms, this parameter does not control the tolerance of the optimization. copy_Gram : bool, default=True If ``False``, ``Gram`` is overwritten. verbose : int, default=0 Controls output verbosity. return_path : bool, default=True If ``return_path==True`` returns the entire path, else returns only the last point of the path. return_n_iter : bool, default=False Whether to return the number of iterations. positive : bool, default=False Restrict coefficients to be >= 0. This option is only allowed with method 'lasso'. Note that the model coefficients will not converge to the ordinary-least-squares solution for small values of alpha. Only coefficients up to the smallest alpha value (``alphas_[alphas_ > 0.].min()`` when fit_path=True) reached by the stepwise Lars-Lasso algorithm are typically in congruence with the solution of the coordinate descent lasso_path function. Returns ------- alphas : array-like of shape (n_alphas + 1,) Maximum of covariances (in absolute value) at each iteration. ``n_alphas`` is either ``max_iter``, ``n_features`` or the number of nodes in the path with ``alpha >= alpha_min``, whichever is smaller. active : array-like of shape (n_alphas,) Indices of active variables at the end of the path. coefs : array-like of shape (n_features, n_alphas + 1) Coefficients along the path n_iter : int Number of iterations run. Returned only if return_n_iter is set to True. See Also -------- lars_path_gram lasso_path lasso_path_gram LassoLars Lars LassoLarsCV LarsCV sklearn.decomposition.sparse_encode References ---------- .. [1] "Least Angle Regression", Efron et al. http://statweb.stanford.edu/~tibs/ftp/lars.pdf .. [2] `Wikipedia entry on the Least-angle regression <https://en.wikipedia.org/wiki/Least-angle_regression>`_ .. [3] `Wikipedia entry on the Lasso <https://en.wikipedia.org/wiki/Lasso_(statistics)>`_
Compute Least Angle Regression or Lasso path using LARS algorithm [1]
[ "Compute", "Least", "Angle", "Regression", "or", "Lasso", "path", "using", "LARS", "algorithm", "[", "1", "]" ]
def lars_path( X, y, Xy=None, *, Gram=None, max_iter=500, alpha_min=0, method="lar", copy_X=True, eps=np.finfo(float).eps, copy_Gram=True, verbose=0, return_path=True, return_n_iter=False, positive=False, ): """Compute Least Angle Regression or Lasso path using LARS algorithm [1] The optimization objective for the case method='lasso' is:: (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 in the case of method='lars', the objective function is only known in the form of an implicit equation (see discussion in [1]) Read more in the :ref:`User Guide <least_angle_regression>`. Parameters ---------- X : None or array-like of shape (n_samples, n_features) Input data. Note that if X is None then the Gram matrix must be specified, i.e., cannot be None or False. y : None or array-like of shape (n_samples,) Input targets. Xy : array-like of shape (n_samples,) or (n_samples, n_targets), \ default=None Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed. Gram : None, 'auto', array-like of shape (n_features, n_features), \ default=None Precomputed Gram matrix (X' * X), if ``'auto'``, the Gram matrix is precomputed from the given X, if there are more samples than features. max_iter : int, default=500 Maximum number of iterations to perform, set to infinity for no limit. alpha_min : float, default=0 Minimum correlation along the path. It corresponds to the regularization parameter alpha parameter in the Lasso. method : {'lar', 'lasso'}, default='lar' Specifies the returned model. Select ``'lar'`` for Least Angle Regression, ``'lasso'`` for the Lasso. copy_X : bool, default=True If ``False``, ``X`` is overwritten. eps : float, default=np.finfo(float).eps The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned systems. Unlike the ``tol`` parameter in some iterative optimization-based algorithms, this parameter does not control the tolerance of the optimization. copy_Gram : bool, default=True If ``False``, ``Gram`` is overwritten. verbose : int, default=0 Controls output verbosity. return_path : bool, default=True If ``return_path==True`` returns the entire path, else returns only the last point of the path. return_n_iter : bool, default=False Whether to return the number of iterations. positive : bool, default=False Restrict coefficients to be >= 0. This option is only allowed with method 'lasso'. Note that the model coefficients will not converge to the ordinary-least-squares solution for small values of alpha. Only coefficients up to the smallest alpha value (``alphas_[alphas_ > 0.].min()`` when fit_path=True) reached by the stepwise Lars-Lasso algorithm are typically in congruence with the solution of the coordinate descent lasso_path function. Returns ------- alphas : array-like of shape (n_alphas + 1,) Maximum of covariances (in absolute value) at each iteration. ``n_alphas`` is either ``max_iter``, ``n_features`` or the number of nodes in the path with ``alpha >= alpha_min``, whichever is smaller. active : array-like of shape (n_alphas,) Indices of active variables at the end of the path. coefs : array-like of shape (n_features, n_alphas + 1) Coefficients along the path n_iter : int Number of iterations run. Returned only if return_n_iter is set to True. See Also -------- lars_path_gram lasso_path lasso_path_gram LassoLars Lars LassoLarsCV LarsCV sklearn.decomposition.sparse_encode References ---------- .. [1] "Least Angle Regression", Efron et al. http://statweb.stanford.edu/~tibs/ftp/lars.pdf .. [2] `Wikipedia entry on the Least-angle regression <https://en.wikipedia.org/wiki/Least-angle_regression>`_ .. [3] `Wikipedia entry on the Lasso <https://en.wikipedia.org/wiki/Lasso_(statistics)>`_ """ if X is None and Gram is not None: raise ValueError( "X cannot be None if Gram is not None" "Use lars_path_gram to avoid passing X and y." ) return _lars_path_solver( X=X, y=y, Xy=Xy, Gram=Gram, n_samples=None, max_iter=max_iter, alpha_min=alpha_min, method=method, copy_X=copy_X, eps=eps, copy_Gram=copy_Gram, verbose=verbose, return_path=return_path, return_n_iter=return_n_iter, positive=positive, )
[ "def", "lars_path", "(", "X", ",", "y", ",", "Xy", "=", "None", ",", "*", ",", "Gram", "=", "None", ",", "max_iter", "=", "500", ",", "alpha_min", "=", "0", ",", "method", "=", "\"lar\"", ",", "copy_X", "=", "True", ",", "eps", "=", "np", ".", ...
https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/sklearn/linear_model/_least_angle.py#L35-L188
Tinkoff/Nginx-builder
1c8bbd1e51bf6e856b3756f59aa911a3687b3138
src/builder.py
python
repair_keys
(block)
return repaired_keys_dict
Преобразованиие формата названий параметров :param block: :return repaired_keys_dict:
Преобразованиие формата названий параметров :param block: :return repaired_keys_dict:
[ "Преобразованиие", "формата", "названий", "параметров", ":", "param", "block", ":", ":", "return", "repaired_keys_dict", ":" ]
def repair_keys(block): """ Преобразованиие формата названий параметров :param block: :return repaired_keys_dict: """ repaired_keys_dict = OrderedDict() for block_part in block: repaired_keys = OrderedDict() for key in block_part: z = ''.join(x for x in key.title() if not x.isspace()).replace('_', '-') repaired_keys[z] = block_part[key] index = list(repaired_keys)[0] index_q = '{}_{}'.format(index, repaired_keys[index]) repaired_keys_dict[index_q] = repaired_keys return repaired_keys_dict
[ "def", "repair_keys", "(", "block", ")", ":", "repaired_keys_dict", "=", "OrderedDict", "(", ")", "for", "block_part", "in", "block", ":", "repaired_keys", "=", "OrderedDict", "(", ")", "for", "key", "in", "block_part", ":", "z", "=", "''", ".", "join", ...
https://github.com/Tinkoff/Nginx-builder/blob/1c8bbd1e51bf6e856b3756f59aa911a3687b3138/src/builder.py#L233-L248
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/lib-tk/Tix.py
python
HList.item_cget
(self, entry, col, opt)
return self.tk.call(self._w, 'item', 'cget', entry, col, opt)
[]
def item_cget(self, entry, col, opt): return self.tk.call(self._w, 'item', 'cget', entry, col, opt)
[ "def", "item_cget", "(", "self", ",", "entry", ",", "col", ",", "opt", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'item'", ",", "'cget'", ",", "entry", ",", "col", ",", "opt", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/lib-tk/Tix.py#L1008-L1009
gothinkster/flask-realworld-example-app
4b95fb2227dfeb5dd1a45d89b2bf48630b93fd28
conduit/extensions.py
python
CRUDMixin.delete
(self, commit=True)
return commit and db.session.commit()
Remove the record from the database.
Remove the record from the database.
[ "Remove", "the", "record", "from", "the", "database", "." ]
def delete(self, commit=True): """Remove the record from the database.""" db.session.delete(self) return commit and db.session.commit()
[ "def", "delete", "(", "self", ",", "commit", "=", "True", ")", ":", "db", ".", "session", ".", "delete", "(", "self", ")", "return", "commit", "and", "db", ".", "session", ".", "commit", "(", ")" ]
https://github.com/gothinkster/flask-realworld-example-app/blob/4b95fb2227dfeb5dd1a45d89b2bf48630b93fd28/conduit/extensions.py#L34-L37
cbfinn/gps
82fa6cc930c4392d55d2525f6b792089f1d2ccfe
python/gps/gui/image_visualizer.py
python
ImageVisualizer.draw
(self)
[]
def draw(self): self._ax_image.draw_artist(self._ax_image.patch) self._ax_image.draw_artist(self._plot) self._ax_image.draw_artist(self._overlay_plot_initial) self._ax_image.draw_artist(self._overlay_plot_target) self._fig.canvas.update() self._fig.canvas.flush_events()
[ "def", "draw", "(", "self", ")", ":", "self", ".", "_ax_image", ".", "draw_artist", "(", "self", ".", "_ax_image", ".", "patch", ")", "self", ".", "_ax_image", ".", "draw_artist", "(", "self", ".", "_plot", ")", "self", ".", "_ax_image", ".", "draw_art...
https://github.com/cbfinn/gps/blob/82fa6cc930c4392d55d2525f6b792089f1d2ccfe/python/gps/gui/image_visualizer.py#L153-L159
yougov/mongo-connector
557cafd4b54c848cd54ef28a258391a154650cb4
mongo_connector/connector.py
python
Connector.oplog_thread_join
(self)
Stops all the OplogThreads
Stops all the OplogThreads
[ "Stops", "all", "the", "OplogThreads" ]
def oplog_thread_join(self): """Stops all the OplogThreads """ LOG.info("MongoConnector: Stopping all OplogThreads") for thread in self.shard_set.values(): thread.join()
[ "def", "oplog_thread_join", "(", "self", ")", ":", "LOG", ".", "info", "(", "\"MongoConnector: Stopping all OplogThreads\"", ")", "for", "thread", "in", "self", ".", "shard_set", ".", "values", "(", ")", ":", "thread", ".", "join", "(", ")" ]
https://github.com/yougov/mongo-connector/blob/557cafd4b54c848cd54ef28a258391a154650cb4/mongo_connector/connector.py#L475-L480
univ-of-utah-marriott-library-apple/firmware_password_manager
198694a650acd3fa61b85d25dd61e83782bb25d5
firmware_password_manager.py
python
FWPM_Object.secure_delete
(self)
return
attempts to securely delete the keyfile with medium overwrite and zeroing settings
attempts to securely delete the keyfile with medium overwrite and zeroing settings
[ "attempts", "to", "securely", "delete", "the", "keyfile", "with", "medium", "overwrite", "and", "zeroing", "settings" ]
def secure_delete(self): """ attempts to securely delete the keyfile with medium overwrite and zeroing settings """ if self.logger: self.logger.info("%s: activated" % inspect.stack()[0][3]) if self.logger: self.logger.info("Deleting keyfile") use_srm = bool(os.path.exists("/usr/bin/srm")) if self.args.testmode: if self.logger: self.logger.info("Test mode, keyfile not deleted.") return if use_srm: try: subprocess.call(["/usr/bin/srm", "-mz", self.config_options["keyfile"]["path"]]) if self.logger: self.logger.info("keyfile deleted successfuly.") except Exception as exception_message: if self.logger: self.logger.critical("Issue with attempt to remove keyfile. %s" % exception_message) else: try: deleted_keyfile = subprocess.call(["/bin/rm", "-Pf", self.config_options["keyfile"]["path"]]) print("return: %r" % deleted_keyfile) if self.logger: self.logger.info("keyfile deleted successfuly.") except Exception as exception_message: if self.logger: self.logger.critical("Issue with attempt to remove keyfile. %s" % exception_message) # is this really needed? if os.path.exists(self.config_options["keyfile"]["path"]): if self.logger: self.logger.critical("Failure to remove keyfile.") else: if self.logger: self.logger.info("Keyfile removed.") return
[ "def", "secure_delete", "(", "self", ")", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "\"%s: activated\"", "%", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ")", "if", "self", ".", "logger", ...
https://github.com/univ-of-utah-marriott-library-apple/firmware_password_manager/blob/198694a650acd3fa61b85d25dd61e83782bb25d5/firmware_password_manager.py#L316-L358
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/configuration.py
python
Configuration.logger_format
(self)
return self.__logger_format
The logger format. The logger_formatter will be updated when sets logger_format. :param value: The format string. :type: str
The logger format.
[ "The", "logger", "format", "." ]
def logger_format(self): """The logger format. The logger_formatter will be updated when sets logger_format. :param value: The format string. :type: str """ return self.__logger_format
[ "def", "logger_format", "(", "self", ")", ":", "return", "self", ".", "__logger_format" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/configuration.py#L276-L284
thinkle/gourmet
8af29c8ded24528030e5ae2ea3461f61c1e5a575
gourmet/plugins/nutritional_information/nutritionDisplay.py
python
NutritionModel.connect_treeview_signals
(self,tv)
[]
def connect_treeview_signals (self,tv): tv.connect('row-expanded',self.row_expanded_cb)
[ "def", "connect_treeview_signals", "(", "self", ",", "tv", ")", ":", "tv", ".", "connect", "(", "'row-expanded'", ",", "self", ".", "row_expanded_cb", ")" ]
https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/plugins/nutritional_information/nutritionDisplay.py#L15-L16
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/opsi/operations_insights_client.py
python
OperationsInsightsClient.summarize_exadata_insight_resource_utilization_insight
(self, compartment_id, resource_type, resource_metric, **kwargs)
Gets current utilization, projected utilization and days to reach projectedUtilization for an exadata system over specified time period. Valid values for ResourceType DATABASE are CPU,MEMORY,IO and STORAGE. Valid values for ResourceType HOST are CPU and MEMORY. Valid values for ResourceType STORAGE_SERVER are STORAGE, IOPS and THROUGHPUT. :param str compartment_id: (required) The `OCID`__ of the compartment. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param str resource_type: (required) Filter by resource. Supported values are HOST , STORAGE_SERVER and DATABASE :param str resource_metric: (required) Filter by resource metric. Supported values are CPU , STORAGE, MEMORY, IO, IOPS, THROUGHPUT :param str analysis_time_interval: (optional) Specify time period in ISO 8601 format with respect to current time. Default is last 30 days represented by P30D. If timeInterval is specified, then timeIntervalStart and timeIntervalEnd will be ignored. Examples P90D (last 90 days), P4W (last 4 weeks), P2M (last 2 months), P1Y (last 12 months), . Maximum value allowed is 25 months prior to current time (P25M). :param datetime time_interval_start: (optional) Analysis start time in UTC in ISO 8601 format(inclusive). Example 2019-10-30T00:00:00Z (yyyy-MM-ddThh:mm:ssZ). The minimum allowed value is 2 years prior to the current day. timeIntervalStart and timeIntervalEnd parameters are used together. If analysisTimeInterval is specified, this parameter is ignored. :param datetime time_interval_end: (optional) Analysis end time in UTC in ISO 8601 format(exclusive). Example 2019-10-30T00:00:00Z (yyyy-MM-ddThh:mm:ssZ). timeIntervalStart and timeIntervalEnd are used together. If timeIntervalEnd is not specified, current time is used as timeIntervalEnd. :param list[str] exadata_insight_id: (optional) Optional list of exadata insight resource `OCIDs`__. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param list[str] exadata_type: (optional) Filter by one or more Exadata types. Possible value are DBMACHINE, EXACS, and EXACC. :param int forecast_start_day: (optional) Number of days used for utilization forecast analysis. :param int forecast_days: (optional) Number of days used for utilization forecast analysis. :param list[str] cdb_name: (optional) Filter by one or more cdb name. :param list[str] host_name: (optional) Filter by hostname. :param int limit: (optional) For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see `List Pagination`__. Example: `50` __ https://docs.cloud.oracle.com/Content/API/Concepts/usingapi.htm#nine :param str page: (optional) For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see `List Pagination`__. __ https://docs.cloud.oracle.com/Content/API/Concepts/usingapi.htm#nine :param list[str] defined_tag_equals: (optional) A list of tag filters to apply. Only resources with a defined tag matching the value will be returned. Each item in the list has the format \"{namespace}.{tagName}.{value}\". All inputs are case-insensitive. Multiple values for the same key (i.e. same namespace and tag name) are interpreted as \"OR\". Values for different keys (i.e. different namespaces, different tag names, or both) are interpreted as \"AND\". :param list[str] freeform_tag_equals: (optional) A list of tag filters to apply. Only resources with a freeform tag matching the value will be returned. The key for each tag is \"{tagName}.{value}\". All inputs are case-insensitive. Multiple values for the same tag name are interpreted as \"OR\". Values for different tag names are interpreted as \"AND\". :param list[str] defined_tag_exists: (optional) A list of tag existence filters to apply. Only resources for which the specified defined tags exist will be returned. Each item in the list has the format \"{namespace}.{tagName}.true\" (for checking existence of a defined tag) or \"{namespace}.true\". All inputs are case-insensitive. Currently, only existence (\"true\" at the end) is supported. Absence (\"false\" at the end) is not supported. Multiple values for the same key (i.e. same namespace and tag name) are interpreted as \"OR\". Values for different keys (i.e. different namespaces, different tag names, or both) are interpreted as \"AND\". :param list[str] freeform_tag_exists: (optional) A list of tag existence filters to apply. Only resources for which the specified freeform tags exist the value will be returned. The key for each tag is \"{tagName}.true\". All inputs are case-insensitive. Currently, only existence (\"true\" at the end) is supported. Absence (\"false\" at the end) is not supported. Multiple values for different tag names are interpreted as \"AND\". :param str opc_request_id: (optional) Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.opsi.models.SummarizeExadataInsightResourceUtilizationInsightAggregation` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/opsi/summarize_exadata_insight_resource_utilization_insight.py.html>`__ to see an example of how to use summarize_exadata_insight_resource_utilization_insight API.
Gets current utilization, projected utilization and days to reach projectedUtilization for an exadata system over specified time period. Valid values for ResourceType DATABASE are CPU,MEMORY,IO and STORAGE. Valid values for ResourceType HOST are CPU and MEMORY. Valid values for ResourceType STORAGE_SERVER are STORAGE, IOPS and THROUGHPUT.
[ "Gets", "current", "utilization", "projected", "utilization", "and", "days", "to", "reach", "projectedUtilization", "for", "an", "exadata", "system", "over", "specified", "time", "period", ".", "Valid", "values", "for", "ResourceType", "DATABASE", "are", "CPU", "M...
def summarize_exadata_insight_resource_utilization_insight(self, compartment_id, resource_type, resource_metric, **kwargs): """ Gets current utilization, projected utilization and days to reach projectedUtilization for an exadata system over specified time period. Valid values for ResourceType DATABASE are CPU,MEMORY,IO and STORAGE. Valid values for ResourceType HOST are CPU and MEMORY. Valid values for ResourceType STORAGE_SERVER are STORAGE, IOPS and THROUGHPUT. :param str compartment_id: (required) The `OCID`__ of the compartment. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param str resource_type: (required) Filter by resource. Supported values are HOST , STORAGE_SERVER and DATABASE :param str resource_metric: (required) Filter by resource metric. Supported values are CPU , STORAGE, MEMORY, IO, IOPS, THROUGHPUT :param str analysis_time_interval: (optional) Specify time period in ISO 8601 format with respect to current time. Default is last 30 days represented by P30D. If timeInterval is specified, then timeIntervalStart and timeIntervalEnd will be ignored. Examples P90D (last 90 days), P4W (last 4 weeks), P2M (last 2 months), P1Y (last 12 months), . Maximum value allowed is 25 months prior to current time (P25M). :param datetime time_interval_start: (optional) Analysis start time in UTC in ISO 8601 format(inclusive). Example 2019-10-30T00:00:00Z (yyyy-MM-ddThh:mm:ssZ). The minimum allowed value is 2 years prior to the current day. timeIntervalStart and timeIntervalEnd parameters are used together. If analysisTimeInterval is specified, this parameter is ignored. :param datetime time_interval_end: (optional) Analysis end time in UTC in ISO 8601 format(exclusive). Example 2019-10-30T00:00:00Z (yyyy-MM-ddThh:mm:ssZ). timeIntervalStart and timeIntervalEnd are used together. If timeIntervalEnd is not specified, current time is used as timeIntervalEnd. :param list[str] exadata_insight_id: (optional) Optional list of exadata insight resource `OCIDs`__. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param list[str] exadata_type: (optional) Filter by one or more Exadata types. Possible value are DBMACHINE, EXACS, and EXACC. :param int forecast_start_day: (optional) Number of days used for utilization forecast analysis. :param int forecast_days: (optional) Number of days used for utilization forecast analysis. :param list[str] cdb_name: (optional) Filter by one or more cdb name. :param list[str] host_name: (optional) Filter by hostname. :param int limit: (optional) For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see `List Pagination`__. Example: `50` __ https://docs.cloud.oracle.com/Content/API/Concepts/usingapi.htm#nine :param str page: (optional) For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see `List Pagination`__. __ https://docs.cloud.oracle.com/Content/API/Concepts/usingapi.htm#nine :param list[str] defined_tag_equals: (optional) A list of tag filters to apply. Only resources with a defined tag matching the value will be returned. Each item in the list has the format \"{namespace}.{tagName}.{value}\". All inputs are case-insensitive. Multiple values for the same key (i.e. same namespace and tag name) are interpreted as \"OR\". Values for different keys (i.e. different namespaces, different tag names, or both) are interpreted as \"AND\". :param list[str] freeform_tag_equals: (optional) A list of tag filters to apply. Only resources with a freeform tag matching the value will be returned. The key for each tag is \"{tagName}.{value}\". All inputs are case-insensitive. Multiple values for the same tag name are interpreted as \"OR\". Values for different tag names are interpreted as \"AND\". :param list[str] defined_tag_exists: (optional) A list of tag existence filters to apply. Only resources for which the specified defined tags exist will be returned. Each item in the list has the format \"{namespace}.{tagName}.true\" (for checking existence of a defined tag) or \"{namespace}.true\". All inputs are case-insensitive. Currently, only existence (\"true\" at the end) is supported. Absence (\"false\" at the end) is not supported. Multiple values for the same key (i.e. same namespace and tag name) are interpreted as \"OR\". Values for different keys (i.e. different namespaces, different tag names, or both) are interpreted as \"AND\". :param list[str] freeform_tag_exists: (optional) A list of tag existence filters to apply. Only resources for which the specified freeform tags exist the value will be returned. The key for each tag is \"{tagName}.true\". All inputs are case-insensitive. Currently, only existence (\"true\" at the end) is supported. Absence (\"false\" at the end) is not supported. Multiple values for different tag names are interpreted as \"AND\". :param str opc_request_id: (optional) Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.opsi.models.SummarizeExadataInsightResourceUtilizationInsightAggregation` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/opsi/summarize_exadata_insight_resource_utilization_insight.py.html>`__ to see an example of how to use summarize_exadata_insight_resource_utilization_insight API. """ resource_path = "/exadataInsights/resourceUtilizationInsight" method = "GET" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "analysis_time_interval", "time_interval_start", "time_interval_end", "exadata_insight_id", "exadata_type", "forecast_start_day", "forecast_days", "cdb_name", "host_name", "limit", "page", "defined_tag_equals", "freeform_tag_equals", "defined_tag_exists", "freeform_tag_exists", "opc_request_id" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "summarize_exadata_insight_resource_utilization_insight got unknown kwargs: {!r}".format(extra_kwargs)) query_params = { "compartmentId": compartment_id, "resourceType": resource_type, "resourceMetric": resource_metric, "analysisTimeInterval": kwargs.get("analysis_time_interval", missing), "timeIntervalStart": kwargs.get("time_interval_start", missing), "timeIntervalEnd": kwargs.get("time_interval_end", missing), "exadataInsightId": self.base_client.generate_collection_format_param(kwargs.get("exadata_insight_id", missing), 'multi'), "exadataType": self.base_client.generate_collection_format_param(kwargs.get("exadata_type", missing), 'multi'), "forecastStartDay": kwargs.get("forecast_start_day", missing), "forecastDays": kwargs.get("forecast_days", missing), "cdbName": self.base_client.generate_collection_format_param(kwargs.get("cdb_name", missing), 'multi'), "hostName": self.base_client.generate_collection_format_param(kwargs.get("host_name", missing), 'multi'), "limit": kwargs.get("limit", missing), "page": kwargs.get("page", missing), "definedTagEquals": self.base_client.generate_collection_format_param(kwargs.get("defined_tag_equals", missing), 'multi'), "freeformTagEquals": self.base_client.generate_collection_format_param(kwargs.get("freeform_tag_equals", missing), 'multi'), "definedTagExists": self.base_client.generate_collection_format_param(kwargs.get("defined_tag_exists", missing), 'multi'), "freeformTagExists": self.base_client.generate_collection_format_param(kwargs.get("freeform_tag_exists", missing), 'multi') } query_params = {k: v for (k, v) in six.iteritems(query_params) if v is not missing and v is not None} header_params = { "accept": "application/json", "content-type": "application/json", "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, query_params=query_params, header_params=header_params, response_type="SummarizeExadataInsightResourceUtilizationInsightAggregation") else: return self.base_client.call_api( resource_path=resource_path, method=method, query_params=query_params, header_params=header_params, response_type="SummarizeExadataInsightResourceUtilizationInsightAggregation")
[ "def", "summarize_exadata_insight_resource_utilization_insight", "(", "self", ",", "compartment_id", ",", "resource_type", ",", "resource_metric", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/exadataInsights/resourceUtilizationInsight\"", "method", "=", "\"G...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/opsi/operations_insights_client.py#L10537-L10733
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/decimal.py
python
Context.logical_or
(self, a, b)
return a.logical_or(b, context=self)
Applies the logical operation 'or' between each operand's digits. The operands must be both logical numbers. >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) Decimal('0') >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) Decimal('1') >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) Decimal('1') >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) Decimal('1') >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) Decimal('1110') >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) Decimal('1110') >>> ExtendedContext.logical_or(110, 1101) Decimal('1111') >>> ExtendedContext.logical_or(Decimal(110), 1101) Decimal('1111') >>> ExtendedContext.logical_or(110, Decimal(1101)) Decimal('1111')
Applies the logical operation 'or' between each operand's digits.
[ "Applies", "the", "logical", "operation", "or", "between", "each", "operand", "s", "digits", "." ]
def logical_or(self, a, b): """Applies the logical operation 'or' between each operand's digits. The operands must be both logical numbers. >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) Decimal('0') >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) Decimal('1') >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) Decimal('1') >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) Decimal('1') >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) Decimal('1110') >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) Decimal('1110') >>> ExtendedContext.logical_or(110, 1101) Decimal('1111') >>> ExtendedContext.logical_or(Decimal(110), 1101) Decimal('1111') >>> ExtendedContext.logical_or(110, Decimal(1101)) Decimal('1111') """ a = _convert_other(a, raiseit=True) return a.logical_or(b, context=self)
[ "def", "logical_or", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "logical_or", "(", "b", ",", "context", "=", "self", ")" ]
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/decimal.py#L4608-L4633
LxMLS/lxmls-toolkit
d95c623dd13e31135f4887c3788959eb9ad3d269
lxmls/deep_learning/numpy_models/mlp.py
python
NumpyMLP.cross_entropy_loss
(self, input, output)
return -log_probability[range(num_examples), output].mean()
Cross entropy loss
Cross entropy loss
[ "Cross", "entropy", "loss" ]
def cross_entropy_loss(self, input, output): """Cross entropy loss""" num_examples = input.shape[0] log_probability, _ = self.log_forward(input) return -log_probability[range(num_examples), output].mean()
[ "def", "cross_entropy_loss", "(", "self", ",", "input", ",", "output", ")", ":", "num_examples", "=", "input", ".", "shape", "[", "0", "]", "log_probability", ",", "_", "=", "self", ".", "log_forward", "(", "input", ")", "return", "-", "log_probability", ...
https://github.com/LxMLS/lxmls-toolkit/blob/d95c623dd13e31135f4887c3788959eb9ad3d269/lxmls/deep_learning/numpy_models/mlp.py#L75-L79
compas-dev/compas
0b33f8786481f710115fb1ae5fe79abc2a9a5175
src/compas/geometry/intersections/intersections.py
python
intersection_polyline_plane
(polyline, plane, expected_number_of_intersections=None, tol=1e-6)
return intersections
Calculate the intersection point of a plane with a polyline. Reduce expected_number_of_intersections to speed up. Parameters ---------- polyline : sequence[point] or :class:`compas.geometry.Polyline` Polyline to test intersection. plane : [point, vector] or :class:`compas.geometry.Plane` Plane to compute intersection. expected_number_of_intersections : int, optional Number of useful or expected intersections. Default is the number of line segments of the polyline. tol : float, optional A tolerance for membership verification. Returns ------- list[[float, float, float]] The intersection points between the polyline segments and the plane.
Calculate the intersection point of a plane with a polyline. Reduce expected_number_of_intersections to speed up.
[ "Calculate", "the", "intersection", "point", "of", "a", "plane", "with", "a", "polyline", ".", "Reduce", "expected_number_of_intersections", "to", "speed", "up", "." ]
def intersection_polyline_plane(polyline, plane, expected_number_of_intersections=None, tol=1e-6): """Calculate the intersection point of a plane with a polyline. Reduce expected_number_of_intersections to speed up. Parameters ---------- polyline : sequence[point] or :class:`compas.geometry.Polyline` Polyline to test intersection. plane : [point, vector] or :class:`compas.geometry.Plane` Plane to compute intersection. expected_number_of_intersections : int, optional Number of useful or expected intersections. Default is the number of line segments of the polyline. tol : float, optional A tolerance for membership verification. Returns ------- list[[float, float, float]] The intersection points between the polyline segments and the plane. """ if not expected_number_of_intersections: expected_number_of_intersections = len(polyline) intersections = [] for segment in pairwise(polyline): if len(intersections) == expected_number_of_intersections: break point = intersection_segment_plane(segment, plane, tol) if point: intersections.append(point) return intersections
[ "def", "intersection_polyline_plane", "(", "polyline", ",", "plane", ",", "expected_number_of_intersections", "=", "None", ",", "tol", "=", "1e-6", ")", ":", "if", "not", "expected_number_of_intersections", ":", "expected_number_of_intersections", "=", "len", "(", "po...
https://github.com/compas-dev/compas/blob/0b33f8786481f710115fb1ae5fe79abc2a9a5175/src/compas/geometry/intersections/intersections.py#L311-L341
cisco/mindmeld
809c36112e9ea8019fe29d54d136ca14eb4fd8db
mindmeld/text_preparation/spacy_model_factory.py
python
SpacyModelFactory.validate_spacy_language
(language)
Check if the language is valid. Args: language (str, optional): Language as specified using a 639-1/2 code.
Check if the language is valid.
[ "Check", "if", "the", "language", "is", "valid", "." ]
def validate_spacy_language(language): """Check if the language is valid. Args: language (str, optional): Language as specified using a 639-1/2 code. """ if language not in SPACY_SUPPORTED_LANGUAGES: raise ValueError("Spacy does not currently support: {!r}.".format(language))
[ "def", "validate_spacy_language", "(", "language", ")", ":", "if", "language", "not", "in", "SPACY_SUPPORTED_LANGUAGES", ":", "raise", "ValueError", "(", "\"Spacy does not currently support: {!r}.\"", ".", "format", "(", "language", ")", ")" ]
https://github.com/cisco/mindmeld/blob/809c36112e9ea8019fe29d54d136ca14eb4fd8db/mindmeld/text_preparation/spacy_model_factory.py#L51-L58
flosell/trailscraper
2509b8da81b49edf375a44fbc22a58fd9e2ea928
trailscraper/iam.py
python
BaseElement.json_repr
(self)
JSON representation of the class
JSON representation of the class
[ "JSON", "representation", "of", "the", "class" ]
def json_repr(self): """JSON representation of the class""" raise NotImplementedError
[ "def", "json_repr", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/flosell/trailscraper/blob/2509b8da81b49edf375a44fbc22a58fd9e2ea928/trailscraper/iam.py#L18-L20
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/utils/vault.py
python
write_cache
(connection)
Write the vault token to cache
Write the vault token to cache
[ "Write", "the", "vault", "token", "to", "cache" ]
def write_cache(connection): """ Write the vault token to cache """ # If uses is 1 and unlimited_use_token is not true, then this is a single use token and should not be cached # In that case, we still want to cache the vault metadata lookup information for paths, so continue on if ( connection.get("uses", None) == 1 and "unlimited_use_token" not in connection and "vault_secret_path_metadata" not in connection ): log.debug("Not caching vault single use token") __context__["vault_token"] = connection return True elif ( "vault_secret_path_metadata" in __context__ and "vault_secret_path_metadata" not in connection ): # If session storage is being used, and info passed is not the already saved metadata log.debug("Storing token only for this session") __context__["vault_token"] = connection return True elif "vault_secret_path_metadata" in __context__: # Must have been passed metadata. This is already handled by _get_secret_path_metadata # and does not need to be resaved return True cache_file = os.path.join(__opts__["cachedir"], "salt_vault_token") try: log.debug("Writing vault cache file") # Detect if token was issued without use limit if connection.get("uses") == 0: connection["unlimited_use_token"] = True else: connection["unlimited_use_token"] = False with salt.utils.files.fpopen(cache_file, "w", mode=0o600) as fp_: fp_.write(salt.utils.json.dumps(connection)) return True except OSError: log.error( "Failed to cache vault information", exc_info_on_loglevel=logging.DEBUG ) return False
[ "def", "write_cache", "(", "connection", ")", ":", "# If uses is 1 and unlimited_use_token is not true, then this is a single use token and should not be cached", "# In that case, we still want to cache the vault metadata lookup information for paths, so continue on", "if", "(", "connection", ...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/utils/vault.py#L204-L246
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/collections/__init__.py
python
Counter.elements
(self)
return _chain.from_iterable(_starmap(_repeat, self.items()))
Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors ... product *= factor # and multiply them >>> product 1836 Note, if an element's count has been set to zero or is a negative number, elements() will ignore it.
Iterator over elements repeating each as many times as its count.
[ "Iterator", "over", "elements", "repeating", "each", "as", "many", "times", "as", "its", "count", "." ]
def elements(self): '''Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors ... product *= factor # and multiply them >>> product 1836 Note, if an element's count has been set to zero or is a negative number, elements() will ignore it. ''' # Emulate Bag.do from Smalltalk and Multiset.begin from C++. return _chain.from_iterable(_starmap(_repeat, self.items()))
[ "def", "elements", "(", "self", ")", ":", "# Emulate Bag.do from Smalltalk and Multiset.begin from C++.", "return", "_chain", ".", "from_iterable", "(", "_starmap", "(", "_repeat", ",", "self", ".", "items", "(", ")", ")", ")" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/collections/__init__.py#L557-L577
Cue/ocstyle
aec49228f7a4aee9d20f9de51ae50bb969075aee
src/ocstyle/rules.py
python
keyword
(_)
return None
Matches keywords.
Matches keywords.
[ "Matches", "keywords", "." ]
def keyword(_): """Matches keywords.""" return None
[ "def", "keyword", "(", "_", ")", ":", "return", "None" ]
https://github.com/Cue/ocstyle/blob/aec49228f7a4aee9d20f9de51ae50bb969075aee/src/ocstyle/rules.py#L522-L524
google-research/language
61fa7260ac7d690d11ef72ca863e45a37c0bdc80
language/compir/dataset_parsers/scan_parser.py
python
ScanParser._get_atom_map
(self)
return atom_map
Gets (utterance, program) pairs, used for adding brackets to programs.
Gets (utterance, program) pairs, used for adding brackets to programs.
[ "Gets", "(", "utterance", "program", ")", "pairs", "used", "for", "adding", "brackets", "to", "programs", "." ]
def _get_atom_map(self): """Gets (utterance, program) pairs, used for adding brackets to programs.""" atoms = [ ("turn left", "I_TURN_LEFT"), ("turn right", "I_TURN_RIGHT"), ("walk left", "I_TURN_LEFT I_WALK"), ("run left", "I_TURN_LEFT I_RUN"), ("look left", "I_TURN_LEFT I_LOOK"), ("jump left", "I_TURN_LEFT I_JUMP"), ("walk right", "I_TURN_RIGHT I_WALK"), ("run right", "I_TURN_RIGHT I_RUN"), ("look right", "I_TURN_RIGHT I_LOOK"), ("jump right", "I_TURN_RIGHT I_JUMP"), ("walk", "I_WALK"), ("run", "I_RUN"), ("look", "I_LOOK"), ("jump", "I_JUMP"), ("turn opposite left", "I_TURN_LEFT I_TURN_LEFT"), ("turn opposite right", "I_TURN_RIGHT I_TURN_RIGHT"), ("walk opposite left", "I_TURN_LEFT I_TURN_LEFT I_WALK"), ("walk opposite right", "I_TURN_RIGHT I_TURN_RIGHT I_WALK"), ("run opposite left", "I_TURN_LEFT I_TURN_LEFT I_RUN"), ("run opposite right", "I_TURN_RIGHT I_TURN_RIGHT I_RUN"), ("look opposite left", "I_TURN_LEFT I_TURN_LEFT I_LOOK"), ("look opposite right", "I_TURN_RIGHT I_TURN_RIGHT I_LOOK"), ("jump opposite left", "I_TURN_LEFT I_TURN_LEFT I_JUMP"), ("jump opposite right", "I_TURN_RIGHT I_TURN_RIGHT I_JUMP"), ("turn around left", "I_TURN_LEFT I_TURN_LEFT I_TURN_LEFT I_TURN_LEFT"), ("turn around right", "I_TURN_RIGHT I_TURN_RIGHT I_TURN_RIGHT I_TURN_RIGHT"), ("walk around left", "I_TURN_LEFT I_WALK I_TURN_LEFT I_WALK I_TURN_LEFT I_WALK I_TURN_LEFT" " I_WALK"), ("walk around right", "I_TURN_RIGHT I_WALK I_TURN_RIGHT I_WALK I_TURN_RIGHT I_WALK " "I_TURN_RIGHT I_WALK"), ("run around left", "I_TURN_LEFT I_RUN I_TURN_LEFT I_RUN I_TURN_LEFT I_RUN I_TURN_LEFT I_RUN" ), ("run around right", "I_TURN_RIGHT I_RUN I_TURN_RIGHT I_RUN I_TURN_RIGHT I_RUN " "I_TURN_RIGHT I_RUN"), ("look around left", "I_TURN_LEFT I_LOOK I_TURN_LEFT I_LOOK I_TURN_LEFT I_LOOK I_TURN_LEFT" " I_LOOK"), ("look around right", "I_TURN_RIGHT I_LOOK I_TURN_RIGHT I_LOOK " "I_TURN_RIGHT I_LOOK " "I_TURN_RIGHT I_LOOK"), ("jump around left", "I_TURN_LEFT I_JUMP I_TURN_LEFT I_JUMP I_TURN_LEFT I_JUMP I_TURN_LEFT" "" " I_JUMP"), ("jump around right", "I_TURN_RIGHT I_JUMP I_TURN_RIGHT I_JUMP I_TURN_RIGHT I_JUMP " "I_TURN_RIGHT I_JUMP"), ] atom_map = {atom[0]: atom[1] for atom in atoms} # Adds "X twice" actions. atom_map.update({ "{} twice".format(atom[0]): "{} {}".format(atom[1], atom[1]) for atom in atoms }) # Adds "X thrice" actions. atom_map.update({ "{} thrice".format(atom[0]): "{} {} {}".format(atom[1], atom[1], atom[1]) for atom in atoms }) return atom_map
[ "def", "_get_atom_map", "(", "self", ")", ":", "atoms", "=", "[", "(", "\"turn left\"", ",", "\"I_TURN_LEFT\"", ")", ",", "(", "\"turn right\"", ",", "\"I_TURN_RIGHT\"", ")", ",", "(", "\"walk left\"", ",", "\"I_TURN_LEFT I_WALK\"", ")", ",", "(", "\"run left\...
https://github.com/google-research/language/blob/61fa7260ac7d690d11ef72ca863e45a37c0bdc80/language/compir/dataset_parsers/scan_parser.py#L109-L176
guildai/guildai
1665985a3d4d788efc1a3180ca51cc417f71ca78
guild/op_util.py
python
_default_run_label
(flag_vals)
return " ".join( flag_util.flag_assigns(non_null, truncate_floats=True, shorten_paths=True) )
Returns a default run label for a map of flag values. The default label is a string containing flag assign as NAME=VALUE.
Returns a default run label for a map of flag values.
[ "Returns", "a", "default", "run", "label", "for", "a", "map", "of", "flag", "values", "." ]
def _default_run_label(flag_vals): """Returns a default run label for a map of flag values. The default label is a string containing flag assign as NAME=VALUE. """ non_null = {name: val for name, val in flag_vals.items() if val is not None} return " ".join( flag_util.flag_assigns(non_null, truncate_floats=True, shorten_paths=True) )
[ "def", "_default_run_label", "(", "flag_vals", ")", ":", "non_null", "=", "{", "name", ":", "val", "for", "name", ",", "val", "in", "flag_vals", ".", "items", "(", ")", "if", "val", "is", "not", "None", "}", "return", "\" \"", ".", "join", "(", "flag...
https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/op_util.py#L692-L700
alicevision/meshroom
92004286fd0bc8ab36bd3575b4c0166090e665e1
meshroom/ui/reconstruction.py
python
ViewpointWrapper.pose
(self)
return QMatrix4x4( self._R[0], -self._R[1], -self._R[2], self._T[0], self._R[3], -self._R[4], -self._R[5], self._T[1], self._R[6], -self._R[7], -self._R[8], self._T[2], 0, 0, 0, 1 )
Get the camera pose of 'viewpoint' as a 4x4 matrix.
Get the camera pose of 'viewpoint' as a 4x4 matrix.
[ "Get", "the", "camera", "pose", "of", "viewpoint", "as", "a", "4x4", "matrix", "." ]
def pose(self): """ Get the camera pose of 'viewpoint' as a 4x4 matrix. """ if self._R is None or self._T is None: return None # convert transform matrix for Qt return QMatrix4x4( self._R[0], -self._R[1], -self._R[2], self._T[0], self._R[3], -self._R[4], -self._R[5], self._T[1], self._R[6], -self._R[7], -self._R[8], self._T[2], 0, 0, 0, 1 )
[ "def", "pose", "(", "self", ")", ":", "if", "self", ".", "_R", "is", "None", "or", "self", ".", "_T", "is", "None", ":", "return", "None", "# convert transform matrix for Qt", "return", "QMatrix4x4", "(", "self", ".", "_R", "[", "0", "]", ",", "-", "...
https://github.com/alicevision/meshroom/blob/92004286fd0bc8ab36bd3575b4c0166090e665e1/meshroom/ui/reconstruction.py#L318-L329
PyTorchLightning/pytorch-lightning
5914fb748fb53d826ab337fc2484feab9883a104
pytorch_lightning/utilities/memory.py
python
get_memory_profile
(mode: str)
return memory_map
r""" .. deprecated:: v1.5 This function was deprecated in v1.5 in favor of `pytorch_lightning.accelerators.gpu._get_nvidia_gpu_stats` and will be removed in v1.7. Get a profile of the current memory usage. Args: mode: There are two modes: - 'all' means return memory for all gpus - 'min_max' means return memory for max and min Return: A dictionary in which the keys are device ids as integers and values are memory usage as integers in MB. If mode is 'min_max', the dictionary will also contain two additional keys: - 'min_gpu_mem': the minimum memory usage in MB - 'max_gpu_mem': the maximum memory usage in MB
r""" .. deprecated:: v1.5 This function was deprecated in v1.5 in favor of `pytorch_lightning.accelerators.gpu._get_nvidia_gpu_stats` and will be removed in v1.7.
[ "r", "..", "deprecated", "::", "v1", ".", "5", "This", "function", "was", "deprecated", "in", "v1", ".", "5", "in", "favor", "of", "pytorch_lightning", ".", "accelerators", ".", "gpu", ".", "_get_nvidia_gpu_stats", "and", "will", "be", "removed", "in", "v1...
def get_memory_profile(mode: str) -> Dict[str, float]: r""" .. deprecated:: v1.5 This function was deprecated in v1.5 in favor of `pytorch_lightning.accelerators.gpu._get_nvidia_gpu_stats` and will be removed in v1.7. Get a profile of the current memory usage. Args: mode: There are two modes: - 'all' means return memory for all gpus - 'min_max' means return memory for max and min Return: A dictionary in which the keys are device ids as integers and values are memory usage as integers in MB. If mode is 'min_max', the dictionary will also contain two additional keys: - 'min_gpu_mem': the minimum memory usage in MB - 'max_gpu_mem': the maximum memory usage in MB """ memory_map = get_gpu_memory_map() if mode == "min_max": min_index, min_memory = min(memory_map.items(), key=lambda item: item[1]) max_index, max_memory = max(memory_map.items(), key=lambda item: item[1]) memory_map = {"min_gpu_mem": min_memory, "max_gpu_mem": max_memory} return memory_map
[ "def", "get_memory_profile", "(", "mode", ":", "str", ")", "->", "Dict", "[", "str", ",", "float", "]", ":", "memory_map", "=", "get_gpu_memory_map", "(", ")", "if", "mode", "==", "\"min_max\"", ":", "min_index", ",", "min_memory", "=", "min", "(", "memo...
https://github.com/PyTorchLightning/pytorch-lightning/blob/5914fb748fb53d826ab337fc2484feab9883a104/pytorch_lightning/utilities/memory.py#L111-L141
RTIInternational/gobbli
d9ec8132f74ce49dc4bead2fad25b661bcef6e76
gobbli/io.py
python
validate_X
(X: List[str])
Confirm a given array matches the expected type for input. Args: X: Something that should be valid model input.
Confirm a given array matches the expected type for input.
[ "Confirm", "a", "given", "array", "matches", "the", "expected", "type", "for", "input", "." ]
def validate_X(X: List[str]): """ Confirm a given array matches the expected type for input. Args: X: Something that should be valid model input. """ _check_string_list(X)
[ "def", "validate_X", "(", "X", ":", "List", "[", "str", "]", ")", ":", "_check_string_list", "(", "X", ")" ]
https://github.com/RTIInternational/gobbli/blob/d9ec8132f74ce49dc4bead2fad25b661bcef6e76/gobbli/io.py#L55-L62
vilemduha/blendercam
3bd98ace230464d68d9ff86eae595481ec98ffc0
scripts/addons/cam/nc/nc.py
python
Creator.set_plane
(self, plane)
Set plane
Set plane
[ "Set", "plane" ]
def set_plane(self, plane): """Set plane""" pass
[ "def", "set_plane", "(", "self", ",", "plane", ")", ":", "pass" ]
https://github.com/vilemduha/blendercam/blob/3bd98ace230464d68d9ff86eae595481ec98ffc0/scripts/addons/cam/nc/nc.py#L112-L114
pyproj4/pyproj
24eade78c52f8bf6717e56fb7c878f7da9892368
pyproj/crs/coordinate_operation.py
python
MercatorAConversion.__new__
( cls, latitude_natural_origin: float = 0.0, longitude_natural_origin: float = 0.0, false_easting: float = 0.0, false_northing: float = 0.0, scale_factor_natural_origin: float = 1.0, )
return cls.from_json_dict(merc_json)
Parameters ---------- longitude_natural_origin: float, default=0.0 Latitude of natural origin (lat_0). longitude_natural_origin: float, default=0.0 Longitude of natural origin (lon_0). false_easting: float, default=0.0 False easting (x_0). false_northing: float, default=0.0 False northing (y_0). scale_factor_natural_origin: float, default=1.0 Scale factor at natural origin (k or k_0).
Parameters ---------- longitude_natural_origin: float, default=0.0 Latitude of natural origin (lat_0). longitude_natural_origin: float, default=0.0 Longitude of natural origin (lon_0). false_easting: float, default=0.0 False easting (x_0). false_northing: float, default=0.0 False northing (y_0). scale_factor_natural_origin: float, default=1.0 Scale factor at natural origin (k or k_0).
[ "Parameters", "----------", "longitude_natural_origin", ":", "float", "default", "=", "0", ".", "0", "Latitude", "of", "natural", "origin", "(", "lat_0", ")", ".", "longitude_natural_origin", ":", "float", "default", "=", "0", ".", "0", "Longitude", "of", "nat...
def __new__( cls, latitude_natural_origin: float = 0.0, longitude_natural_origin: float = 0.0, false_easting: float = 0.0, false_northing: float = 0.0, scale_factor_natural_origin: float = 1.0, ): """ Parameters ---------- longitude_natural_origin: float, default=0.0 Latitude of natural origin (lat_0). longitude_natural_origin: float, default=0.0 Longitude of natural origin (lon_0). false_easting: float, default=0.0 False easting (x_0). false_northing: float, default=0.0 False northing (y_0). scale_factor_natural_origin: float, default=1.0 Scale factor at natural origin (k or k_0). """ merc_json = { "$schema": "https://proj.org/schemas/v0.2/projjson.schema.json", "type": "Conversion", "name": "unknown", "method": { "name": "Mercator (variant A)", "id": {"authority": "EPSG", "code": 9804}, }, "parameters": [ { "name": "Latitude of natural origin", "value": latitude_natural_origin, "unit": "degree", "id": {"authority": "EPSG", "code": 8801}, }, { "name": "Longitude of natural origin", "value": longitude_natural_origin, "unit": "degree", "id": {"authority": "EPSG", "code": 8802}, }, { "name": "Scale factor at natural origin", "value": scale_factor_natural_origin, "unit": "unity", "id": {"authority": "EPSG", "code": 8805}, }, { "name": "False easting", "value": false_easting, "unit": "metre", "id": {"authority": "EPSG", "code": 8806}, }, { "name": "False northing", "value": false_northing, "unit": "metre", "id": {"authority": "EPSG", "code": 8807}, }, ], } return cls.from_json_dict(merc_json)
[ "def", "__new__", "(", "cls", ",", "latitude_natural_origin", ":", "float", "=", "0.0", ",", "longitude_natural_origin", ":", "float", "=", "0.0", ",", "false_easting", ":", "float", "=", "0.0", ",", "false_northing", ":", "float", "=", "0.0", ",", "scale_fa...
https://github.com/pyproj4/pyproj/blob/24eade78c52f8bf6717e56fb7c878f7da9892368/pyproj/crs/coordinate_operation.py#L679-L743
PacificBiosciences/FALCON
ab80e88e1278879f28fe83b9fa0382249213444e
falcon_kit/run_support.py
python
update_job_sections
(config)
More for backwards compatibility with stuff from 'General' section.
More for backwards compatibility with stuff from 'General' section.
[ "More", "for", "backwards", "compatibility", "with", "stuff", "from", "General", "section", "." ]
def update_job_sections(config): """More for backwards compatibility with stuff from 'General' section. """ update_job_defaults_section(config) General = config['General'] # Update a few where the names change and the section is non-default. def update_step_job_opts(name): if General.get('sge_option_'+name) and 'JOB_OPTS' not in config['job.step.'+name]: config['job.step.'+name]['JOB_OPTS'] = General['sge_option_'+name] def update_step_njobs(name): if General.get(name+'_concurrent_jobs') and 'njobs' not in config['job.step.'+name]: config['job.step.'+name]['njobs'] = int(General[name+'_concurrent_jobs']) for name in ['da', 'la', 'pda', 'pla', 'cns', 'fc', 'asm']: update_step_job_opts(name) update_step_njobs(name) # Prefer 'asm' to 'fc'. asm = dict(config['job.step.asm']) config['job.step.asm'] = config['job.step.fc'] del config['job.step.fc'] config['job.step.asm'].update(asm)
[ "def", "update_job_sections", "(", "config", ")", ":", "update_job_defaults_section", "(", "config", ")", "General", "=", "config", "[", "'General'", "]", "# Update a few where the names change and the section is non-default.", "def", "update_step_job_opts", "(", "name", ")...
https://github.com/PacificBiosciences/FALCON/blob/ab80e88e1278879f28fe83b9fa0382249213444e/falcon_kit/run_support.py#L256-L276
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/httplib.py
python
HTTPConnection._send_output
(self, message_body=None)
Send the currently buffered request and clear the buffer. Appends an extra \\r\\n to the buffer. A message_body may be specified, to be appended to the request.
Send the currently buffered request and clear the buffer.
[ "Send", "the", "currently", "buffered", "request", "and", "clear", "the", "buffer", "." ]
def _send_output(self, message_body=None): """Send the currently buffered request and clear the buffer. Appends an extra \\r\\n to the buffer. A message_body may be specified, to be appended to the request. """ self._buffer.extend(("", "")) msg = "\r\n".join(self._buffer) del self._buffer[:] # If msg and message_body are sent in a single send() call, # it will avoid performance problems caused by the interaction # between delayed ack and the Nagle algorithm. if isinstance(message_body, str): msg += message_body message_body = None self.send(msg) if message_body is not None: #message_body was not a string (i.e. it is a file) and #we must run the risk of Nagle self.send(message_body)
[ "def", "_send_output", "(", "self", ",", "message_body", "=", "None", ")", ":", "self", ".", "_buffer", ".", "extend", "(", "(", "\"\"", ",", "\"\"", ")", ")", "msg", "=", "\"\\r\\n\"", ".", "join", "(", "self", ".", "_buffer", ")", "del", "self", ...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/httplib.py#L814-L833
IlyaGusev/rupo
83a5fac0dddd480a401181e5465f0e3c94ad2dcc
rupo/stress/word.py
python
Stress.__str__
(self)
return str(self.position) + "\t" + str(self.type)
[]
def __str__(self): return str(self.position) + "\t" + str(self.type)
[ "def", "__str__", "(", "self", ")", ":", "return", "str", "(", "self", ".", "position", ")", "+", "\"\\t\"", "+", "str", "(", "self", ".", "type", ")" ]
https://github.com/IlyaGusev/rupo/blob/83a5fac0dddd480a401181e5465f0e3c94ad2dcc/rupo/stress/word.py#L30-L31
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/pkg_resources/_vendor/packaging/version.py
python
_parse_local_version
(local)
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
[ "Takes", "a", "string", "like", "abc", ".", "1", ".", "twelve", "and", "turns", "it", "into", "(", "abc", "1", "twelve", ")", "." ]
def _parse_local_version(local): """ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). """ if local is not None: return tuple( part.lower() if not part.isdigit() else int(part) for part in _local_version_seperators.split(local) )
[ "def", "_parse_local_version", "(", "local", ")", ":", "if", "local", "is", "not", "None", ":", "return", "tuple", "(", "part", ".", "lower", "(", ")", "if", "not", "part", ".", "isdigit", "(", ")", "else", "int", "(", "part", ")", "for", "part", "...
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/pkg_resources/_vendor/packaging/version.py#L332-L340
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/procedures/linux_kernel/fstat64.py
python
fstat64._store_amd64
(self, stat_buf, stat)
[]
def _store_amd64(self, stat_buf, stat): store = lambda offset, val: self.state.memory.store(stat_buf + offset, val, endness='Iend_LE') store(0x00, stat.st_dev) store(0x08, stat.st_ino) store(0x10, stat.st_mode) store(0x18, stat.st_nlink) store(0x1c, stat.st_uid) store(0x20, stat.st_gid) store(0x24, self.state.solver.BVV(0, 32)) store(0x28, stat.st_rdev) store(0x30, stat.st_size) store(0x38, stat.st_blksize) store(0x40, stat.st_blocks) store(0x48, stat.st_atime) store(0x50, stat.st_atimensec) store(0x58, stat.st_mtime) store(0x60, stat.st_mtimensec) store(0x68, stat.st_ctime) store(0x70, stat.st_ctimensec) store(0x78, self.state.solver.BVV(0, 64)) store(0x80, self.state.solver.BVV(0, 64)) store(0x88, self.state.solver.BVV(0, 64))
[ "def", "_store_amd64", "(", "self", ",", "stat_buf", ",", "stat", ")", ":", "store", "=", "lambda", "offset", ",", "val", ":", "self", ".", "state", ".", "memory", ".", "store", "(", "stat_buf", "+", "offset", ",", "val", ",", "endness", "=", "'Iend_...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/procedures/linux_kernel/fstat64.py#L67-L89
cournape/Bento
37de23d784407a7c98a4a15770ffc570d5f32d70
bento/parser/lexer.py
python
t_insidemstringnotcontinued_WS
(t)
return t
[]
def t_insidemstringnotcontinued_WS(t): return t
[ "def", "t_insidemstringnotcontinued_WS", "(", "t", ")", ":", "return", "t" ]
https://github.com/cournape/Bento/blob/37de23d784407a7c98a4a15770ffc570d5f32d70/bento/parser/lexer.py#L326-L327
NTMC-Community/MatchZoo-py
0e5c04e1e948aa9277abd5c85ff99d9950d8527f
matchzoo/tasks/ranking.py
python
Ranking.list_available_metrics
(cls)
return ['map']
:return: a list of available metrics.
:return: a list of available metrics.
[ ":", "return", ":", "a", "list", "of", "available", "metrics", "." ]
def list_available_metrics(cls) -> list: """:return: a list of available metrics.""" return ['map']
[ "def", "list_available_metrics", "(", "cls", ")", "->", "list", ":", "return", "[", "'map'", "]" ]
https://github.com/NTMC-Community/MatchZoo-py/blob/0e5c04e1e948aa9277abd5c85ff99d9950d8527f/matchzoo/tasks/ranking.py#L29-L31
yt-project/yt
dc7b24f9b266703db4c843e329c6c8644d47b824
yt/frontends/enzo_e/data_structures.py
python
EnzoEHierarchy._setup_derived_fields
(self)
[]
def _setup_derived_fields(self): super()._setup_derived_fields() for fname, field in self.ds.field_info.items(): if not field.particle_type: continue if isinstance(fname, tuple): continue if field._function is NullFunc: continue
[ "def", "_setup_derived_fields", "(", "self", ")", ":", "super", "(", ")", ".", "_setup_derived_fields", "(", ")", "for", "fname", ",", "field", "in", "self", ".", "ds", ".", "field_info", ".", "items", "(", ")", ":", "if", "not", "field", ".", "particl...
https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/frontends/enzo_e/data_structures.py#L255-L263
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/notpip/_internal/operations/install/wheel.py
python
install_wheel
( name, # type: str wheel_path, # type: str scheme, # type: Scheme req_description, # type: str pycompile=True, # type: bool warn_script_location=True, # type: bool direct_url=None, # type: Optional[DirectUrl] requested=False, # type: bool )
[]
def install_wheel( name, # type: str wheel_path, # type: str scheme, # type: Scheme req_description, # type: str pycompile=True, # type: bool warn_script_location=True, # type: bool direct_url=None, # type: Optional[DirectUrl] requested=False, # type: bool ): # type: (...) -> None with ZipFile(wheel_path, allowZip64=True) as z: with req_error_context(req_description): _install_wheel( name=name, wheel_zip=z, wheel_path=wheel_path, scheme=scheme, pycompile=pycompile, warn_script_location=warn_script_location, direct_url=direct_url, requested=requested, )
[ "def", "install_wheel", "(", "name", ",", "# type: str", "wheel_path", ",", "# type: str", "scheme", ",", "# type: Scheme", "req_description", ",", "# type: str", "pycompile", "=", "True", ",", "# type: bool", "warn_script_location", "=", "True", ",", "# type: bool", ...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_internal/operations/install/wheel.py#L781-L803
polakowo/vectorbt
6638735c131655760474d72b9f045d1dbdbd8fe9
vectorbt/utils/checks.py
python
is_index
(arg: tp.Any)
return isinstance(arg, pd.Index)
Check whether the argument is `pd.Index`.
Check whether the argument is `pd.Index`.
[ "Check", "whether", "the", "argument", "is", "pd", ".", "Index", "." ]
def is_index(arg: tp.Any) -> bool: """Check whether the argument is `pd.Index`.""" return isinstance(arg, pd.Index)
[ "def", "is_index", "(", "arg", ":", "tp", ".", "Any", ")", "->", "bool", ":", "return", "isinstance", "(", "arg", ",", "pd", ".", "Index", ")" ]
https://github.com/polakowo/vectorbt/blob/6638735c131655760474d72b9f045d1dbdbd8fe9/vectorbt/utils/checks.py#L32-L34
vispy/vispy
26256fdc2574259dd227022fbce0767cae4e244b
vispy/visuals/graphs/layouts/networkx_layout.py
python
NetworkxCoordinates.__call__
(self, adjacency_mat, directed=False)
Parameters ---------- adjacency_mat : sparse adjacency matrix. directed : bool, default False Returns --------- (node_vertices, line_vertices, arrow_vertices) : tuple Yields the node and line vertices in a tuple. This layout only yields a single time, and has no builtin animation
Parameters ---------- adjacency_mat : sparse adjacency matrix. directed : bool, default False
[ "Parameters", "----------", "adjacency_mat", ":", "sparse", "adjacency", "matrix", ".", "directed", ":", "bool", "default", "False" ]
def __call__(self, adjacency_mat, directed=False): """ Parameters ---------- adjacency_mat : sparse adjacency matrix. directed : bool, default False Returns --------- (node_vertices, line_vertices, arrow_vertices) : tuple Yields the node and line vertices in a tuple. This layout only yields a single time, and has no builtin animation """ if issparse(adjacency_mat): adjacency_mat = adjacency_mat.tocoo() line_vertices, arrows = _straight_line_vertices( adjacency_mat, self.positions, directed) yield self.positions, line_vertices, arrows
[ "def", "__call__", "(", "self", ",", "adjacency_mat", ",", "directed", "=", "False", ")", ":", "if", "issparse", "(", "adjacency_mat", ")", ":", "adjacency_mat", "=", "adjacency_mat", ".", "tocoo", "(", ")", "line_vertices", ",", "arrows", "=", "_straight_li...
https://github.com/vispy/vispy/blob/26256fdc2574259dd227022fbce0767cae4e244b/vispy/visuals/graphs/layouts/networkx_layout.py#L64-L82
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python3-alpha/python-libs/bs4/element.py
python
PageElement.find_next_sibling
(self, name=None, attrs={}, text=None, **kwargs)
return self._find_one(self.find_next_siblings, name, attrs, text, **kwargs)
Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.
Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.
[ "Returns", "the", "closest", "sibling", "to", "this", "Tag", "that", "matches", "the", "given", "criteria", "and", "appears", "after", "this", "Tag", "in", "the", "document", "." ]
def find_next_sibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.""" return self._find_one(self.find_next_siblings, name, attrs, text, **kwargs)
[ "def", "find_next_sibling", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_find_one", "(", "self", ".", "find_next_siblings", ",", "name", ",",...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/bs4/element.py#L258-L262
magmax/python-inquirer
ef7487247b46f33032f54a1547c9b8d9b8287c2b
noxfile.py
python
activate_virtualenv_in_precommit_hooks
(session: Session)
Activate virtualenv in hooks installed by pre-commit. This function patches git hooks installed by pre-commit to activate the session's virtual environment. This allows pre-commit to locate hooks in that environment when invoked from git. Args: session: The Session object.
Activate virtualenv in hooks installed by pre-commit.
[ "Activate", "virtualenv", "in", "hooks", "installed", "by", "pre", "-", "commit", "." ]
def activate_virtualenv_in_precommit_hooks(session: Session) -> None: """Activate virtualenv in hooks installed by pre-commit. This function patches git hooks installed by pre-commit to activate the session's virtual environment. This allows pre-commit to locate hooks in that environment when invoked from git. Args: session: The Session object. """ assert session.bin is not None # noqa: S101 # Only patch hooks containing a reference to this session's bindir. Support # quoting rules for Python and bash, but strip the outermost quotes so we # can detect paths within the bindir, like <bindir>/python. bindirs = [ bindir[1:-1] if bindir[0] in "'\"" else bindir for bindir in (repr(session.bin), shlex.quote(session.bin)) ] virtualenv = session.env.get("VIRTUAL_ENV") if virtualenv is None: return headers = { # pre-commit < 2.16.0 "python": f"""\ import os os.environ["VIRTUAL_ENV"] = {virtualenv!r} os.environ["PATH"] = os.pathsep.join(( {session.bin!r}, os.environ.get("PATH", ""), )) """, # pre-commit >= 2.16.0 "bash": f"""\ VIRTUAL_ENV={shlex.quote(virtualenv)} PATH={shlex.quote(session.bin)}"{os.pathsep}$PATH" """, } hookdir = Path(".git") / "hooks" if not hookdir.is_dir(): return for hook in hookdir.iterdir(): if hook.name.endswith(".sample") or not hook.is_file(): continue if not hook.read_bytes().startswith(b"#!"): continue text = hook.read_text() if not any(Path("A") == Path("a") and bindir.lower() in text.lower() or bindir in text for bindir in bindirs): continue lines = text.splitlines() for executable, header in headers.items(): if executable in lines[0].lower(): lines.insert(1, dedent(header)) hook.write_text("\n".join(lines)) break
[ "def", "activate_virtualenv_in_precommit_hooks", "(", "session", ":", "Session", ")", "->", "None", ":", "assert", "session", ".", "bin", "is", "not", "None", "# noqa: S101", "# Only patch hooks containing a reference to this session's bindir. Support", "# quoting rules for Pyt...
https://github.com/magmax/python-inquirer/blob/ef7487247b46f33032f54a1547c9b8d9b8287c2b/noxfile.py#L35-L97
tsenghungchen/SA-tensorflow
6aad7dbf609e64dd652e9204518eddc6674168a4
pycocoevalcap/bleu/bleu_scorer.py
python
BleuScorer.score_ratio
(self, option=None)
return (self.fscore(option=option), self.ratio(option=option))
return (bleu, len_ratio) pair
return (bleu, len_ratio) pair
[ "return", "(", "bleu", "len_ratio", ")", "pair" ]
def score_ratio(self, option=None): '''return (bleu, len_ratio) pair''' return (self.fscore(option=option), self.ratio(option=option))
[ "def", "score_ratio", "(", "self", ",", "option", "=", "None", ")", ":", "return", "(", "self", ".", "fscore", "(", "option", "=", "option", ")", ",", "self", ".", "ratio", "(", "option", "=", "option", ")", ")" ]
https://github.com/tsenghungchen/SA-tensorflow/blob/6aad7dbf609e64dd652e9204518eddc6674168a4/pycocoevalcap/bleu/bleu_scorer.py#L126-L128
IdentityPython/pysaml2
6badb32d212257bd83ffcc816f9b625f68281b47
src/saml2/ws/wspol.py
python
operator_content_type__from_string
(xml_string)
return saml2.create_class_from_xml_string(OperatorContentType_, xml_string)
[]
def operator_content_type__from_string(xml_string): return saml2.create_class_from_xml_string(OperatorContentType_, xml_string)
[ "def", "operator_content_type__from_string", "(", "xml_string", ")", ":", "return", "saml2", ".", "create_class_from_xml_string", "(", "OperatorContentType_", ",", "xml_string", ")" ]
https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/ws/wspol.py#L134-L135
bendichter/brokenaxes
191a534e64054f0e155cd7398832e44c681ed539
brokenaxes.py
python
BrokenAxes.set_title
(self, *args, **kwargs)
return self.big_ax.set_title(*args, **kwargs)
[]
def set_title(self, *args, **kwargs): return self.big_ax.set_title(*args, **kwargs)
[ "def", "set_title", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "big_ax", ".", "set_title", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/bendichter/brokenaxes/blob/191a534e64054f0e155cd7398832e44c681ed539/brokenaxes.py#L329-L330
MaurizioFD/RecSys2019_DeepLearning_Evaluation
0fb6b7f5c396f8525316ed66cf9c9fdb03a5fa9b
CNN_on_embeddings/IJCAI/CFM_our_interface/Dataset_wrapper.py
python
dict_to_sparse_matrix
(d:dict, shape:tuple)
return sparse_matrix
Convert a dictionary to a sparse matrix
Convert a dictionary to a sparse matrix
[ "Convert", "a", "dictionary", "to", "a", "sparse", "matrix" ]
def dict_to_sparse_matrix(d:dict, shape:tuple): """ Convert a dictionary to a sparse matrix """ tot_items = 0 row_ind = [] col_ind = [] for k, v in d.items(): c = len(v) row_ind.extend([k] * c) col_ind.extend(v) tot_items += c data = np.ones(tot_items) sparse_matrix = sps.csr_matrix((data, (row_ind, col_ind)), shape=shape) assert sparse_matrix.nnz == len(data), "Duplicate entries found" return sparse_matrix
[ "def", "dict_to_sparse_matrix", "(", "d", ":", "dict", ",", "shape", ":", "tuple", ")", ":", "tot_items", "=", "0", "row_ind", "=", "[", "]", "col_ind", "=", "[", "]", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "c", "=", "len...
https://github.com/MaurizioFD/RecSys2019_DeepLearning_Evaluation/blob/0fb6b7f5c396f8525316ed66cf9c9fdb03a5fa9b/CNN_on_embeddings/IJCAI/CFM_our_interface/Dataset_wrapper.py#L14-L30
chapmanb/bcbb
dbfb52711f0bfcc1d26c5a5b53c9ff4f50dc0027
nextgen/bcbio/broad/metrics.py
python
RNASeqPicardMetrics.report
(self, align_bam, ref_file, gtf_file, is_paired=False, rrna_file="null")
return summary_info, graphs
Produce report metrics for a RNASeq experiment using Picard with a sorted aligned BAM file.
Produce report metrics for a RNASeq experiment using Picard with a sorted aligned BAM file.
[ "Produce", "report", "metrics", "for", "a", "RNASeq", "experiment", "using", "Picard", "with", "a", "sorted", "aligned", "BAM", "file", "." ]
def report(self, align_bam, ref_file, gtf_file, is_paired=False, rrna_file="null"): """Produce report metrics for a RNASeq experiment using Picard with a sorted aligned BAM file. """ # collect duplication metrics dup_bam, dup_metrics = self._get_current_dup_metrics(align_bam) align_metrics = self._collect_align_metrics(align_bam, ref_file) insert_graph, insert_metrics = (None, None) if is_paired: insert_graph, insert_metrics = self._insert_sizes(align_bam) rnaseq_metrics = self._rnaseq_metrics(align_bam, gtf_file, rrna_file) summary_info = self._parser.get_summary_metrics(align_metrics, dup_metrics, insert_metrics=insert_metrics, rnaseq_metrics=rnaseq_metrics) pprint.pprint(summary_info) graphs = [] if insert_graph and file_exists(insert_graph): graphs.append((insert_graph, "Distribution of paired end insert sizes")) return summary_info, graphs
[ "def", "report", "(", "self", ",", "align_bam", ",", "ref_file", ",", "gtf_file", ",", "is_paired", "=", "False", ",", "rrna_file", "=", "\"null\"", ")", ":", "# collect duplication metrics", "dup_bam", ",", "dup_metrics", "=", "self", ".", "_get_current_dup_met...
https://github.com/chapmanb/bcbb/blob/dbfb52711f0bfcc1d26c5a5b53c9ff4f50dc0027/nextgen/bcbio/broad/metrics.py#L442-L467
microsoft/unilm
65f15af2a307ebb64cfb25adf54375b002e6fe8d
infoxlm/fairseq/fairseq/models/fairseq_model.py
python
BaseFairseqModel.upgrade_state_dict_named
(self, state_dict, name)
Upgrade old state dicts to work with newer code. Args: state_dict (dict): state dictionary to upgrade, in place name (str): the state dict key corresponding to the current module
Upgrade old state dicts to work with newer code.
[ "Upgrade", "old", "state", "dicts", "to", "work", "with", "newer", "code", "." ]
def upgrade_state_dict_named(self, state_dict, name): """Upgrade old state dicts to work with newer code. Args: state_dict (dict): state dictionary to upgrade, in place name (str): the state dict key corresponding to the current module """ assert state_dict is not None def do_upgrade(m, prefix): if len(prefix) > 0: prefix += '.' for n, c in m.named_children(): name = prefix + n if hasattr(c, 'upgrade_state_dict_named'): c.upgrade_state_dict_named(state_dict, name) elif hasattr(c, 'upgrade_state_dict'): c.upgrade_state_dict(state_dict) do_upgrade(c, name) do_upgrade(self, name)
[ "def", "upgrade_state_dict_named", "(", "self", ",", "state_dict", ",", "name", ")", ":", "assert", "state_dict", "is", "not", "None", "def", "do_upgrade", "(", "m", ",", "prefix", ")", ":", "if", "len", "(", "prefix", ")", ">", "0", ":", "prefix", "+=...
https://github.com/microsoft/unilm/blob/65f15af2a307ebb64cfb25adf54375b002e6fe8d/infoxlm/fairseq/fairseq/models/fairseq_model.py#L77-L98
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_oa_openshift/library/oc_adm_router.py
python
Router.__init__
(self, router_config, verbose=False)
Constructor for OpenshiftOC a router consists of 3 or more parts - dc/router - svc/router - sa/router - secret/router-certs - clusterrolebinding/router-router-role
Constructor for OpenshiftOC
[ "Constructor", "for", "OpenshiftOC" ]
def __init__(self, router_config, verbose=False): ''' Constructor for OpenshiftOC a router consists of 3 or more parts - dc/router - svc/router - sa/router - secret/router-certs - clusterrolebinding/router-router-role ''' super(Router, self).__init__(router_config.namespace, router_config.kubeconfig, verbose) self.config = router_config self.verbose = verbose self.router_parts = [{'kind': 'dc', 'name': self.config.name}, {'kind': 'svc', 'name': self.config.name}, {'kind': 'sa', 'name': self.config.config_options['service_account']['value']}, {'kind': 'secret', 'name': self.config.name + '-certs'}, {'kind': 'clusterrolebinding', 'name': 'router-' + self.config.name + '-role'}, ] self.__prepared_router = None self.dconfig = None self.svc = None self._secret = None self._serviceaccount = None self._rolebinding = None
[ "def", "__init__", "(", "self", ",", "router_config", ",", "verbose", "=", "False", ")", ":", "super", "(", "Router", ",", "self", ")", ".", "__init__", "(", "router_config", ".", "namespace", ",", "router_config", ".", "kubeconfig", ",", "verbose", ")", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_adm_router.py#L2693-L2720
blurstudio/cross3d
277968d1227de740fc87ef61005c75034420eadf
cross3d/abstract/abstractcontainer.py
python
AbstractContainer.deselect
(self)
return self.setSelected(False)
Deselects the objects on this object group from the scene :return: bool
Deselects the objects on this object group from the scene :return: bool
[ "Deselects", "the", "objects", "on", "this", "object", "group", "from", "the", "scene", ":", "return", ":", "bool" ]
def deselect(self): """Deselects the objects on this object group from the scene :return: bool """ return self.setSelected(False)
[ "def", "deselect", "(", "self", ")", ":", "return", "self", ".", "setSelected", "(", "False", ")" ]
https://github.com/blurstudio/cross3d/blob/277968d1227de740fc87ef61005c75034420eadf/cross3d/abstract/abstractcontainer.py#L249-L255
InsaneLife/dssm
1d32e137654e03994f7ba6cfde52e1d47601027c
model/bert/tokenization.py
python
whitespace_tokenize
(text)
return tokens
Runs basic whitespace cleaning and splitting on a peice of text.
Runs basic whitespace cleaning and splitting on a peice of text.
[ "Runs", "basic", "whitespace", "cleaning", "and", "splitting", "on", "a", "peice", "of", "text", "." ]
def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a peice of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
[ "def", "whitespace_tokenize", "(", "text", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "not", "text", ":", "return", "[", "]", "tokens", "=", "text", ".", "split", "(", ")", "return", "tokens" ]
https://github.com/InsaneLife/dssm/blob/1d32e137654e03994f7ba6cfde52e1d47601027c/model/bert/tokenization.py#L96-L102
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/inject/thirdparty/bottle/bottle.py
python
BaseRequest.json
(self)
return None
If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion.
If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion.
[ "If", "the", "Content", "-", "Type", "header", "is", "application", "/", "json", "this", "property", "holds", "the", "parsed", "content", "of", "the", "request", "body", ".", "Only", "requests", "smaller", "than", ":", "attr", ":", "MEMFILE_MAX", "are", "p...
def json(self): ''' If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion. ''' if 'application/json' in self.environ.get('CONTENT_TYPE', '') \ and 0 < self.content_length < self.MEMFILE_MAX: return json_loads(self.body.read(self.MEMFILE_MAX)) return None
[ "def", "json", "(", "self", ")", ":", "if", "'application/json'", "in", "self", ".", "environ", ".", "get", "(", "'CONTENT_TYPE'", ",", "''", ")", "and", "0", "<", "self", ".", "content_length", "<", "self", ".", "MEMFILE_MAX", ":", "return", "json_loads...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/inject/thirdparty/bottle/bottle.py#L1017-L1025
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/pipes.py
python
Template.clone
(self)
return t
t.clone() returns a new pipeline template with identical initial state as the current one.
t.clone() returns a new pipeline template with identical initial state as the current one.
[ "t", ".", "clone", "()", "returns", "a", "new", "pipeline", "template", "with", "identical", "initial", "state", "as", "the", "current", "one", "." ]
def clone(self): """t.clone() returns a new pipeline template with identical initial state as the current one.""" t = Template() t.steps = self.steps[:] t.debugging = self.debugging return t
[ "def", "clone", "(", "self", ")", ":", "t", "=", "Template", "(", ")", "t", ".", "steps", "=", "self", ".", "steps", "[", ":", "]", "t", ".", "debugging", "=", "self", ".", "debugging", "return", "t" ]
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/pipes.py#L97-L103
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/mailcap.py
python
parsefield
(line, i, n)
return line[start:i].strip(), i
Separate one key-value pair in a mailcap entry.
Separate one key-value pair in a mailcap entry.
[ "Separate", "one", "key", "-", "value", "pair", "in", "a", "mailcap", "entry", "." ]
def parsefield(line, i, n): """Separate one key-value pair in a mailcap entry.""" start = i while i < n: c = line[i] if c == ';': break elif c == '\\': i = i+2 else: i = i+1 return line[start:i].strip(), i
[ "def", "parsefield", "(", "line", ",", "i", ",", "n", ")", ":", "start", "=", "i", "while", "i", "<", "n", ":", "c", "=", "line", "[", "i", "]", "if", "c", "==", "';'", ":", "break", "elif", "c", "==", "'\\\\'", ":", "i", "=", "i", "+", "...
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/mailcap.py#L122-L133
erikdubois/Aureola
005fb14b3cab0ba1929ebf9ac3ac68d2c6e1c0ef
shailen mc/dropbox.py
python
relpath
(path, start=curdir)
return join(*rel_list)
Return a relative version of a path
Return a relative version of a path
[ "Return", "a", "relative", "version", "of", "a", "path" ]
def relpath(path, start=curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") if type(start) is unicode: start_list = unicode_abspath(start).split(sep) else: start_list = abspath(start).split(sep) if type(path) is unicode: path_list = unicode_abspath(path).split(sep) else: path_list = abspath(path).split(sep) # Work out how much of the filepath is shared by start and path. i = len(commonprefix([start_list, path_list])) rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list)
[ "def", "relpath", "(", "path", ",", "start", "=", "curdir", ")", ":", "if", "not", "path", ":", "raise", "ValueError", "(", "\"no path specified\"", ")", "if", "type", "(", "start", ")", "is", "unicode", ":", "start_list", "=", "unicode_abspath", "(", "s...
https://github.com/erikdubois/Aureola/blob/005fb14b3cab0ba1929ebf9ac3ac68d2c6e1c0ef/shailen mc/dropbox.py#L97-L119
asciidoc-py/asciidoc-py
b40326325e5985c8b60366237eabe850b32d2176
asciidoc/a2x.py
python
A2X.xsl_stylesheet
(self, file_name=None)
return self.asciidoc_conf_file(os.path.join('docbook-xsl', file_name))
Return full path name of file in asciidoc docbook-xsl configuration directory. If an XSL file was specified with the --xsl-file option then it is returned.
Return full path name of file in asciidoc docbook-xsl configuration directory. If an XSL file was specified with the --xsl-file option then it is returned.
[ "Return", "full", "path", "name", "of", "file", "in", "asciidoc", "docbook", "-", "xsl", "configuration", "directory", ".", "If", "an", "XSL", "file", "was", "specified", "with", "the", "--", "xsl", "-", "file", "option", "then", "it", "is", "returned", ...
def xsl_stylesheet(self, file_name=None): ''' Return full path name of file in asciidoc docbook-xsl configuration directory. If an XSL file was specified with the --xsl-file option then it is returned. ''' if self.xsl_file is not None: return self.xsl_file if not file_name: file_name = self.format + '.xsl' return self.asciidoc_conf_file(os.path.join('docbook-xsl', file_name))
[ "def", "xsl_stylesheet", "(", "self", ",", "file_name", "=", "None", ")", ":", "if", "self", ".", "xsl_file", "is", "not", "None", ":", "return", "self", ".", "xsl_file", "if", "not", "file_name", ":", "file_name", "=", "self", ".", "format", "+", "'.x...
https://github.com/asciidoc-py/asciidoc-py/blob/b40326325e5985c8b60366237eabe850b32d2176/asciidoc/a2x.py#L589-L600
fossasia/pslab-python
bb53a334b729d0956ed9f4ce6899903f3e4868ef
pslab/bus/uart.py
python
UART.write_byte
(self, data: int)
Write a single byte to the UART bus. Parameters ---------- data : int Byte value to write to the UART bus.
Write a single byte to the UART bus.
[ "Write", "a", "single", "byte", "to", "the", "UART", "bus", "." ]
def write_byte(self, data: int): """Write a single byte to the UART bus. Parameters ---------- data : int Byte value to write to the UART bus. """ self._write_byte(data)
[ "def", "write_byte", "(", "self", ",", "data", ":", "int", ")", ":", "self", ".", "_write_byte", "(", "data", ")" ]
https://github.com/fossasia/pslab-python/blob/bb53a334b729d0956ed9f4ce6899903f3e4868ef/pslab/bus/uart.py#L252-L260
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/unsupervised/owcorrespondence.py
python
ScatterPlotItem.paint
(self, painter, option, widget=None)
[]
def paint(self, painter, option, widget=None): painter.setRenderHint(QPainter.SmoothPixmapTransform, True) painter.setRenderHint(QPainter.Antialiasing, True) super().paint(painter, option, widget)
[ "def", "paint", "(", "self", ",", "painter", ",", "option", ",", "widget", "=", "None", ")", ":", "painter", ".", "setRenderHint", "(", "QPainter", ".", "SmoothPixmapTransform", ",", "True", ")", "painter", ".", "setRenderHint", "(", "QPainter", ".", "Anti...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/unsupervised/owcorrespondence.py#L26-L29
HSLCY/ABSA-BERT-pair
7d238eb8c772946b9e572373c144b11151e4187f
evaluation.py
python
get_y_pred
(task_name, pred_data_dir)
return pred, score
Read file to obtain y_pred and scores.
Read file to obtain y_pred and scores.
[ "Read", "file", "to", "obtain", "y_pred", "and", "scores", "." ]
def get_y_pred(task_name, pred_data_dir): """ Read file to obtain y_pred and scores. """ pred=[] score=[] if task_name in ["sentihood_NLI_M", "sentihood_QA_M"]: with open(pred_data_dir, "r", encoding="utf-8") as f: s=f.readline().strip().split() while s: pred.append(int(s[0])) score.append([float(s[1]),float(s[2]),float(s[3])]) s = f.readline().strip().split() elif task_name in ["sentihood_NLI_B", "sentihood_QA_B"]: count = 0 tmp = [] with open(pred_data_dir, "r", encoding="utf-8") as f: s = f.readline().strip().split() while s: tmp.append([float(s[2])]) count += 1 if count % 3 == 0: tmp_sum = np.sum(tmp) t = [] for i in range(3): t.append(tmp[i] / tmp_sum) score.append(t) if t[0] >= t[1] and t[0] >= t[2]: pred.append(0) elif t[1] >= t[0] and t[1] >= t[2]: pred.append(1) else: pred.append(2) tmp = [] s = f.readline().strip().split() elif task_name == "sentihood_single": count = 0 with open(pred_data_dir + "loc1_general.txt", "r", encoding="utf-8") as f1_general, \ open(pred_data_dir + "loc1_price.txt", "r", encoding="utf-8") as f1_price, \ open(pred_data_dir + "loc1_safety.txt", "r", encoding="utf-8") as f1_safety, \ open(pred_data_dir + "loc1_transit.txt", "r", encoding="utf-8") as f1_transit: s = f1_general.readline().strip().split() while s: count += 1 pred.append(int(s[0])) score.append([float(s[1]), float(s[2]), float(s[3])]) if count % 4 == 0: s = f1_general.readline().strip().split() if count % 4 == 1: s = f1_price.readline().strip().split() if count % 4 == 2: s = f1_safety.readline().strip().split() if count % 4 == 3: s = f1_transit.readline().strip().split() with open(pred_data_dir + "loc2_general.txt", "r", encoding="utf-8") as f2_general, \ open(pred_data_dir + "loc2_price.txt", "r", encoding="utf-8") as f2_price, \ open(pred_data_dir + "loc2_safety.txt", "r", encoding="utf-8") as f2_safety, \ open(pred_data_dir + "loc2_transit.txt", "r", encoding="utf-8") as f2_transit: s = f2_general.readline().strip().split() while s: count += 1 pred.append(int(s[0])) score.append([float(s[1]), float(s[2]), float(s[3])]) if count % 4 == 0: s = f2_general.readline().strip().split() if count % 4 == 1: s = f2_price.readline().strip().split() if count % 4 == 2: s = f2_safety.readline().strip().split() if count % 4 == 3: s = f2_transit.readline().strip().split() elif task_name in ["semeval_NLI_M", "semeval_QA_M"]: with open(pred_data_dir,"r",encoding="utf-8") as f: s=f.readline().strip().split() while s: pred.append(int(s[0])) score.append([float(s[1]), float(s[2]), float(s[3]), float(s[4]), float(s[5])]) s = f.readline().strip().split() elif task_name in ["semeval_NLI_B", "semeval_QA_B"]: count = 0 tmp = [] with open(pred_data_dir, "r", encoding="utf-8") as f: s = f.readline().strip().split() while s: tmp.append([float(s[2])]) count += 1 if count % 5 == 0: tmp_sum = np.sum(tmp) t = [] for i in range(5): t.append(tmp[i] / tmp_sum) score.append(t) if t[0] >= t[1] and t[0] >= t[2] and t[0]>=t[3] and t[0]>=t[4]: pred.append(0) elif t[1] >= t[0] and t[1] >= t[2] and t[1]>=t[3] and t[1]>=t[4]: pred.append(1) elif t[2] >= t[0] and t[2] >= t[1] and t[2]>=t[3] and t[2]>=t[4]: pred.append(2) elif t[3] >= t[0] and t[3] >= t[1] and t[3]>=t[2] and t[3]>=t[4]: pred.append(3) else: pred.append(4) tmp = [] s = f.readline().strip().split() else: count = 0 with open(pred_data_dir+"price.txt","r",encoding="utf-8") as f_price, \ open(pred_data_dir+"anecdotes.txt", "r", encoding="utf-8") as f_anecdotes, \ open(pred_data_dir+"food.txt", "r", encoding="utf-8") as f_food, \ open(pred_data_dir+"ambience.txt", "r", encoding="utf-8") as f_ambience, \ open(pred_data_dir+"service.txt", "r", encoding="utf-8") as f_service: s = f_price.readline().strip().split() while s: count += 1 pred.append(int(s[0])) score.append([float(s[1]), float(s[2]), float(s[3]), float(s[4]), float(s[5])]) if count % 5 == 0: s = f_price.readline().strip().split() if count % 5 == 1: s = f_anecdotes.readline().strip().split() if count % 5 == 2: s = f_food.readline().strip().split() if count % 5 == 3: s = f_ambience.readline().strip().split() if count % 5 == 4: s = f_service.readline().strip().split() return pred, score
[ "def", "get_y_pred", "(", "task_name", ",", "pred_data_dir", ")", ":", "pred", "=", "[", "]", "score", "=", "[", "]", "if", "task_name", "in", "[", "\"sentihood_NLI_M\"", ",", "\"sentihood_QA_M\"", "]", ":", "with", "open", "(", "pred_data_dir", ",", "\"r\...
https://github.com/HSLCY/ABSA-BERT-pair/blob/7d238eb8c772946b9e572373c144b11151e4187f/evaluation.py#L54-L182
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/requests/cookies.py
python
RequestsCookieJar._find_no_duplicates
(self, name, domain=None, path=None)
Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value
Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests.
[ "Both", "__get_item__", "and", "get", "call", "this", "function", ":", "it", "s", "never", "used", "elsewhere", "in", "Requests", "." ]
def _find_no_duplicates(self, name, domain=None, path=None): """Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value """ toReturn = None for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: if toReturn is not None: # if there are multiple cookies that meet passed in criteria raise CookieConflictError('There are multiple cookies with name, %r' % (name)) toReturn = cookie.value # we will eventually return this as long as no cookie conflict if toReturn: return toReturn raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
[ "def", "_find_no_duplicates", "(", "self", ",", "name", ",", "domain", "=", "None", ",", "path", "=", "None", ")", ":", "toReturn", "=", "None", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "name", "==", "name", ":", "...
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/requests/cookies.py#L376-L399
zopefoundation/Zope
ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb
src/OFS/PropertySheets.py
python
View.tpURL
(self)
return self.getId()
[]
def tpURL(self): return self.getId()
[ "def", "tpURL", "(", "self", ")", ":", "return", "self", ".", "getId", "(", ")" ]
https://github.com/zopefoundation/Zope/blob/ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb/src/OFS/PropertySheets.py#L58-L59
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/sqlalchemy/orm/session.py
python
Session.object_session
(cls, instance)
return object_session(instance)
Return the ``Session`` to which an object belongs.
Return the ``Session`` to which an object belongs.
[ "Return", "the", "Session", "to", "which", "an", "object", "belongs", "." ]
def object_session(cls, instance): """Return the ``Session`` to which an object belongs.""" return object_session(instance)
[ "def", "object_session", "(", "cls", ",", "instance", ")", ":", "return", "object_session", "(", "instance", ")" ]
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/sqlalchemy/orm/session.py#L1261-L1264
facebookresearch/pytorch3d
fddd6a700fa9685c1ce2d4b266c111d7db424ecc
pytorch3d/structures/meshes.py
python
Meshes.faces_list
(self)
return self._faces_list
Get the list representation of the faces. Returns: list of tensors of faces of shape (F_n, 3).
Get the list representation of the faces.
[ "Get", "the", "list", "representation", "of", "the", "faces", "." ]
def faces_list(self): """ Get the list representation of the faces. Returns: list of tensors of faces of shape (F_n, 3). """ if self._faces_list is None: assert ( self._faces_padded is not None ), "faces_padded is required to compute faces_list." self._faces_list = struct_utils.padded_to_list( self._faces_padded, self.num_faces_per_mesh().tolist() ) return self._faces_list
[ "def", "faces_list", "(", "self", ")", ":", "if", "self", ".", "_faces_list", "is", "None", ":", "assert", "(", "self", ".", "_faces_padded", "is", "not", "None", ")", ",", "\"faces_padded is required to compute faces_list.\"", "self", ".", "_faces_list", "=", ...
https://github.com/facebookresearch/pytorch3d/blob/fddd6a700fa9685c1ce2d4b266c111d7db424ecc/pytorch3d/structures/meshes.py#L538-L552
tortoise/tortoise-orm
5bf910a3dcd1e729106b7f0dee16aae362d35f46
tortoise/queryset.py
python
QuerySet.select_related
(self, *fields: str)
return queryset
Return a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection.
Return a new QuerySet instance that will select related objects.
[ "Return", "a", "new", "QuerySet", "instance", "that", "will", "select", "related", "objects", "." ]
def select_related(self, *fields: str) -> "QuerySet[MODEL]": """ Return a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection. """ queryset = self._clone() for field in fields: queryset._select_related.add(field) return queryset
[ "def", "select_related", "(", "self", ",", "*", "fields", ":", "str", ")", "->", "\"QuerySet[MODEL]\"", ":", "queryset", "=", "self", ".", "_clone", "(", ")", "for", "field", "in", "fields", ":", "queryset", ".", "_select_related", ".", "add", "(", "fiel...
https://github.com/tortoise/tortoise-orm/blob/5bf910a3dcd1e729106b7f0dee16aae362d35f46/tortoise/queryset.py#L800-L811
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
contrib/performance/benchmarks/unbounded_recurrence_autoaccept.py
python
measure
(host, port, dtrace, attendeeCount, samples)
return _measure( calendar, organizerSequence, events, host, port, dtrace, samples)
[]
def measure(host, port, dtrace, attendeeCount, samples): calendar = "unbounded-recurrence-autoaccept" organizerSequence = 1 # An infinite stream of recurring VEVENTS to PUT to the server. events = ((i, makeEvent(i, organizerSequence, attendeeCount)) for i in count(2)) return _measure( calendar, organizerSequence, events, host, port, dtrace, samples)
[ "def", "measure", "(", "host", ",", "port", ",", "dtrace", ",", "attendeeCount", ",", "samples", ")", ":", "calendar", "=", "\"unbounded-recurrence-autoaccept\"", "organizerSequence", "=", "1", "# An infinite stream of recurring VEVENTS to PUT to the server.", "events", "...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/contrib/performance/benchmarks/unbounded_recurrence_autoaccept.py#L45-L54
nilearn/nilearn
9edba4471747efacf21260bf470a346307f52706
nilearn/plotting/img_plotting.py
python
_MNI152Template.__str__
(self)
return "<MNI152Template>"
[]
def __str__(self): return "<MNI152Template>"
[ "def", "__str__", "(", "self", ")", ":", "return", "\"<MNI152Template>\"" ]
https://github.com/nilearn/nilearn/blob/9edba4471747efacf21260bf470a346307f52706/nilearn/plotting/img_plotting.py#L384-L385
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/pythonfinder/_vendor/pep514tools/_registry.py
python
get_value_from_tuple
(value, vtype)
return None
[]
def get_value_from_tuple(value, vtype): if vtype == winreg.REG_SZ: if '\0' in value: return value[:value.index('\0')] return value return None
[ "def", "get_value_from_tuple", "(", "value", ",", "vtype", ")", ":", "if", "vtype", "==", "winreg", ".", "REG_SZ", ":", "if", "'\\0'", "in", "value", ":", "return", "value", "[", ":", "value", ".", "index", "(", "'\\0'", ")", "]", "return", "value", ...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/pythonfinder/_vendor/pep514tools/_registry.py#L27-L32
karmab/kcli
fff2a2632841f54d9346b437821585df0ec659d7
kvirt/providers/sampleprovider.py
python
Kbase.delete
(self, name, snapshots=False)
return {'result': 'success'}
:param name: :param snapshots: :return:
[]
def delete(self, name, snapshots=False): """ :param name: :param snapshots: :return: """ print("not implemented") return {'result': 'success'}
[ "def", "delete", "(", "self", ",", "name", ",", "snapshots", "=", "False", ")", ":", "print", "(", "\"not implemented\"", ")", "return", "{", "'result'", ":", "'success'", "}" ]
https://github.com/karmab/kcli/blob/fff2a2632841f54d9346b437821585df0ec659d7/kvirt/providers/sampleprovider.py#L262-L270
mrJean1/PyGeodesy
7da5ca71aa3edb7bc49e219e0b8190686e1a7965
pygeodesy/lcc.py
python
Conic.__init__
(self, latlon0, par1, par2=None, E0=0, N0=0, k0=1, opt3=0, name=NN, auth=NN)
New Lambert conformal conic projection. @arg latlon0: Origin with (ellipsoidal) datum (C{LatLon}). @arg par1: First standard parallel (C{degrees90}). @kwarg par2: Optional, second standard parallel (C{degrees90}). @kwarg E0: Optional, false easting (C{meter}). @kwarg N0: Optional, false northing (C{meter}). @kwarg k0: Optional scale factor (C{scalar}). @kwarg opt3: Optional meridian (C{degrees180}). @kwarg name: Optional name of the conic (C{str}). @kwarg auth: Optional authentication authority (C{str}). @return: A Lambert projection (L{Conic}). @raise TypeError: Non-ellipsoidal B{C{latlon0}}. @raise ValueError: Invalid B{C{par1}}, B{C{par2}}, B{C{E0}}, B{C{N0}}, B{C{k0}} or B{C{opt3}}. @example: >>> from pygeodesy import Conic, Datums, ellipsoidalNvector >>> ll0 = ellipsoidalNvector.LatLon(23, -96, datum=Datums.NAD27) >>> Snyder = Conic(ll0, 33, 45, E0=0, N0=0, name='Snyder')
New Lambert conformal conic projection.
[ "New", "Lambert", "conformal", "conic", "projection", "." ]
def __init__(self, latlon0, par1, par2=None, E0=0, N0=0, k0=1, opt3=0, name=NN, auth=NN): '''New Lambert conformal conic projection. @arg latlon0: Origin with (ellipsoidal) datum (C{LatLon}). @arg par1: First standard parallel (C{degrees90}). @kwarg par2: Optional, second standard parallel (C{degrees90}). @kwarg E0: Optional, false easting (C{meter}). @kwarg N0: Optional, false northing (C{meter}). @kwarg k0: Optional scale factor (C{scalar}). @kwarg opt3: Optional meridian (C{degrees180}). @kwarg name: Optional name of the conic (C{str}). @kwarg auth: Optional authentication authority (C{str}). @return: A Lambert projection (L{Conic}). @raise TypeError: Non-ellipsoidal B{C{latlon0}}. @raise ValueError: Invalid B{C{par1}}, B{C{par2}}, B{C{E0}}, B{C{N0}}, B{C{k0}} or B{C{opt3}}. @example: >>> from pygeodesy import Conic, Datums, ellipsoidalNvector >>> ll0 = ellipsoidalNvector.LatLon(23, -96, datum=Datums.NAD27) >>> Snyder = Conic(ll0, 33, 45, E0=0, N0=0, name='Snyder') ''' if latlon0 is not None: _xinstanceof(_LLEB, latlon0=latlon0) self._phi0, self._lam0 = latlon0.philam self._par1 = Phi_(par1=par1) self._par2 = self._par1 if par2 is None else Phi_(par2=par2) if k0 != 1: self._k0 = Scalar_(k0=k0) if E0: self._E0 = Northing(E0=E0, falsed=True) if N0: self._N0 = Easting(N0=N0, falsed=True) if opt3: self._opt3 = Lam_(opt3=opt3) self.toDatum(latlon0.datum)._dup2(self) self._register(Conics, name) elif name: self.name = name if auth: self._auth = str(auth)
[ "def", "__init__", "(", "self", ",", "latlon0", ",", "par1", ",", "par2", "=", "None", ",", "E0", "=", "0", ",", "N0", "=", "0", ",", "k0", "=", "1", ",", "opt3", "=", "0", ",", "name", "=", "NN", ",", "auth", "=", "NN", ")", ":", "if", "...
https://github.com/mrJean1/PyGeodesy/blob/7da5ca71aa3edb7bc49e219e0b8190686e1a7965/pygeodesy/lcc.py#L82-L131
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/asynchat.py
python
async_chat._collect_incoming_data
(self, data)
[]
def _collect_incoming_data(self, data): self.incoming.append(data)
[ "def", "_collect_incoming_data", "(", "self", ",", "data", ")", ":", "self", ".", "incoming", ".", "append", "(", "data", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/asynchat.py#L92-L93