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
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/ext/admin/__init__.py
python
XMPPPageHandler.get
(self)
Shows template displaying the XMPP.
Shows template displaying the XMPP.
[ "Shows", "template", "displaying", "the", "XMPP", "." ]
def get(self): """Shows template displaying the XMPP.""" xmpp_configured = True values = { 'xmpp_configured': xmpp_configured, 'request': self.request } self.generate('xmpp.html', values)
[ "def", "get", "(", "self", ")", ":", "xmpp_configured", "=", "True", "values", "=", "{", "'xmpp_configured'", ":", "xmpp_configured", ",", "'request'", ":", "self", ".", "request", "}", "self", ".", "generate", "(", "'xmpp.html'", ",", "values", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/ext/admin/__init__.py#L413-L421
open-mmlab/OpenPCDet
0f4d3f1f5c1fbe551c35917220e75eb90e28035f
pcdet/datasets/kitti/kitti_object_eval_python/eval.py
python
eval_class
(gt_annos, dt_annos, current_classes, difficultys, metric, min_overlaps, compute_aos=False, num_parts=100)
return ret_dict
Kitti eval. support 2d/bev/3d/aos eval. support 0.5:0.05:0.95 coco AP. Args: gt_annos: dict, must from get_label_annos() in kitti_common.py dt_annos: dict, must from get_label_annos() in kitti_common.py current_classes: list of int, 0: car, 1: pedestrian, 2: cyclist difficultys: list of int. eval difficulty, 0: easy, 1: normal, 2: hard metric: eval type. 0: bbox, 1: bev, 2: 3d min_overlaps: float, min overlap. format: [num_overlap, metric, class]. num_parts: int. a parameter for fast calculate algorithm Returns: dict of recall, precision and aos
Kitti eval. support 2d/bev/3d/aos eval. support 0.5:0.05:0.95 coco AP. Args: gt_annos: dict, must from get_label_annos() in kitti_common.py dt_annos: dict, must from get_label_annos() in kitti_common.py current_classes: list of int, 0: car, 1: pedestrian, 2: cyclist difficultys: list of int. eval difficulty, 0: easy, 1: normal, 2: hard metric: eval type. 0: bbox, 1: bev, 2: 3d min_overlaps: float, min overlap. format: [num_overlap, metric, class]. num_parts: int. a parameter for fast calculate algorithm
[ "Kitti", "eval", ".", "support", "2d", "/", "bev", "/", "3d", "/", "aos", "eval", ".", "support", "0", ".", "5", ":", "0", ".", "05", ":", "0", ".", "95", "coco", "AP", ".", "Args", ":", "gt_annos", ":", "dict", "must", "from", "get_label_annos",...
def eval_class(gt_annos, dt_annos, current_classes, difficultys, metric, min_overlaps, compute_aos=False, num_parts=100): """Kitti eval. support 2d/bev/3d/aos eval. support 0.5:0.05:0.95 coco AP. Args: gt_annos: dict, must from get_label_annos() in kitti_common.py dt_annos: dict, must from get_label_annos() in kitti_common.py current_classes: list of int, 0: car, 1: pedestrian, 2: cyclist difficultys: list of int. eval difficulty, 0: easy, 1: normal, 2: hard metric: eval type. 0: bbox, 1: bev, 2: 3d min_overlaps: float, min overlap. format: [num_overlap, metric, class]. num_parts: int. a parameter for fast calculate algorithm Returns: dict of recall, precision and aos """ assert len(gt_annos) == len(dt_annos) num_examples = len(gt_annos) split_parts = get_split_parts(num_examples, num_parts) rets = calculate_iou_partly(dt_annos, gt_annos, metric, num_parts) overlaps, parted_overlaps, total_dt_num, total_gt_num = rets N_SAMPLE_PTS = 41 num_minoverlap = len(min_overlaps) num_class = len(current_classes) num_difficulty = len(difficultys) precision = np.zeros( [num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS]) recall = np.zeros( [num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS]) aos = np.zeros([num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS]) for m, current_class in enumerate(current_classes): for l, difficulty in enumerate(difficultys): rets = _prepare_data(gt_annos, dt_annos, current_class, difficulty) (gt_datas_list, dt_datas_list, ignored_gts, ignored_dets, dontcares, total_dc_num, total_num_valid_gt) = rets for k, min_overlap in enumerate(min_overlaps[:, metric, m]): thresholdss = [] for i in range(len(gt_annos)): rets = compute_statistics_jit( overlaps[i], gt_datas_list[i], dt_datas_list[i], ignored_gts[i], ignored_dets[i], dontcares[i], metric, min_overlap=min_overlap, thresh=0.0, compute_fp=False) tp, fp, fn, similarity, thresholds = rets thresholdss += thresholds.tolist() thresholdss = np.array(thresholdss) thresholds = get_thresholds(thresholdss, total_num_valid_gt) thresholds = np.array(thresholds) pr = np.zeros([len(thresholds), 4]) idx = 0 for j, num_part in enumerate(split_parts): gt_datas_part = np.concatenate( gt_datas_list[idx:idx + num_part], 0) dt_datas_part = np.concatenate( dt_datas_list[idx:idx + num_part], 0) dc_datas_part = np.concatenate( dontcares[idx:idx + num_part], 0) ignored_dets_part = np.concatenate( ignored_dets[idx:idx + num_part], 0) ignored_gts_part = np.concatenate( ignored_gts[idx:idx + num_part], 0) fused_compute_statistics( parted_overlaps[j], pr, total_gt_num[idx:idx + num_part], total_dt_num[idx:idx + num_part], total_dc_num[idx:idx + num_part], gt_datas_part, dt_datas_part, dc_datas_part, ignored_gts_part, ignored_dets_part, metric, min_overlap=min_overlap, thresholds=thresholds, compute_aos=compute_aos) idx += num_part for i in range(len(thresholds)): recall[m, l, k, i] = pr[i, 0] / (pr[i, 0] + pr[i, 2]) precision[m, l, k, i] = pr[i, 0] / (pr[i, 0] + pr[i, 1]) if compute_aos: aos[m, l, k, i] = pr[i, 3] / (pr[i, 0] + pr[i, 1]) for i in range(len(thresholds)): precision[m, l, k, i] = np.max( precision[m, l, k, i:], axis=-1) recall[m, l, k, i] = np.max(recall[m, l, k, i:], axis=-1) if compute_aos: aos[m, l, k, i] = np.max(aos[m, l, k, i:], axis=-1) ret_dict = { "recall": recall, "precision": precision, "orientation": aos, } return ret_dict
[ "def", "eval_class", "(", "gt_annos", ",", "dt_annos", ",", "current_classes", ",", "difficultys", ",", "metric", ",", "min_overlaps", ",", "compute_aos", "=", "False", ",", "num_parts", "=", "100", ")", ":", "assert", "len", "(", "gt_annos", ")", "==", "l...
https://github.com/open-mmlab/OpenPCDet/blob/0f4d3f1f5c1fbe551c35917220e75eb90e28035f/pcdet/datasets/kitti/kitti_object_eval_python/eval.py#L448-L553
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
Bio/AlignIO/Interfaces.py
python
AlignmentIterator.__iter__
(self)
return iter(self.__next__, None)
Iterate over the entries as MultipleSeqAlignment objects. Example usage for (concatenated) PHYLIP files:: with open("many.phy","r") as myFile: for alignment in PhylipIterator(myFile): print("New alignment:") for record in alignment: print(record.id) print(record.seq)
Iterate over the entries as MultipleSeqAlignment objects.
[ "Iterate", "over", "the", "entries", "as", "MultipleSeqAlignment", "objects", "." ]
def __iter__(self): """Iterate over the entries as MultipleSeqAlignment objects. Example usage for (concatenated) PHYLIP files:: with open("many.phy","r") as myFile: for alignment in PhylipIterator(myFile): print("New alignment:") for record in alignment: print(record.id) print(record.seq) """ return iter(self.__next__, None)
[ "def", "__iter__", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "__next__", ",", "None", ")" ]
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/AlignIO/Interfaces.py#L57-L70
llSourcell/AI_Artist
3038c06c2e389b9c919c881c9a169efe2fd7810e
lib/python2.7/site-packages/wheel/signatures/djbec.py
python
scalarmult
(pt, e)
return pt_unxform(xpt_mult(pt_xform(pt), e))
[]
def scalarmult(pt, e): return pt_unxform(xpt_mult(pt_xform(pt), e))
[ "def", "scalarmult", "(", "pt", ",", "e", ")", ":", "return", "pt_unxform", "(", "xpt_mult", "(", "pt_xform", "(", "pt", ")", ",", "e", ")", ")" ]
https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/wheel/signatures/djbec.py#L129-L130
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/keyframeeditor.py
python
GeometryEditor.paste_kf_value
(self, value_data)
[]
def paste_kf_value(self, value_data): #frame, rect, opacity = value_data frame, rect, opacity, kf_type = value_data self.clip_editor.set_active_kf_value(opacity) self.geom_kf_edit.set_keyframe_to_edit_shape(self.clip_editor.active_kf_index, rect) self.update_property_value() self.update_editor_view()
[ "def", "paste_kf_value", "(", "self", ",", "value_data", ")", ":", "#frame, rect, opacity = value_data", "frame", ",", "rect", ",", "opacity", ",", "kf_type", "=", "value_data", "self", ".", "clip_editor", ".", "set_active_kf_value", "(", "opacity", ")", "self", ...
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/keyframeeditor.py#L1438-L1444
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/base64.py
python
b32decode
(s, casefold=False, map01=None)
return EMPTYSTRING.join(parts)
Decode a Base32 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O (oh), and for optional mapping of the digit 1 (one) to either the letter I (eye) or letter L (el). The optional argument map01 when not None, specifies which letter the digit 1 should be mapped to (when map01 is not None, the digit 0 is always mapped to the letter O). For security purposes the default is None, so that 0 and 1 are not allowed in the input. The decoded string is returned. A TypeError is raised if s were incorrectly padded or if there are non-alphabet characters present in the string.
Decode a Base32 encoded string.
[ "Decode", "a", "Base32", "encoded", "string", "." ]
def b32decode(s, casefold=False, map01=None): """Decode a Base32 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O (oh), and for optional mapping of the digit 1 (one) to either the letter I (eye) or letter L (el). The optional argument map01 when not None, specifies which letter the digit 1 should be mapped to (when map01 is not None, the digit 0 is always mapped to the letter O). For security purposes the default is None, so that 0 and 1 are not allowed in the input. The decoded string is returned. A TypeError is raised if s were incorrectly padded or if there are non-alphabet characters present in the string. """ quanta, leftover = divmod(len(s), 8) if leftover: raise TypeError('Incorrect padding') # Handle section 2.4 zero and one mapping. The flag map01 will be either # False, or the character to map the digit 1 (one) to. It should be # either L (el) or I (eye). if map01: s = s.translate(string.maketrans(b'01', b'O' + map01)) if casefold: s = s.upper() # Strip off pad characters from the right. We need to count the pad # characters because this will tell us how many null bytes to remove from # the end of the decoded string. padchars = 0 mo = re.search('(?P<pad>[=]*)$', s) if mo: padchars = len(mo.group('pad')) if padchars > 0: s = s[:-padchars] # Now decode the full quanta parts = [] acc = 0 shift = 35 for c in s: val = _b32rev.get(c) if val is None: raise TypeError('Non-base32 digit found') acc += _b32rev[c] << shift shift -= 5 if shift < 0: parts.append(binascii.unhexlify('%010x' % acc)) acc = 0 shift = 35 # Process the last, partial quanta last = binascii.unhexlify('%010x' % acc) if padchars == 0: last = '' # No characters elif padchars == 1: last = last[:-1] elif padchars == 3: last = last[:-2] elif padchars == 4: last = last[:-3] elif padchars == 6: last = last[:-4] else: raise TypeError('Incorrect padding') parts.append(last) return EMPTYSTRING.join(parts)
[ "def", "b32decode", "(", "s", ",", "casefold", "=", "False", ",", "map01", "=", "None", ")", ":", "quanta", ",", "leftover", "=", "divmod", "(", "len", "(", "s", ")", ",", "8", ")", "if", "leftover", ":", "raise", "TypeError", "(", "'Incorrect paddin...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/base64.py#L184-L251
pyocd/pyOCD
7d164d99e816c4ef6c99f257014543188a0ca5a6
pyocd/probe/pydapaccess/dap_access_api.py
python
DAPAccessIntf.swj_sequence
(self, length, bits)
! @brief Send sequence to activate JTAG or SWD on the target. @param self @param length Number of bits to transfer on TCK/TMS. @param bits Integer with the bit values, sent LSB first.
!
[ "!" ]
def swj_sequence(self, length, bits): """! @brief Send sequence to activate JTAG or SWD on the target. @param self @param length Number of bits to transfer on TCK/TMS. @param bits Integer with the bit values, sent LSB first. """ raise NotImplementedError()
[ "def", "swj_sequence", "(", "self", ",", "length", ",", "bits", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/pyocd/pyOCD/blob/7d164d99e816c4ef6c99f257014543188a0ca5a6/pyocd/probe/pydapaccess/dap_access_api.py#L182-L189
pyapi-gitlab/pyapi-gitlab
f74b6fb5c13cecae9524997847e928905cc60acf
gitlab/base.py
python
Base.getall
(fn, page=None, *args, **kwargs)
Auto-iterate over the paginated results of various methods of the API. Pass the GitLabAPI method as the first argument, followed by the other parameters as normal. Include `page` to determine first page to poll. Remaining kwargs are passed on to the called method, including `per_page`. :param fn: Actual method to call :param page: Optional, page number to start at, defaults to 1 :param args: Positional arguments to actual method :param kwargs: Keyword arguments to actual method :return: Yields each item in the result until exhausted, and then implicit StopIteration; or no elements if error
Auto-iterate over the paginated results of various methods of the API. Pass the GitLabAPI method as the first argument, followed by the other parameters as normal. Include `page` to determine first page to poll. Remaining kwargs are passed on to the called method, including `per_page`.
[ "Auto", "-", "iterate", "over", "the", "paginated", "results", "of", "various", "methods", "of", "the", "API", ".", "Pass", "the", "GitLabAPI", "method", "as", "the", "first", "argument", "followed", "by", "the", "other", "parameters", "as", "normal", ".", ...
def getall(fn, page=None, *args, **kwargs): """ Auto-iterate over the paginated results of various methods of the API. Pass the GitLabAPI method as the first argument, followed by the other parameters as normal. Include `page` to determine first page to poll. Remaining kwargs are passed on to the called method, including `per_page`. :param fn: Actual method to call :param page: Optional, page number to start at, defaults to 1 :param args: Positional arguments to actual method :param kwargs: Keyword arguments to actual method :return: Yields each item in the result until exhausted, and then implicit StopIteration; or no elements if error """ if not page: page = 1 while True: results = fn(*args, page=page, **kwargs) if not results: break for x in results: yield x page += 1
[ "def", "getall", "(", "fn", ",", "page", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "page", ":", "page", "=", "1", "while", "True", ":", "results", "=", "fn", "(", "*", "args", ",", "page", "=", "page", ","...
https://github.com/pyapi-gitlab/pyapi-gitlab/blob/f74b6fb5c13cecae9524997847e928905cc60acf/gitlab/base.py#L148-L172
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txdav/common/datastore/file.py
python
CommonStoreTransaction.removeAPNSubscription
(self, token, key)
return NotImplementedError
[]
def removeAPNSubscription(self, token, key): return NotImplementedError
[ "def", "removeAPNSubscription", "(", "self", ",", "token", ",", "key", ")", ":", "return", "NotImplementedError" ]
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/common/datastore/file.py#L367-L368
ronf/asyncssh
ee1714c598d8c2ea6f5484e465443f38b68714aa
asyncssh/eddsa.py
python
_EdKey.make_private
(cls, key_params: object)
Construct an EdDSA private key
Construct an EdDSA private key
[ "Construct", "an", "EdDSA", "private", "key" ]
def make_private(cls, key_params: object) -> SSHKey: """Construct an EdDSA private key""" try: private_value, = cast(_PrivateKeyArgs, key_params) return cls(EdDSAPrivateKey.construct(cls.algorithm[4:], private_value)) except (TypeError, ValueError): raise KeyImportError('Invalid EdDSA private key') from None
[ "def", "make_private", "(", "cls", ",", "key_params", ":", "object", ")", "->", "SSHKey", ":", "try", ":", "private_value", ",", "=", "cast", "(", "_PrivateKeyArgs", ",", "key_params", ")", "return", "cls", "(", "EdDSAPrivateKey", ".", "construct", "(", "c...
https://github.com/ronf/asyncssh/blob/ee1714c598d8c2ea6f5484e465443f38b68714aa/asyncssh/eddsa.py#L67-L76
menpo/menpofit
5f2f45bab26df206d43292fd32d19cd8f62f0443
menpofit/dlib/fitter.py
python
DlibWrapper.fit_from_bb
(self, image, bounding_box, gt_shape=None)
return Result( final_shape=fit_result.final_shape, image=image, initial_shape=None, gt_shape=gt_shape, )
r""" Fits the model to an image given an initial bounding box. Parameters ---------- image : `menpo.image.Image` or subclass The image to be fitted. bounding_box : `menpo.shape.PointDirectedGraph` The initial bounding box. gt_shape : `menpo.shape.PointCloud` The ground truth shape associated to the image. Returns ------- fitting_result : :map:`Result` The result of the fitting procedure.
r""" Fits the model to an image given an initial bounding box.
[ "r", "Fits", "the", "model", "to", "an", "image", "given", "an", "initial", "bounding", "box", "." ]
def fit_from_bb(self, image, bounding_box, gt_shape=None): r""" Fits the model to an image given an initial bounding box. Parameters ---------- image : `menpo.image.Image` or subclass The image to be fitted. bounding_box : `menpo.shape.PointDirectedGraph` The initial bounding box. gt_shape : `menpo.shape.PointCloud` The ground truth shape associated to the image. Returns ------- fitting_result : :map:`Result` The result of the fitting procedure. """ # We get back a NonParametricIterativeResult with one iteration, # which is pointless. Simply convert it to a Result instance without # passing in an initial shape. fit_result = self.algorithm.run(image, bounding_box, gt_shape=gt_shape) return Result( final_shape=fit_result.final_shape, image=image, initial_shape=None, gt_shape=gt_shape, )
[ "def", "fit_from_bb", "(", "self", ",", "image", ",", "bounding_box", ",", "gt_shape", "=", "None", ")", ":", "# We get back a NonParametricIterativeResult with one iteration,", "# which is pointless. Simply convert it to a Result instance without", "# passing in an initial shape.", ...
https://github.com/menpo/menpofit/blob/5f2f45bab26df206d43292fd32d19cd8f62f0443/menpofit/dlib/fitter.py#L582-L609
mrlesmithjr/Ansible
d44f0dc0d942bdf3bf7334b307e6048f0ee16e36
roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/retry.py
python
Retry.from_int
(cls, retries, redirect=True, default=None)
return new_retries
Backwards-compatibility for the old retries format.
Backwards-compatibility for the old retries format.
[ "Backwards", "-", "compatibility", "for", "the", "old", "retries", "format", "." ]
def from_int(cls, retries, redirect=True, default=None): """ Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redirect) and None new_retries = cls(retries, redirect=redirect) log.debug("Converted retries value: %r -> %r", retries, new_retries) return new_retries
[ "def", "from_int", "(", "cls", ",", "retries", ",", "redirect", "=", "True", ",", "default", "=", "None", ")", ":", "if", "retries", "is", "None", ":", "retries", "=", "default", "if", "default", "is", "not", "None", "else", "cls", ".", "DEFAULT", "i...
https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/retry.py#L160-L171
rytilahti/python-miio
b6e53dd16fac77915426e7592e2528b78ef65190
miio/airqualitymonitor_miot.py
python
AirQualityMonitorCGDN1.set_display_temperature_unit
(self, unit: DisplayTemperatureUnitCGDN1)
return self.set_property("temperature_unit", unit.value)
Set display temperature unit.
Set display temperature unit.
[ "Set", "display", "temperature", "unit", "." ]
def set_display_temperature_unit(self, unit: DisplayTemperatureUnitCGDN1): """Set display temperature unit.""" return self.set_property("temperature_unit", unit.value)
[ "def", "set_display_temperature_unit", "(", "self", ",", "unit", ":", "DisplayTemperatureUnitCGDN1", ")", ":", "return", "self", ".", "set_property", "(", "\"temperature_unit\"", ",", "unit", ".", "value", ")" ]
https://github.com/rytilahti/python-miio/blob/b6e53dd16fac77915426e7592e2528b78ef65190/miio/airqualitymonitor_miot.py#L245-L247
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/gui/api_call_router.py
python
ApiCallRouterStub.GetVfsTimelineAsCsv
(self, args, context=None)
Get event timeline of VFS evetns for a given VFS path in CSV format.
Get event timeline of VFS evetns for a given VFS path in CSV format.
[ "Get", "event", "timeline", "of", "VFS", "evetns", "for", "a", "given", "VFS", "path", "in", "CSV", "format", "." ]
def GetVfsTimelineAsCsv(self, args, context=None): """Get event timeline of VFS evetns for a given VFS path in CSV format.""" raise NotImplementedError()
[ "def", "GetVfsTimelineAsCsv", "(", "self", ",", "args", ",", "context", "=", "None", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/gui/api_call_router.py#L525-L528
hgrecco/pint
befdffb9d767fb354fc756660a33268c0f8d48e1
pint/quantity.py
python
Quantity.check
(self, dimension: UnitLike)
return self.dimensionality == self._REGISTRY.get_dimensionality(dimension)
Return true if the quantity's dimension matches passed dimension.
Return true if the quantity's dimension matches passed dimension.
[ "Return", "true", "if", "the", "quantity", "s", "dimension", "matches", "passed", "dimension", "." ]
def check(self, dimension: UnitLike) -> bool: """Return true if the quantity's dimension matches passed dimension.""" return self.dimensionality == self._REGISTRY.get_dimensionality(dimension)
[ "def", "check", "(", "self", ",", "dimension", ":", "UnitLike", ")", "->", "bool", ":", "return", "self", ".", "dimensionality", "==", "self", ".", "_REGISTRY", ".", "get_dimensionality", "(", "dimension", ")" ]
https://github.com/hgrecco/pint/blob/befdffb9d767fb354fc756660a33268c0f8d48e1/pint/quantity.py#L557-L559
postgres/pgadmin4
374c5e952fa594d749fadf1f88076c1cba8c5f64
web/pgadmin/browser/server_groups/servers/databases/languages/__init__.py
python
LanguageView.msql
(self, gid, sid, did, lid=None)
This function is used to return modified SQL for the selected language node. Args: gid: Server Group ID sid: Server ID did: Database ID lid: Language ID
This function is used to return modified SQL for the selected language node.
[ "This", "function", "is", "used", "to", "return", "modified", "SQL", "for", "the", "selected", "language", "node", "." ]
def msql(self, gid, sid, did, lid=None): """ This function is used to return modified SQL for the selected language node. Args: gid: Server Group ID sid: Server ID did: Database ID lid: Language ID """ data = {} for k, v in request.args.items(): try: # comments should be taken as is because if user enters a # json comment it is parsed by loads which should not happen if k in ('description',): data[k] = v else: data[k] = json.loads(v, encoding='utf-8') except ValueError: data[k] = v try: sql, name = self.get_sql(data, lid) # Most probably this is due to error if not isinstance(sql, str): return sql if sql == '': sql = "--modified SQL" return make_json_response( data=sql, status=200 ) except Exception as e: return internal_server_error(errormsg=str(e))
[ "def", "msql", "(", "self", ",", "gid", ",", "sid", ",", "did", ",", "lid", "=", "None", ")", ":", "data", "=", "{", "}", "for", "k", ",", "v", "in", "request", ".", "args", ".", "items", "(", ")", ":", "try", ":", "# comments should be taken as ...
https://github.com/postgres/pgadmin4/blob/374c5e952fa594d749fadf1f88076c1cba8c5f64/web/pgadmin/browser/server_groups/servers/databases/languages/__init__.py#L565-L600
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/compilers/mixins/clike.py
python
CLikeCompiler.needs_static_linker
(self)
return True
[]
def needs_static_linker(self) -> bool: return True
[ "def", "needs_static_linker", "(", "self", ")", "->", "bool", ":", "return", "True" ]
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/compilers/mixins/clike.py#L152-L153
IlyaGusev/rupo
83a5fac0dddd480a401181e5465f0e3c94ad2dcc
rupo/stress/word.py
python
StressedWord.__eq__
(self, other: 'StressedWord')
return self.text == other.text
[]
def __eq__(self, other: 'StressedWord'): return self.text == other.text
[ "def", "__eq__", "(", "self", ",", "other", ":", "'StressedWord'", ")", ":", "return", "self", ".", "text", "==", "other", ".", "text" ]
https://github.com/IlyaGusev/rupo/blob/83a5fac0dddd480a401181e5465f0e3c94ad2dcc/rupo/stress/word.py#L79-L80
cloudlinux/kuberdock-platform
8b3923c19755f3868e4142b62578d9b9857d2704
kubedock/kapi/apps.py
python
PredefinedApp.get_used_plan_entities
(self, plan_id)
return self._used_entities_by_plans[plan_id]
Method which returns entities for particular plan :param plan_id: int -> plan index :return: dict -> PA entities by names
Method which returns entities for particular plan :param plan_id: int -> plan index :return: dict -> PA entities by names
[ "Method", "which", "returns", "entities", "for", "particular", "plan", ":", "param", "plan_id", ":", "int", "-", ">", "plan", "index", ":", "return", ":", "dict", "-", ">", "PA", "entities", "by", "names" ]
def get_used_plan_entities(self, plan_id): """ Method which returns entities for particular plan :param plan_id: int -> plan index :return: dict -> PA entities by names """ if plan_id in self._used_entities_by_plans: return self._used_entities_by_plans[plan_id] self._get_filled_template_for_plan(plan_id) return self._used_entities_by_plans[plan_id]
[ "def", "get_used_plan_entities", "(", "self", ",", "plan_id", ")", ":", "if", "plan_id", "in", "self", ".", "_used_entities_by_plans", ":", "return", "self", ".", "_used_entities_by_plans", "[", "plan_id", "]", "self", ".", "_get_filled_template_for_plan", "(", "p...
https://github.com/cloudlinux/kuberdock-platform/blob/8b3923c19755f3868e4142b62578d9b9857d2704/kubedock/kapi/apps.py#L308-L317
entropy1337/infernal-twin
10995cd03312e39a48ade0f114ebb0ae3a711bb8
Modules/build/pip/pip/_vendor/distlib/manifest.py
python
Manifest.sorted
(self, wantdirs=False)
return [os.path.join(*path_tuple) for path_tuple in sorted(os.path.split(path) for path in result)]
Return sorted files in directory order
Return sorted files in directory order
[ "Return", "sorted", "files", "in", "directory", "order" ]
def sorted(self, wantdirs=False): """ Return sorted files in directory order """ def add_dir(dirs, d): dirs.add(d) logger.debug('add_dir added %s', d) if d != self.base: parent, _ = os.path.split(d) assert parent not in ('', '/') add_dir(dirs, parent) result = set(self.files) # make a copy! if wantdirs: dirs = set() for f in result: add_dir(dirs, os.path.dirname(f)) result |= dirs return [os.path.join(*path_tuple) for path_tuple in sorted(os.path.split(path) for path in result)]
[ "def", "sorted", "(", "self", ",", "wantdirs", "=", "False", ")", ":", "def", "add_dir", "(", "dirs", ",", "d", ")", ":", "dirs", ".", "add", "(", "d", ")", "logger", ".", "debug", "(", "'add_dir added %s'", ",", "d", ")", "if", "d", "!=", "self"...
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/pip/_vendor/distlib/manifest.py#L96-L116
Skyscanner/LambdaGuard
51e9a0b4acd4a14583d86fc4b5a2287d36560e25
lambdaguard/__init__.py
python
get_regions
(args)
return regions
Valid region specification: Single: eu-west-1 Multiple: eu-west-1,ap-south-1,us-east-2 All: all Returns regions as a Python list
Valid region specification: Single: eu-west-1 Multiple: eu-west-1,ap-south-1,us-east-2 All: all Returns regions as a Python list
[ "Valid", "region", "specification", ":", "Single", ":", "eu", "-", "west", "-", "1", "Multiple", ":", "eu", "-", "west", "-", "1", "ap", "-", "south", "-", "1", "us", "-", "east", "-", "2", "All", ":", "all", "Returns", "regions", "as", "a", "Pyt...
def get_regions(args): """ Valid region specification: Single: eu-west-1 Multiple: eu-west-1,ap-south-1,us-east-2 All: all Returns regions as a Python list """ if not isinstance(args.region, str): raise ValueError("No region specified") if args.function: return [arnparse(args.function).region] available = boto3.Session().get_available_regions("lambda") if args.region == "all": return available regions = args.region.split(",") if not regions: raise ValueError("No region specified") for region in regions: if region not in available: raise ValueError(f'Invalid region "{region}"') return regions
[ "def", "get_regions", "(", "args", ")", ":", "if", "not", "isinstance", "(", "args", ".", "region", ",", "str", ")", ":", "raise", "ValueError", "(", "\"No region specified\"", ")", "if", "args", ".", "function", ":", "return", "[", "arnparse", "(", "arg...
https://github.com/Skyscanner/LambdaGuard/blob/51e9a0b4acd4a14583d86fc4b5a2287d36560e25/lambdaguard/__init__.py#L53-L74
steveKapturowski/tensorflow-rl
6dc58da69bad0349a646cfc94ea9c5d1eada8351
algorithms/cem_actor_learner.py
python
CEMLearner.choose_next_action
(self, state)
return self.local_network.get_action(self.session, state)
[]
def choose_next_action(self, state): return self.local_network.get_action(self.session, state)
[ "def", "choose_next_action", "(", "self", ",", "state", ")", ":", "return", "self", ".", "local_network", ".", "get_action", "(", "self", ".", "session", ",", "state", ")" ]
https://github.com/steveKapturowski/tensorflow-rl/blob/6dc58da69bad0349a646cfc94ea9c5d1eada8351/algorithms/cem_actor_learner.py#L41-L42
plangrid/flask-rebar
a5b8697450689e2ae2234992b0f2f7f2ef8eec78
flask_rebar/rebar.py
python
get_validated_headers
()
return g.validated_headers
Retrieve the result of validating/transforming an incoming request's headers with the `headers_schema` a handler was registered with. :rtype: dict
Retrieve the result of validating/transforming an incoming request's headers with the `headers_schema` a handler was registered with.
[ "Retrieve", "the", "result", "of", "validating", "/", "transforming", "an", "incoming", "request", "s", "headers", "with", "the", "headers_schema", "a", "handler", "was", "registered", "with", "." ]
def get_validated_headers(): """ Retrieve the result of validating/transforming an incoming request's headers with the `headers_schema` a handler was registered with. :rtype: dict """ return g.validated_headers
[ "def", "get_validated_headers", "(", ")", ":", "return", "g", ".", "validated_headers" ]
https://github.com/plangrid/flask-rebar/blob/a5b8697450689e2ae2234992b0f2f7f2ef8eec78/flask_rebar/rebar.py#L192-L199
wradlib/wradlib
25f9768ddfd69b5c339d8b22d20e45e591eaeb8d
wradlib/io/iris.py
python
IrisRawFile._check_record
(self)
return chk
Checks record for correct size. Returns ------- chk : bool False, if record is truncated.
Checks record for correct size.
[ "Checks", "record", "for", "correct", "size", "." ]
def _check_record(self): """Checks record for correct size. Returns ------- chk : bool False, if record is truncated. """ # we do not know filesize (structure_size) before reading first record, # so we try and pass try: if self.record_number >= self.structure_size / RECORD_BYTES: return False except AttributeError: pass chk = self._rh.record.shape[0] == RECORD_BYTES if not chk: raise EOFError(f"Unexpected file end detected at record {self.rh.recnum}") return chk
[ "def", "_check_record", "(", "self", ")", ":", "# we do not know filesize (structure_size) before reading first record,", "# so we try and pass", "try", ":", "if", "self", ".", "record_number", ">=", "self", ".", "structure_size", "/", "RECORD_BYTES", ":", "return", "Fals...
https://github.com/wradlib/wradlib/blob/25f9768ddfd69b5c339d8b22d20e45e591eaeb8d/wradlib/io/iris.py#L3249-L3267
RichardFrangenberg/Prism
09283b5146d9cdf9d489dcf252f7927083534a48
Prism/Plugins/ProjectManagers/Shotgun/external_modules/shotgun_api3/shotgun.py
python
Shotgun.work_schedule_update
(self, date, working, description=None, project=None, user=None, recalculate_field=None)
return self._call_rpc("work_schedule_update", params)
Update the work schedule for a given date. .. versionadded:: 3.0.9 Requires Shotgun server v3.2.0+ If neither ``project`` nor ``user`` are passed in, the studio work schedule will be updated. ``project`` and ``user`` can only be used exclusively of each other. >>> sg.work_schedule_update ("2015-12-31", working=False, ... description="Studio closed for New Years Eve", project=None, ... user=None, recalculate_field=None) {'date': '2015-12-31', 'description': "Studio closed for New Years Eve", 'project': None, 'user': None, 'working': False} :param str date: Date of WorkDayRule to update. ``YYY-MM-DD`` :param bool working: Indicates whether the day is a working day or not. :param str description: Optional reason for time off. :param dict project: Optional Project entity to assign the rule to. Cannot be used with the ``user`` param. :param dict user: Optional HumanUser entity to assign the rule to. Cannot be used with the ``project`` param. :param str recalculate_field: Optional schedule field that will be recalculated on Tasks when they are affected by a change in working schedule. Options are ``due_date`` or ``duration``. Defaults to the value set in the Shotgun web application's Site Preferences. :returns: dict containing key/value pairs for each value of the work day rule updated. :rtype: dict
Update the work schedule for a given date.
[ "Update", "the", "work", "schedule", "for", "a", "given", "date", "." ]
def work_schedule_update(self, date, working, description=None, project=None, user=None, recalculate_field=None): """ Update the work schedule for a given date. .. versionadded:: 3.0.9 Requires Shotgun server v3.2.0+ If neither ``project`` nor ``user`` are passed in, the studio work schedule will be updated. ``project`` and ``user`` can only be used exclusively of each other. >>> sg.work_schedule_update ("2015-12-31", working=False, ... description="Studio closed for New Years Eve", project=None, ... user=None, recalculate_field=None) {'date': '2015-12-31', 'description': "Studio closed for New Years Eve", 'project': None, 'user': None, 'working': False} :param str date: Date of WorkDayRule to update. ``YYY-MM-DD`` :param bool working: Indicates whether the day is a working day or not. :param str description: Optional reason for time off. :param dict project: Optional Project entity to assign the rule to. Cannot be used with the ``user`` param. :param dict user: Optional HumanUser entity to assign the rule to. Cannot be used with the ``project`` param. :param str recalculate_field: Optional schedule field that will be recalculated on Tasks when they are affected by a change in working schedule. Options are ``due_date`` or ``duration``. Defaults to the value set in the Shotgun web application's Site Preferences. :returns: dict containing key/value pairs for each value of the work day rule updated. :rtype: dict """ if not self.server_caps.version or self.server_caps.version < (3, 2, 0): raise ShotgunError("Work schedule support requires server version 3.2 or " "higher, server is %s" % (self.server_caps.version,)) if not isinstance(date, str): raise ShotgunError("The date argument must be string in YYYY-MM-DD format") params = dict( date=date, working=working, description=description, project=project, user=user, recalculate_field=recalculate_field ) return self._call_rpc("work_schedule_update", params)
[ "def", "work_schedule_update", "(", "self", ",", "date", ",", "working", ",", "description", "=", "None", ",", "project", "=", "None", ",", "user", "=", "None", ",", "recalculate_field", "=", "None", ")", ":", "if", "not", "self", ".", "server_caps", "."...
https://github.com/RichardFrangenberg/Prism/blob/09283b5146d9cdf9d489dcf252f7927083534a48/Prism/Plugins/ProjectManagers/Shotgun/external_modules/shotgun_api3/shotgun.py#L1678-L1729
mkeeter/kokopelli
c99b7909e138c42c7d5c99927f5031f021bffd77
koko/prims/points.py
python
Point.__init__
(self, name='point', x=0, y=0)
[]
def __init__(self, name='point', x=0, y=0): Primitive.__init__(self, name) self.create_evaluators(x=(x,float), y=(y,float))
[ "def", "__init__", "(", "self", ",", "name", "=", "'point'", ",", "x", "=", "0", ",", "y", "=", "0", ")", ":", "Primitive", ".", "__init__", "(", "self", ",", "name", ")", "self", ".", "create_evaluators", "(", "x", "=", "(", "x", ",", "float", ...
https://github.com/mkeeter/kokopelli/blob/c99b7909e138c42c7d5c99927f5031f021bffd77/koko/prims/points.py#L13-L15
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/core/leoNodes.py
python
Position.safeMoveToThreadNext
(self)
return p
Move a position to threadNext position. Issue an error if any vnode is an ancestor of itself.
Move a position to threadNext position. Issue an error if any vnode is an ancestor of itself.
[ "Move", "a", "position", "to", "threadNext", "position", ".", "Issue", "an", "error", "if", "any", "vnode", "is", "an", "ancestor", "of", "itself", "." ]
def safeMoveToThreadNext(self): """ Move a position to threadNext position. Issue an error if any vnode is an ancestor of itself. """ p = self if p.v: child_v = p.v.children and p.v.children[0] if child_v: for parent in p.self_and_parents(copy=False): if child_v == parent.v: g.app.structure_errors += 1 g.error(f"vnode: {child_v} is its own parent") # Allocating a new vnode would be difficult. # Just remove child_v from parent.v.children. parent.v.children = [ v2 for v2 in parent.v.children if not v2 == child_v] if parent.v in child_v.parents: child_v.parents.remove(parent.v) # Try not to hang. p.moveToParent() break elif child_v.fileIndex == parent.v.fileIndex: g.app.structure_errors += 1 g.error( f"duplicate gnx: {child_v.fileIndex!r} " f"v: {child_v} parent: {parent.v}") child_v.fileIndex = g.app.nodeIndices.getNewIndex(v=child_v) assert child_v.gnx != parent.v.gnx # Should be ok to continue. p.moveToFirstChild() break else: p.moveToFirstChild() elif p.hasNext(): p.moveToNext() else: p.moveToParent() while p: if p.hasNext(): p.moveToNext() break # found p.moveToParent() # not found. return p
[ "def", "safeMoveToThreadNext", "(", "self", ")", ":", "p", "=", "self", "if", "p", ".", "v", ":", "child_v", "=", "p", ".", "v", ".", "children", "and", "p", ".", "v", ".", "children", "[", "0", "]", "if", "child_v", ":", "for", "parent", "in", ...
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/core/leoNodes.py#L1364-L1408
EventGhost/EventGhost
177be516849e74970d2e13cda82244be09f277ce
eg/Classes/MainFrame/__init__.py
python
MainFrame.CreateTreePopupMenu
(self)
return menu
Creates the pop-up menu for the configuration tree.
Creates the pop-up menu for the configuration tree.
[ "Creates", "the", "pop", "-", "up", "menu", "for", "the", "configuration", "tree", "." ]
def CreateTreePopupMenu(self): """ Creates the pop-up menu for the configuration tree. """ menu = wx.Menu() text = Text.Menu def Append(ident, kind=wx.ITEM_NORMAL, image=wx.NullBitmap): item = wx.MenuItem(menu, ID[ident], getattr(text, ident), "", kind) item.SetBitmap(image) menu.AppendItem(item) return item Append("Expand", image=GetInternalBitmap("expand")) Append("Collapse", image=GetInternalBitmap("collapse")) Append("ExpandChilds", image=GetInternalBitmap("expand_children")) Append("CollapseChilds", image=GetInternalBitmap("collapse_children")) Append("ExpandAll", image=GetInternalBitmap("expand_all")) Append("CollapseAll", image=GetInternalBitmap("collapse_all")) subm = menu menu = wx.Menu() Append("Undo") Append("Redo") menu.AppendSeparator() Append("Cut") Append("Copy") Append("Python") Append("Paste") Append("Delete") menu.AppendSeparator() menu.AppendMenu(wx.ID_ANY, text=text.ExpandCollapseMenu, submenu=subm) menu.AppendSeparator() Append("AddPlugin", image=ADD_PLUGIN_ICON) Append("AddFolder", image=ADD_FOLDER_ICON) Append("AddMacro", image=ADD_MACRO_ICON) Append("AddEvent", image=ADD_EVENT_ICON) Append("AddAction", image=ADD_ACTION_ICON) menu.AppendSeparator() Append("Configure") Append("Rename") Append("Execute") menu.AppendSeparator() Append("Disabled", kind=wx.ITEM_CHECK) return menu
[ "def", "CreateTreePopupMenu", "(", "self", ")", ":", "menu", "=", "wx", ".", "Menu", "(", ")", "text", "=", "Text", ".", "Menu", "def", "Append", "(", "ident", ",", "kind", "=", "wx", ".", "ITEM_NORMAL", ",", "image", "=", "wx", ".", "NullBitmap", ...
https://github.com/EventGhost/EventGhost/blob/177be516849e74970d2e13cda82244be09f277ce/eg/Classes/MainFrame/__init__.py#L447-L491
tobegit3hub/deep_image_model
8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e
java_predict_client/src/main/proto/tensorflow/python/ops/functional_ops.py
python
foldl
(fn, elems, initializer=None, parallel_iterations=10, back_prop=True, swap_memory=False, name=None)
foldl on the list of tensors unpacked from `elems` on dimension 0. This foldl operator repeatedly applies the callable `fn` to a sequence of elements from first to last. The elements are made of the tensors unpacked from `elems` on dimension 0. The callable fn takes two tensors as arguments. The first argument is the accumulated value computed from the preceding invocation of fn. If `initializer` is None, `elems` must contain at least one element, and its first element is used as the initializer. Suppose that `elems` is unpacked into `values`, a list of tensors. The shape of the result tensor is fn(initializer, values[0]).shape`. Args: fn: The callable to be performed. elems: A tensor to be unpacked on dimension 0. initializer: (optional) The initial value for the accumulator. parallel_iterations: (optional) The number of iterations allowed to run in parallel. back_prop: (optional) True enables support for back propagation. swap_memory: (optional) True enables GPU-CPU memory swapping. name: (optional) Name prefix for the returned tensors. Returns: A tensor resulting from applying `fn` consecutively to the list of tensors unpacked from `elems`, from first to last. Raises: TypeError: if `fn` is not callable. Example: ```python elems = [1, 2, 3, 4, 5, 6] sum = foldl(lambda a, x: a + x, elems) # sum == 21 ```
foldl on the list of tensors unpacked from `elems` on dimension 0.
[ "foldl", "on", "the", "list", "of", "tensors", "unpacked", "from", "elems", "on", "dimension", "0", "." ]
def foldl(fn, elems, initializer=None, parallel_iterations=10, back_prop=True, swap_memory=False, name=None): """foldl on the list of tensors unpacked from `elems` on dimension 0. This foldl operator repeatedly applies the callable `fn` to a sequence of elements from first to last. The elements are made of the tensors unpacked from `elems` on dimension 0. The callable fn takes two tensors as arguments. The first argument is the accumulated value computed from the preceding invocation of fn. If `initializer` is None, `elems` must contain at least one element, and its first element is used as the initializer. Suppose that `elems` is unpacked into `values`, a list of tensors. The shape of the result tensor is fn(initializer, values[0]).shape`. Args: fn: The callable to be performed. elems: A tensor to be unpacked on dimension 0. initializer: (optional) The initial value for the accumulator. parallel_iterations: (optional) The number of iterations allowed to run in parallel. back_prop: (optional) True enables support for back propagation. swap_memory: (optional) True enables GPU-CPU memory swapping. name: (optional) Name prefix for the returned tensors. Returns: A tensor resulting from applying `fn` consecutively to the list of tensors unpacked from `elems`, from first to last. Raises: TypeError: if `fn` is not callable. Example: ```python elems = [1, 2, 3, 4, 5, 6] sum = foldl(lambda a, x: a + x, elems) # sum == 21 ``` """ if not callable(fn): raise TypeError("fn must be callable.") with ops.name_scope(name, "foldl", [elems]): # Any get_variable calls in fn will cache the first call locally # and not issue repeated network I/O requests for each iteration. varscope = vs.get_variable_scope() varscope_caching_device_was_none = False if varscope.caching_device is None: # TODO(ebrevdo): Change to using colocate_with here and in other methods. varscope.set_caching_device(lambda op: op.device) varscope_caching_device_was_none = True # Convert elems to tensor array. elems = ops.convert_to_tensor(elems, name="elems") n = array_ops.shape(elems)[0] elems_ta = tensor_array_ops.TensorArray(dtype=elems.dtype, size=n, dynamic_size=False, infer_shape=True) elems_ta = elems_ta.unpack(elems) if initializer is None: a = elems_ta.read(0) i = constant_op.constant(1) else: a = ops.convert_to_tensor(initializer) i = constant_op.constant(0) def compute(i, a): a = fn(a, elems_ta.read(i)) return [i + 1, a] _, r_a = control_flow_ops.while_loop( lambda i, a: i < n, compute, [i, a], parallel_iterations=parallel_iterations, back_prop=back_prop, swap_memory=swap_memory) if varscope_caching_device_was_none: varscope.set_caching_device(None) return r_a
[ "def", "foldl", "(", "fn", ",", "elems", ",", "initializer", "=", "None", ",", "parallel_iterations", "=", "10", ",", "back_prop", "=", "True", ",", "swap_memory", "=", "False", ",", "name", "=", "None", ")", ":", "if", "not", "callable", "(", "fn", ...
https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/python/ops/functional_ops.py#L53-L130
niosus/EasyClangComplete
3b16eb17735aaa3f56bb295fc5481b269ee9f2ef
plugin/clang/cindex37.py
python
Type.is_function_variadic
(self)
return conf.lib.clang_isFunctionTypeVariadic(self)
Determine whether this function Type is a variadic function type.
Determine whether this function Type is a variadic function type.
[ "Determine", "whether", "this", "function", "Type", "is", "a", "variadic", "function", "type", "." ]
def is_function_variadic(self): """Determine whether this function Type is a variadic function type.""" assert self.kind == TypeKind.FUNCTIONPROTO return conf.lib.clang_isFunctionTypeVariadic(self)
[ "def", "is_function_variadic", "(", "self", ")", ":", "assert", "self", ".", "kind", "==", "TypeKind", ".", "FUNCTIONPROTO", "return", "conf", ".", "lib", ".", "clang_isFunctionTypeVariadic", "(", "self", ")" ]
https://github.com/niosus/EasyClangComplete/blob/3b16eb17735aaa3f56bb295fc5481b269ee9f2ef/plugin/clang/cindex37.py#L1837-L1841
aosp-mirror/tools_repo
1f20776dbb3b87ba39928dc4baba58f9c2d17c80
git_config.py
python
Branch.LocalMerge
(self)
return None
Convert the merge spec to a local name.
Convert the merge spec to a local name.
[ "Convert", "the", "merge", "spec", "to", "a", "local", "name", "." ]
def LocalMerge(self): """Convert the merge spec to a local name. """ if self.remote and self.merge: return self.remote.ToLocal(self.merge) return None
[ "def", "LocalMerge", "(", "self", ")", ":", "if", "self", ".", "remote", "and", "self", ".", "merge", ":", "return", "self", ".", "remote", ".", "ToLocal", "(", "self", ".", "merge", ")", "return", "None" ]
https://github.com/aosp-mirror/tools_repo/blob/1f20776dbb3b87ba39928dc4baba58f9c2d17c80/git_config.py#L810-L815
Ultimaker/Cura
a1622c77ea7259ecb956acd6de07b7d34b7ac52b
cura/Settings/CuraContainerStack.py
python
CuraContainerStack.definitionChanges
(self)
return cast(InstanceContainer, self._containers[_ContainerIndexes.DefinitionChanges])
Get the definition changes container. :return: The definition changes container. Should always be a valid container, but can be equal to the empty InstanceContainer.
Get the definition changes container.
[ "Get", "the", "definition", "changes", "container", "." ]
def definitionChanges(self) -> InstanceContainer: """Get the definition changes container. :return: The definition changes container. Should always be a valid container, but can be equal to the empty InstanceContainer. """ return cast(InstanceContainer, self._containers[_ContainerIndexes.DefinitionChanges])
[ "def", "definitionChanges", "(", "self", ")", "->", "InstanceContainer", ":", "return", "cast", "(", "InstanceContainer", ",", "self", ".", "_containers", "[", "_ContainerIndexes", ".", "DefinitionChanges", "]", ")" ]
https://github.com/Ultimaker/Cura/blob/a1622c77ea7259ecb956acd6de07b7d34b7ac52b/cura/Settings/CuraContainerStack.py#L181-L187
getsentry/sentry
83b1f25aac3e08075e0e2495bc29efaf35aca18a
src/sentry/notifications/manager.py
python
NotificationsManager.get_settings
( self, provider: ExternalProviders, type: NotificationSettingTypes, user: User | None = None, team: Team | None = None, project: Project | None = None, organization: Organization | None = None, )
return ( NotificationSettingOptionValues(settings[0].value) if settings else NotificationSettingOptionValues.DEFAULT )
One and only one of (user, team, project, or organization) must not be null. This function automatically translates a missing DB row to NotificationSettingOptionValues.DEFAULT.
One and only one of (user, team, project, or organization) must not be null. This function automatically translates a missing DB row to NotificationSettingOptionValues.DEFAULT.
[ "One", "and", "only", "one", "of", "(", "user", "team", "project", "or", "organization", ")", "must", "not", "be", "null", ".", "This", "function", "automatically", "translates", "a", "missing", "DB", "row", "to", "NotificationSettingOptionValues", ".", "DEFAU...
def get_settings( self, provider: ExternalProviders, type: NotificationSettingTypes, user: User | None = None, team: Team | None = None, project: Project | None = None, organization: Organization | None = None, ) -> NotificationSettingOptionValues: """ One and only one of (user, team, project, or organization) must not be null. This function automatically translates a missing DB row to NotificationSettingOptionValues.DEFAULT. """ # The `unique_together` constraint should guarantee 0 or 1 rows, but # using `list()` rather than `.first()` to prevent Django from adding an # ordering that could make the query slow. settings = list(self.find_settings(provider, type, user, team, project, organization))[:1] return ( NotificationSettingOptionValues(settings[0].value) if settings else NotificationSettingOptionValues.DEFAULT )
[ "def", "get_settings", "(", "self", ",", "provider", ":", "ExternalProviders", ",", "type", ":", "NotificationSettingTypes", ",", "user", ":", "User", "|", "None", "=", "None", ",", "team", ":", "Team", "|", "None", "=", "None", ",", "project", ":", "Pro...
https://github.com/getsentry/sentry/blob/83b1f25aac3e08075e0e2495bc29efaf35aca18a/src/sentry/notifications/manager.py#L40-L62
tensorflow/tensor2tensor
2a33b152d7835af66a6d20afe7961751047e28dd
tensor2tensor/models/transformer.py
python
transformer_tall_pretrain_lm_tpu_adafactor
()
return hparams
Hparams for transformer on LM pretraining (with 64k vocab) on TPU.
Hparams for transformer on LM pretraining (with 64k vocab) on TPU.
[ "Hparams", "for", "transformer", "on", "LM", "pretraining", "(", "with", "64k", "vocab", ")", "on", "TPU", "." ]
def transformer_tall_pretrain_lm_tpu_adafactor(): """Hparams for transformer on LM pretraining (with 64k vocab) on TPU.""" hparams = transformer_tall_pretrain_lm() update_hparams_for_tpu(hparams) hparams.max_length = 1024 # For multi-problem on TPU we need it in absolute examples. hparams.batch_size = 8 hparams.multiproblem_vocab_size = 2**16 return hparams
[ "def", "transformer_tall_pretrain_lm_tpu_adafactor", "(", ")", ":", "hparams", "=", "transformer_tall_pretrain_lm", "(", ")", "update_hparams_for_tpu", "(", "hparams", ")", "hparams", ".", "max_length", "=", "1024", "# For multi-problem on TPU we need it in absolute examples.",...
https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/models/transformer.py#L2115-L2123
seppius-xbmc-repo/ru
d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2
script.module.elementtree/lib/elementtree/ElementTree.py
python
dump
(elem)
[]
def dump(elem): # debugging if not isinstance(elem, ElementTree): elem = ElementTree(elem) elem.write(sys.stdout) tail = elem.getroot().tail if not tail or tail[-1] != "\n": sys.stdout.write("\n")
[ "def", "dump", "(", "elem", ")", ":", "# debugging", "if", "not", "isinstance", "(", "elem", ",", "ElementTree", ")", ":", "elem", "=", "ElementTree", "(", "elem", ")", "elem", ".", "write", "(", "sys", ".", "stdout", ")", "tail", "=", "elem", ".", ...
https://github.com/seppius-xbmc-repo/ru/blob/d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2/script.module.elementtree/lib/elementtree/ElementTree.py#L776-L783
Yam-cn/pyalgotrade-cn
d8ba00e9a2bb609e3e925db17a9a97929c57f672
pyalgotrade/cn/CTP/api/CTPTdApi.py
python
CTPTdApi.onRspQryTradingAccount
(self, data, error, n, last)
资金账户查询回报
资金账户查询回报
[ "资金账户查询回报" ]
def onRspQryTradingAccount(self, data, error, n, last): """资金账户查询回报""" self._server.onAccount(data)
[ "def", "onRspQryTradingAccount", "(", "self", ",", "data", ",", "error", ",", "n", ",", "last", ")", ":", "self", ".", "_server", ".", "onAccount", "(", "data", ")" ]
https://github.com/Yam-cn/pyalgotrade-cn/blob/d8ba00e9a2bb609e3e925db17a9a97929c57f672/pyalgotrade/cn/CTP/api/CTPTdApi.py#L199-L201
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/ext/ipaddress.py
python
IPv6Address.is_multicast
(self)
return self in self._constants._multicast_network
Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details.
Test if the address is reserved for multicast use.
[ "Test", "if", "the", "address", "is", "reserved", "for", "multicast", "use", "." ]
def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return self in self._constants._multicast_network
[ "def", "is_multicast", "(", "self", ")", ":", "return", "self", "in", "self", ".", "_constants", ".", "_multicast_network" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/ext/ipaddress.py#L2013-L2021
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
EventType.get_paper_doc_mention
(self)
return self._value
(paper) Mentioned user in Paper doc Only call this if :meth:`is_paper_doc_mention` is true. :rtype: PaperDocMentionType
(paper) Mentioned user in Paper doc
[ "(", "paper", ")", "Mentioned", "user", "in", "Paper", "doc" ]
def get_paper_doc_mention(self): """ (paper) Mentioned user in Paper doc Only call this if :meth:`is_paper_doc_mention` is true. :rtype: PaperDocMentionType """ if not self.is_paper_doc_mention(): raise AttributeError("tag 'paper_doc_mention' not set") return self._value
[ "def", "get_paper_doc_mention", "(", "self", ")", ":", "if", "not", "self", ".", "is_paper_doc_mention", "(", ")", ":", "raise", "AttributeError", "(", "\"tag 'paper_doc_mention' not set\"", ")", "return", "self", ".", "_value" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L34424-L34434
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/mailbox.py
python
mbox._post_message_hook
(self, f)
Called after writing each message to file f.
Called after writing each message to file f.
[ "Called", "after", "writing", "each", "message", "to", "file", "f", "." ]
def _post_message_hook(self, f): """Called after writing each message to file f.""" f.write(os.linesep)
[ "def", "_post_message_hook", "(", "self", ",", "f", ")", ":", "f", ".", "write", "(", "os", ".", "linesep", ")" ]
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/mailbox.py#L834-L836
riverloopsec/tumblerf
ad79f9dbbfee0612433be3d71c859d6918395f10
tumblerf/generators/dot15d4_isotope_franconiannotch.py
python
Dot15d4FranconianNotchGenerator.yield_test_case
(self, count, constraints=None)
Is a Python generator which yields potential test cases to use. :param constraints: Dictionary of constraints to apply, which: Optionally have the key 'max_fill' set to an integer, indicating the maximum number of nibbles to turn to fill. Deafult=8. Optionally the key 'min_fill' to fix a minimum number of nibbles to turn to fill. Default=0. Optionally have the key 'fill_byte' to specify a byte (as a string) to fill with. Default="\xff" :yield: A byte array generated as a possible test case.
Is a Python generator which yields potential test cases to use. :param constraints: Dictionary of constraints to apply, which: Optionally have the key 'max_fill' set to an integer, indicating the maximum number of nibbles to turn to fill. Deafult=8. Optionally the key 'min_fill' to fix a minimum number of nibbles to turn to fill. Default=0. Optionally have the key 'fill_byte' to specify a byte (as a string) to fill with. Default="\xff" :yield: A byte array generated as a possible test case.
[ "Is", "a", "Python", "generator", "which", "yields", "potential", "test", "cases", "to", "use", ".", ":", "param", "constraints", ":", "Dictionary", "of", "constraints", "to", "apply", "which", ":", "Optionally", "have", "the", "key", "max_fill", "set", "to"...
def yield_test_case(self, count, constraints=None): """ Is a Python generator which yields potential test cases to use. :param constraints: Dictionary of constraints to apply, which: Optionally have the key 'max_fill' set to an integer, indicating the maximum number of nibbles to turn to fill. Deafult=8. Optionally the key 'min_fill' to fix a minimum number of nibbles to turn to fill. Default=0. Optionally have the key 'fill_byte' to specify a byte (as a string) to fill with. Default="\xff" :yield: A byte array generated as a possible test case. """ if constraints is None: max_fill = 8 min_fill = 0 fill_byte = "\xff" else: max_fill = constraints.get('max_fill', 8) if type(max_fill) is not int or max_fill > 8: raise ValueError("If provide a constraint with key 'preamb_len' set to an integer < 8.") min_fill = constraints.get('min_fill', 0) if type(min_fill) is not int: raise ValueError("If provide a constraint with key 'min_fill', it must be an integer.") fill_byte = constraints.get('fill_byte', "\xff") if type(fill_byte) is not str or len(fill_byte) != 1: raise ValueError("If provide a constraint with key 'fill_byte', it must be an single-byte string.") for i in range(count): for f_len in range(min_fill, max_fill+1): # Create a beacon request frame: pkt = Dot15d4FCS(seqnum=self.__start_seqnum, fcf_ackreq=True) / \ Dot15d4Cmd(dest_panid=self.__target_pan_id, dest_addr=self.__target_short_addr, cmd_id=7) self.__start_seqnum = (self.__start_seqnum + 1) % (0xFF + 1) # This will contain the FCS due to Dot15d4FCS: syncpkt = str(pkt) # As we are providing the PHY items, we add the SFD and length of the packet to the front: syncpkt = SFD + struct.pack('b', len(syncpkt)) + syncpkt #print("Beacon Request Formed: {}".format(syncpkt.encode('hex'))) #Dot15d4FCS(syncpkt).show() if (f_len%2) != 0: fb = ord(fill_byte) fb = (((fb >> 4)) << 4) # move symbol to high nibble so sent last, clear low fb = struct.pack('B', fb) preamble = ("\x00" * ((8 - f_len - 1) / 2)) + fb + (fill_byte * (f_len/2)) else: preamble = ("\x00" * ((8 - f_len) / 2)) + (fill_byte * (f_len/2)) yield preamble+syncpkt
[ "def", "yield_test_case", "(", "self", ",", "count", ",", "constraints", "=", "None", ")", ":", "if", "constraints", "is", "None", ":", "max_fill", "=", "8", "min_fill", "=", "0", "fill_byte", "=", "\"\\xff\"", "else", ":", "max_fill", "=", "constraints", ...
https://github.com/riverloopsec/tumblerf/blob/ad79f9dbbfee0612433be3d71c859d6918395f10/tumblerf/generators/dot15d4_isotope_franconiannotch.py#L40-L85
mozilla-services/autopush
87e273c4581af88478d9e2658aa51d8c82a6d630
autopush/web/registration.py
python
UaidRegistrationHandler.get
(self, uaid)
return d
HTTP GET Return a list of known channelIDs for a given UAID
HTTP GET
[ "HTTP", "GET" ]
def get(self, uaid): # type: (uuid.UUID) -> Deferred """HTTP GET Return a list of known channelIDs for a given UAID """ d = deferToThread(self.db.message.all_channels, str(uaid)) d.addCallback(self._write_channels, uaid) d.addErrback(self._uaid_not_found_err) d.addErrback(self._response_err) return d
[ "def", "get", "(", "self", ",", "uaid", ")", ":", "# type: (uuid.UUID) -> Deferred", "d", "=", "deferToThread", "(", "self", ".", "db", ".", "message", ".", "all_channels", ",", "str", "(", "uaid", ")", ")", "d", ".", "addCallback", "(", "self", ".", "...
https://github.com/mozilla-services/autopush/blob/87e273c4581af88478d9e2658aa51d8c82a6d630/autopush/web/registration.py#L386-L397
prompt-toolkit/python-prompt-toolkit
e9eac2eb59ec385e81742fa2ac623d4b8de00925
prompt_toolkit/history.py
python
History.load
(self)
Load the history and yield all the entries in reverse order (latest, most recent history entry first). This method can be called multiple times from the `Buffer` to repopulate the history when prompting for a new input. So we are responsible here for both caching, and making sure that strings that were were appended to the history will be incorporated next time this method is called.
Load the history and yield all the entries in reverse order (latest, most recent history entry first).
[ "Load", "the", "history", "and", "yield", "all", "the", "entries", "in", "reverse", "order", "(", "latest", "most", "recent", "history", "entry", "first", ")", "." ]
async def load(self) -> AsyncGenerator[str, None]: """ Load the history and yield all the entries in reverse order (latest, most recent history entry first). This method can be called multiple times from the `Buffer` to repopulate the history when prompting for a new input. So we are responsible here for both caching, and making sure that strings that were were appended to the history will be incorporated next time this method is called. """ if not self._loaded: self._loaded_strings = list(self.load_history_strings()) self._loaded = True for item in self._loaded_strings: yield item
[ "async", "def", "load", "(", "self", ")", "->", "AsyncGenerator", "[", "str", ",", "None", "]", ":", "if", "not", "self", ".", "_loaded", ":", "self", ".", "_loaded_strings", "=", "list", "(", "self", ".", "load_history_strings", "(", ")", ")", "self",...
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/e9eac2eb59ec385e81742fa2ac623d4b8de00925/prompt_toolkit/history.py#L46-L62
quodlibet/quodlibet
e3099c89f7aa6524380795d325cc14630031886c
quodlibet/mmkeys/gnome.py
python
GnomeBackend.__release
(self)
Tells gsd that we don't want events anymore and removes all signal matches
Tells gsd that we don't want events anymore and removes all signal matches
[ "Tells", "gsd", "that", "we", "don", "t", "want", "events", "anymore", "and", "removes", "all", "signal", "matches" ]
def __release(self): """Tells gsd that we don't want events anymore and removes all signal matches""" if not self.__interface: return if self.__key_pressed_sig: self.__interface.disconnect(self.__key_pressed_sig) self.__key_pressed_sig = None try: self.__interface.ReleaseMediaPlayerKeys('(s)', self.__name) except GLib.Error: print_exc() self.__interface = None
[ "def", "__release", "(", "self", ")", ":", "if", "not", "self", ".", "__interface", ":", "return", "if", "self", ".", "__key_pressed_sig", ":", "self", ".", "__interface", ".", "disconnect", "(", "self", ".", "__key_pressed_sig", ")", "self", ".", "__key_p...
https://github.com/quodlibet/quodlibet/blob/e3099c89f7aa6524380795d325cc14630031886c/quodlibet/mmkeys/gnome.py#L156-L171
fake-name/ReadableWebProxy
ed5c7abe38706acc2684a1e6cd80242a03c5f010
WebMirror/management/rss_parser_funcs/feed_parse_extractPraisethemetalbatWordpressCom.py
python
extractPraisethemetalbatWordpressCom
(item)
return False
Parser for 'praisethemetalbat.wordpress.com'
Parser for 'praisethemetalbat.wordpress.com'
[ "Parser", "for", "praisethemetalbat", ".", "wordpress", ".", "com" ]
def extractPraisethemetalbatWordpressCom(item): ''' Parser for 'praisethemetalbat.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('Running Away From the Hero', 'Running Away From the Hero', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
[ "def", "extractPraisethemetalbatWordpressCom", "(", "item", ")", ":", "vol", ",", "chp", ",", "frag", ",", "postfix", "=", "extractVolChapterFragmentPostfix", "(", "item", "[", "'title'", "]", ")", "if", "not", "(", "chp", "or", "vol", ")", "or", "\"preview\...
https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractPraisethemetalbatWordpressCom.py#L1-L21
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/chat/v2/service/role.py
python
RoleInstance.service_sid
(self)
return self._properties['service_sid']
:returns: The SID of the Service that the resource is associated with :rtype: unicode
:returns: The SID of the Service that the resource is associated with :rtype: unicode
[ ":", "returns", ":", "The", "SID", "of", "the", "Service", "that", "the", "resource", "is", "associated", "with", ":", "rtype", ":", "unicode" ]
def service_sid(self): """ :returns: The SID of the Service that the resource is associated with :rtype: unicode """ return self._properties['service_sid']
[ "def", "service_sid", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'service_sid'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/chat/v2/service/role.py#L346-L351
endgameinc/eql
688964d807b50ec7b309c453366dca0179778f73
eql/parser.py
python
LarkToEQL.boolean
(self, node)
return node.children[0] == "true"
Callback function to walk the AST.
Callback function to walk the AST.
[ "Callback", "function", "to", "walk", "the", "AST", "." ]
def boolean(self, node): """Callback function to walk the AST.""" return node.children[0] == "true"
[ "def", "boolean", "(", "self", ",", "node", ")", ":", "return", "node", ".", "children", "[", "0", "]", "==", "\"true\"" ]
https://github.com/endgameinc/eql/blob/688964d807b50ec7b309c453366dca0179778f73/eql/parser.py#L341-L343
voc/voctomix
3156f3546890e6ae8d379df17e5cc718eee14b15
voctocore/lib/config.py
python
VoctocoreConfigParser.getSchedule
(self)
return None
return overlay/schedule or <None> from INI configuration
return overlay/schedule or <None> from INI configuration
[ "return", "overlay", "/", "schedule", "or", "<None", ">", "from", "INI", "configuration" ]
def getSchedule(self): ''' return overlay/schedule or <None> from INI configuration ''' if self.has_option('overlay', 'schedule'): if self.has_option('overlay', 'room') or self.has_option('overlay', 'event'): return self.get('overlay', 'schedule') else: # warn if no room has been defined self.log.error( "configuration option 'overlay'/'schedule' ignored when not defining 'room' or 'event' too") return None
[ "def", "getSchedule", "(", "self", ")", ":", "if", "self", ".", "has_option", "(", "'overlay'", ",", "'schedule'", ")", ":", "if", "self", ".", "has_option", "(", "'overlay'", ",", "'room'", ")", "or", "self", ".", "has_option", "(", "'overlay'", ",", ...
https://github.com/voc/voctomix/blob/3156f3546890e6ae8d379df17e5cc718eee14b15/voctocore/lib/config.py#L66-L75
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_replication_controller_status.py
python
V1ReplicationControllerStatus.__init__
(self, available_replicas=None, conditions=None, fully_labeled_replicas=None, observed_generation=None, ready_replicas=None, replicas=None, local_vars_configuration=None)
V1ReplicationControllerStatus - a model defined in OpenAPI
V1ReplicationControllerStatus - a model defined in OpenAPI
[ "V1ReplicationControllerStatus", "-", "a", "model", "defined", "in", "OpenAPI" ]
def __init__(self, available_replicas=None, conditions=None, fully_labeled_replicas=None, observed_generation=None, ready_replicas=None, replicas=None, local_vars_configuration=None): # noqa: E501 """V1ReplicationControllerStatus - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._available_replicas = None self._conditions = None self._fully_labeled_replicas = None self._observed_generation = None self._ready_replicas = None self._replicas = None self.discriminator = None if available_replicas is not None: self.available_replicas = available_replicas if conditions is not None: self.conditions = conditions if fully_labeled_replicas is not None: self.fully_labeled_replicas = fully_labeled_replicas if observed_generation is not None: self.observed_generation = observed_generation if ready_replicas is not None: self.ready_replicas = ready_replicas self.replicas = replicas
[ "def", "__init__", "(", "self", ",", "available_replicas", "=", "None", ",", "conditions", "=", "None", ",", "fully_labeled_replicas", "=", "None", ",", "observed_generation", "=", "None", ",", "ready_replicas", "=", "None", ",", "replicas", "=", "None", ",", ...
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_replication_controller_status.py#L53-L77
HiKapok/SSD.TensorFlow
b47ff6164c8925a8bbccc593719d5bbbab996058
eval_ssd.py
python
ssd_model_fn
(features, labels, mode, params)
model_fn for SSD to be used with our Estimator.
model_fn for SSD to be used with our Estimator.
[ "model_fn", "for", "SSD", "to", "be", "used", "with", "our", "Estimator", "." ]
def ssd_model_fn(features, labels, mode, params): """model_fn for SSD to be used with our Estimator.""" filename = features['filename'] shape = features['shape'] loc_targets = features['loc_targets'] cls_targets = features['cls_targets'] match_scores = features['match_scores'] features = features['image'] global global_anchor_info decode_fn = global_anchor_info['decode_fn'] num_anchors_per_layer = global_anchor_info['num_anchors_per_layer'] all_num_anchors_depth = global_anchor_info['all_num_anchors_depth'] with tf.variable_scope(params['model_scope'], default_name=None, values=[features], reuse=tf.AUTO_REUSE): backbone = ssd_net.VGG16Backbone(params['data_format']) feature_layers = backbone.forward(features, training=(mode == tf.estimator.ModeKeys.TRAIN)) #print(feature_layers) location_pred, cls_pred = ssd_net.multibox_head(feature_layers, params['num_classes'], all_num_anchors_depth, data_format=params['data_format']) if params['data_format'] == 'channels_first': cls_pred = [tf.transpose(pred, [0, 2, 3, 1]) for pred in cls_pred] location_pred = [tf.transpose(pred, [0, 2, 3, 1]) for pred in location_pred] cls_pred = [tf.reshape(pred, [tf.shape(features)[0], -1, params['num_classes']]) for pred in cls_pred] location_pred = [tf.reshape(pred, [tf.shape(features)[0], -1, 4]) for pred in location_pred] cls_pred = tf.concat(cls_pred, axis=1) location_pred = tf.concat(location_pred, axis=1) cls_pred = tf.reshape(cls_pred, [-1, params['num_classes']]) location_pred = tf.reshape(location_pred, [-1, 4]) with tf.device('/cpu:0'): bboxes_pred = decode_fn(location_pred) bboxes_pred = tf.concat(bboxes_pred, axis=0) selected_bboxes, selected_scores = parse_by_class(cls_pred, bboxes_pred, params['num_classes'], params['select_threshold'], params['min_size'], params['keep_topk'], params['nms_topk'], params['nms_threshold']) predictions = {'filename': filename, 'shape': shape } for class_ind in range(1, params['num_classes']): predictions['scores_{}'.format(class_ind)] = tf.expand_dims(selected_scores[class_ind], axis=0) predictions['bboxes_{}'.format(class_ind)] = tf.expand_dims(selected_bboxes[class_ind], axis=0) flaten_cls_targets = tf.reshape(cls_targets, [-1]) flaten_match_scores = tf.reshape(match_scores, [-1]) flaten_loc_targets = tf.reshape(loc_targets, [-1, 4]) # each positive examples has one label positive_mask = flaten_cls_targets > 0 n_positives = tf.count_nonzero(positive_mask) batch_n_positives = tf.count_nonzero(cls_targets, -1) batch_negtive_mask = tf.equal(cls_targets, 0)#tf.logical_and(tf.equal(cls_targets, 0), match_scores > 0.) batch_n_negtives = tf.count_nonzero(batch_negtive_mask, -1) batch_n_neg_select = tf.cast(params['negative_ratio'] * tf.cast(batch_n_positives, tf.float32), tf.int32) batch_n_neg_select = tf.minimum(batch_n_neg_select, tf.cast(batch_n_negtives, tf.int32)) # hard negative mining for classification predictions_for_bg = tf.nn.softmax(tf.reshape(cls_pred, [tf.shape(features)[0], -1, params['num_classes']]))[:, :, 0] prob_for_negtives = tf.where(batch_negtive_mask, 0. - predictions_for_bg, # ignore all the positives 0. - tf.ones_like(predictions_for_bg)) topk_prob_for_bg, _ = tf.nn.top_k(prob_for_negtives, k=tf.shape(prob_for_negtives)[1]) score_at_k = tf.gather_nd(topk_prob_for_bg, tf.stack([tf.range(tf.shape(features)[0]), batch_n_neg_select - 1], axis=-1)) selected_neg_mask = prob_for_negtives >= tf.expand_dims(score_at_k, axis=-1) # include both selected negtive and all positive examples final_mask = tf.stop_gradient(tf.logical_or(tf.reshape(tf.logical_and(batch_negtive_mask, selected_neg_mask), [-1]), positive_mask)) total_examples = tf.count_nonzero(final_mask) cls_pred = tf.boolean_mask(cls_pred, final_mask) location_pred = tf.boolean_mask(location_pred, tf.stop_gradient(positive_mask)) flaten_cls_targets = tf.boolean_mask(tf.clip_by_value(flaten_cls_targets, 0, params['num_classes']), final_mask) flaten_loc_targets = tf.stop_gradient(tf.boolean_mask(flaten_loc_targets, positive_mask)) # Calculate loss, which includes softmax cross entropy and L2 regularization. #cross_entropy = (params['negative_ratio'] + 1.) * tf.cond(n_positives > 0, lambda: tf.losses.sparse_softmax_cross_entropy(labels=glabels, logits=cls_pred), lambda: 0.) cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=flaten_cls_targets, logits=cls_pred) * (params['negative_ratio'] + 1.) # Create a tensor named cross_entropy for logging purposes. tf.identity(cross_entropy, name='cross_entropy_loss') tf.summary.scalar('cross_entropy_loss', cross_entropy) #loc_loss = tf.cond(n_positives > 0, lambda: modified_smooth_l1(location_pred, tf.stop_gradient(flaten_loc_targets), sigma=1.), lambda: tf.zeros_like(location_pred)) loc_loss = modified_smooth_l1(location_pred, flaten_loc_targets, sigma=1.) loc_loss = tf.reduce_mean(tf.reduce_sum(loc_loss, axis=-1), name='location_loss') tf.summary.scalar('location_loss', loc_loss) tf.losses.add_loss(loc_loss) # Add weight decay to the loss. We exclude the batch norm variables because # doing so leads to a small improvement in accuracy. total_loss = tf.add(cross_entropy, loc_loss, name='total_loss') cls_accuracy = tf.metrics.accuracy(flaten_cls_targets, tf.argmax(cls_pred, axis=-1)) # Create a tensor named train_accuracy for logging purposes. tf.identity(cls_accuracy[1], name='cls_accuracy') tf.summary.scalar('cls_accuracy', cls_accuracy[1]) summary_hook = tf.train.SummarySaverHook(save_steps=params['save_summary_steps'], output_dir=params['summary_dir'], summary_op=tf.summary.merge_all()) if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec( mode=mode, predictions=predictions, prediction_hooks=[summary_hook], loss=None, train_op=None) else: raise ValueError('This script only support "PREDICT" mode!')
[ "def", "ssd_model_fn", "(", "features", ",", "labels", ",", "mode", ",", "params", ")", ":", "filename", "=", "features", "[", "'filename'", "]", "shape", "=", "features", "[", "'shape'", "]", "loc_targets", "=", "features", "[", "'loc_targets'", "]", "cls...
https://github.com/HiKapok/SSD.TensorFlow/blob/b47ff6164c8925a8bbccc593719d5bbbab996058/eval_ssd.py#L260-L373
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/onewire/sensor.py
python
async_setup_entry
( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, )
Set up 1-Wire platform.
Set up 1-Wire platform.
[ "Set", "up", "1", "-", "Wire", "platform", "." ]
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up 1-Wire platform.""" onewirehub = hass.data[DOMAIN][config_entry.entry_id] entities = await hass.async_add_executor_job( get_entities, onewirehub, config_entry.data ) async_add_entities(entities, True)
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "config_entry", ":", "ConfigEntry", ",", "async_add_entities", ":", "AddEntitiesCallback", ",", ")", "->", "None", ":", "onewirehub", "=", "hass", ".", "data", "[", "DOMAIN", "]", "["...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/onewire/sensor.py#L314-L324
7sDream/zhihu-py3
bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc
zhihu/answer.py
python
Answer.collect_num
(self)
获取答案收藏数 :return: 答案收藏数量 :rtype: int
获取答案收藏数
[ "获取答案收藏数" ]
def collect_num(self): """获取答案收藏数 :return: 答案收藏数量 :rtype: int """ element = self.soup.find("a", { "data-za-a": "click_answer_collected_count" }) if element is None: return 0 else: return int(element.get_text())
[ "def", "collect_num", "(", "self", ")", ":", "element", "=", "self", ".", "soup", ".", "find", "(", "\"a\"", ",", "{", "\"data-za-a\"", ":", "\"click_answer_collected_count\"", "}", ")", "if", "element", "is", "None", ":", "return", "0", "else", ":", "re...
https://github.com/7sDream/zhihu-py3/blob/bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc/zhihu/answer.py#L169-L181
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/set/src/core/scapy.py
python
hexstr
(x, onlyasc=0, onlyhex=0)
return " ".join(s)
[]
def hexstr(x, onlyasc=0, onlyhex=0): s = [] if not onlyasc: s.append(" ".join(map(lambda x:"%02x"%ord(x), x))) if not onlyhex: s.append(sane(x)) return " ".join(s)
[ "def", "hexstr", "(", "x", ",", "onlyasc", "=", "0", ",", "onlyhex", "=", "0", ")", ":", "s", "=", "[", "]", "if", "not", "onlyasc", ":", "s", ".", "append", "(", "\" \"", ".", "join", "(", "map", "(", "lambda", "x", ":", "\"%02x\"", "%", "or...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/set/src/core/scapy.py#L552-L558
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py/gluon/contrib/fpdf/fpdf.py
python
FPDF.interleaved2of5
(self, txt, x, y, w=1.0, h=10.0)
Barcode I2of5 (numeric), adds a 0 if odd lenght
Barcode I2of5 (numeric), adds a 0 if odd lenght
[ "Barcode", "I2of5", "(", "numeric", ")", "adds", "a", "0", "if", "odd", "lenght" ]
def interleaved2of5(self, txt, x, y, w=1.0, h=10.0): "Barcode I2of5 (numeric), adds a 0 if odd lenght" narrow = w / 3.0 wide = w # wide/narrow codes for the digits bar_char={'0': 'nnwwn', '1': 'wnnnw', '2': 'nwnnw', '3': 'wwnnn', '4': 'nnwnw', '5': 'wnwnn', '6': 'nwwnn', '7': 'nnnww', '8': 'wnnwn', '9': 'nwnwn', 'A': 'nn', 'Z': 'wn'} self.set_fill_color(0) code = txt # add leading zero if code-length is odd if len(code) % 2 != 0: code = '0' + code # add start and stop codes code = 'AA' + code.lower() + 'ZA' for i in range(0, len(code), 2): # choose next pair of digits char_bar = code[i] char_space = code[i+1] # check whether it is a valid digit if not char_bar in bar_char.keys(): raise RuntimeError ('Char "%s" invalid for I25: ' % char_bar) if not char_space in bar_char.keys(): raise RuntimeError ('Char "%s" invalid for I25: ' % char_space) # create a wide/narrow-seq (first digit=bars, second digit=spaces) seq = '' for s in range(0, len(bar_char[char_bar])): seq += bar_char[char_bar][s] + bar_char[char_space][s] for bar in range(0, len(seq)): # set line_width depending on value if seq[bar] == 'n': line_width = narrow else: line_width = wide # draw every second value, the other is represented by space if bar % 2 == 0: self.rect(x, y, line_width, h, 'F') x += line_width
[ "def", "interleaved2of5", "(", "self", ",", "txt", ",", "x", ",", "y", ",", "w", "=", "1.0", ",", "h", "=", "10.0", ")", ":", "narrow", "=", "w", "/", "3.0", "wide", "=", "w", "# wide/narrow codes for the digits", "bar_char", "=", "{", "'0'", ":", ...
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/gluon/contrib/fpdf/fpdf.py#L1980-L2025
rootzoll/raspiblitz
fd4256223c4ada1e1b4fdd8794792b1208514188
home.admin/config.scripts/lndlibs/rpc_pb2_grpc.py
python
LightningServicer.ListMacaroonIDs
(self, request, context)
lncli: `listmacaroonids` ListMacaroonIDs returns all root key IDs that are in use.
lncli: `listmacaroonids` ListMacaroonIDs returns all root key IDs that are in use.
[ "lncli", ":", "listmacaroonids", "ListMacaroonIDs", "returns", "all", "root", "key", "IDs", "that", "are", "in", "use", "." ]
def ListMacaroonIDs(self, request, context): """lncli: `listmacaroonids` ListMacaroonIDs returns all root key IDs that are in use. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
[ "def", "ListMacaroonIDs", "(", "self", ",", "request", ",", "context", ")", ":", "context", ".", "set_code", "(", "grpc", ".", "StatusCode", ".", "UNIMPLEMENTED", ")", "context", ".", "set_details", "(", "'Method not implemented!'", ")", "raise", "NotImplemented...
https://github.com/rootzoll/raspiblitz/blob/fd4256223c4ada1e1b4fdd8794792b1208514188/home.admin/config.scripts/lndlibs/rpc_pb2_grpc.py#L975-L981
bojone/o-gan
c7b3d089e74880e4cc250a1af9607996e75aa724
o_gan_celeba.py
python
Trainer.on_batch_end
(self, batch, logs=None)
[]
def on_batch_end(self, batch, logs=None): if self.batch % self.iters_per_sample == 0: sample('samples/test_%s.png' % self.batch, self.n_size, self.Z) sample_ae('samples/test_ae_%s.png' % self.batch) train_model.save_weights('./train_model.weights') self.batch += 1
[ "def", "on_batch_end", "(", "self", ",", "batch", ",", "logs", "=", "None", ")", ":", "if", "self", ".", "batch", "%", "self", ".", "iters_per_sample", "==", "0", ":", "sample", "(", "'samples/test_%s.png'", "%", "self", ".", "batch", ",", "self", ".",...
https://github.com/bojone/o-gan/blob/c7b3d089e74880e4cc250a1af9607996e75aa724/o_gan_celeba.py#L212-L218
google/apis-client-generator
f09f0ba855c3845d315b811c6234fd3996f33172
src/googleapis/codegen/generator.py
python
TemplateGenerator.GenerateListOfFiles
(self, path_prefix, call_info, template_path, relative_path, template_file_name, variables, package, file_filter=None)
Generate many output files from a template. This method blends together a list of CodeObjects (from call_info) with the template_file_name to produce an output file for each of the elements in the list. The names for each file are derived from a template variable of each element. Args: path_prefix: (str) The piece of path which triggers the replacement. call_info: (list) ['name to bind', [list of CodeObjects]] template_path: (str) The path of the template file. relative_path: (str) The relative path of the output file in the package. template_file_name: (str) the file name of the template for this list. The file name must contain the form '{path_prefix}{variable_name}___' (without the braces). The pair is replaced by the value of variable_name from each successive element of the call list. variables: (dict) The dictionary of variable replacements to pass to the templates. package: (LibraryWriter) The output package stream to write to. file_filter: (func) See WalkTemplateTree for a description. Raises: ValueError: If the template_file_name does not match the call_info data.
Generate many output files from a template.
[ "Generate", "many", "output", "files", "from", "a", "template", "." ]
def GenerateListOfFiles(self, path_prefix, call_info, template_path, relative_path, template_file_name, variables, package, file_filter=None): """Generate many output files from a template. This method blends together a list of CodeObjects (from call_info) with the template_file_name to produce an output file for each of the elements in the list. The names for each file are derived from a template variable of each element. Args: path_prefix: (str) The piece of path which triggers the replacement. call_info: (list) ['name to bind', [list of CodeObjects]] template_path: (str) The path of the template file. relative_path: (str) The relative path of the output file in the package. template_file_name: (str) the file name of the template for this list. The file name must contain the form '{path_prefix}{variable_name}___' (without the braces). The pair is replaced by the value of variable_name from each successive element of the call list. variables: (dict) The dictionary of variable replacements to pass to the templates. package: (LibraryWriter) The output package stream to write to. file_filter: (func) See WalkTemplateTree for a description. Raises: ValueError: If the template_file_name does not match the call_info data. """ path_and_var_regex = r'%s([a-z][A-Za-z]*)___' % path_prefix match_obj = re.compile(path_and_var_regex).match(template_file_name) if not match_obj: raise ValueError( 'file names which match path item for GenerateListOfFiles must' ' contain a variable for substitution. E.g. "___models_codeName___"') variable_name = match_obj.group(1) file_name_piece_to_replace = path_prefix + variable_name + '___' for element in call_info[1]: file_name = template_file_name.replace( file_name_piece_to_replace, element.values[variable_name]) name_in_zip = file_name[:-5] # strip '.tmpl' if file_filter and not file_filter(None, name_in_zip): continue d = dict(variables) d[call_info[0]] = element self.RenderTemplateToFile( template_path, d, package, os.path.join(relative_path, name_in_zip))
[ "def", "GenerateListOfFiles", "(", "self", ",", "path_prefix", ",", "call_info", ",", "template_path", ",", "relative_path", ",", "template_file_name", ",", "variables", ",", "package", ",", "file_filter", "=", "None", ")", ":", "path_and_var_regex", "=", "r'%s([a...
https://github.com/google/apis-client-generator/blob/f09f0ba855c3845d315b811c6234fd3996f33172/src/googleapis/codegen/generator.py#L304-L348
avalonstrel/GatedConvolution_pytorch
0a49013a70e77cc484ab45a5da535c2ac003b252
data/inpaint_dataset.py
python
InpaintDataset.read_mask
(self, path, mask_type)
return Image.fromarray(np.tile(mask,(1,1,3)).astype(np.uint8))
Read Masks now only support bbox
Read Masks now only support bbox
[ "Read", "Masks", "now", "only", "support", "bbox" ]
def read_mask(self, path, mask_type): """ Read Masks now only support bbox """ if mask_type == 'random_bbox': bboxs = [] for i in range(self.random_bbox_number): bbox = InpaintDataset.random_bbox(self.resize_shape, self.random_bbox_margin, self.random_bbox_shape) bboxs.append(bbox) elif mask_type == 'random_free_form': mask = InpaintDataset.random_ff_mask(self.random_ff_setting) return Image.fromarray(np.tile(mask,(1,1,3)).astype(np.uint8)) elif 'val' in mask_type: mask = InpaintDataset.read_val_mask(path) return Image.fromarray(np.tile(mask,(1,1,3)).astype(np.uint8)) else: bbox = InpaintDataset.read_bbox(path) bboxs = [bbox] #print(bboxs, self.resize_shape) mask = InpaintDataset.bbox2mask(bboxs, self.resize_shape) #print('final', mask.shape) return Image.fromarray(np.tile(mask,(1,1,3)).astype(np.uint8))
[ "def", "read_mask", "(", "self", ",", "path", ",", "mask_type", ")", ":", "if", "mask_type", "==", "'random_bbox'", ":", "bboxs", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "random_bbox_number", ")", ":", "bbox", "=", "InpaintDataset", ...
https://github.com/avalonstrel/GatedConvolution_pytorch/blob/0a49013a70e77cc484ab45a5da535c2ac003b252/data/inpaint_dataset.py#L90-L111
andreikop/enki
3170059e5cb46dcc77d7fb1457c38a8a5f13af66
enki/plugins/searchreplace/controller.py
python
Controller._onReplaceThreadFinished
(self)
Handler for replace in directory finished event
Handler for replace in directory finished event
[ "Handler", "for", "replace", "in", "directory", "finished", "event" ]
def _onReplaceThreadFinished(self): """Handler for replace in directory finished event """ self._widget.setReplaceInProgress(False)
[ "def", "_onReplaceThreadFinished", "(", "self", ")", ":", "self", ".", "_widget", ".", "setReplaceInProgress", "(", "False", ")" ]
https://github.com/andreikop/enki/blob/3170059e5cb46dcc77d7fb1457c38a8a5f13af66/enki/plugins/searchreplace/controller.py#L552-L555
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/pdb2pqr/contrib/numpy-1.1.0/numpy/core/defmatrix.py
python
matrix.var
(self, axis=None, dtype=None, out=None, ddof=0)
return N.ndarray.var(self, axis, dtype, out)._align(axis)
Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. Parameters ---------- axis : integer Axis along which the variance is computed. The default is to compute the variance of the flattened array. dtype : data-type Type to use in computing the variance. For arrays of integer type the default is float32, for arrays of float types it is the same as the array type. out : ndarray Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary. ddof : {0, integer} Means Delta Degrees of Freedom. The divisor used in calculations is N-ddof. Returns ------- variance : depends, see above A new array holding the result is returned unless out is specified, in which case a reference to out is returned. SeeAlso ------- std : standard deviation mean : average Notes ----- The variance is the average of the squared deviations from the mean, i.e. var = mean(abs(x - x.mean())**2). The mean is computed by dividing by N-ddof, where N is the number of elements. The argument ddof defaults to zero; for an unbiased estimate supply ddof=1. Note that for complex numbers the absolute value is taken before squaring, so that the result is always real and nonnegative.
Compute the variance along the specified axis.
[ "Compute", "the", "variance", "along", "the", "specified", "axis", "." ]
def var(self, axis=None, dtype=None, out=None, ddof=0): """Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. Parameters ---------- axis : integer Axis along which the variance is computed. The default is to compute the variance of the flattened array. dtype : data-type Type to use in computing the variance. For arrays of integer type the default is float32, for arrays of float types it is the same as the array type. out : ndarray Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary. ddof : {0, integer} Means Delta Degrees of Freedom. The divisor used in calculations is N-ddof. Returns ------- variance : depends, see above A new array holding the result is returned unless out is specified, in which case a reference to out is returned. SeeAlso ------- std : standard deviation mean : average Notes ----- The variance is the average of the squared deviations from the mean, i.e. var = mean(abs(x - x.mean())**2). The mean is computed by dividing by N-ddof, where N is the number of elements. The argument ddof defaults to zero; for an unbiased estimate supply ddof=1. Note that for complex numbers the absolute value is taken before squaring, so that the result is always real and nonnegative. """ return N.ndarray.var(self, axis, dtype, out)._align(axis)
[ "def", "var", "(", "self", ",", "axis", "=", "None", ",", "dtype", "=", "None", ",", "out", "=", "None", ",", "ddof", "=", "0", ")", ":", "return", "N", ".", "ndarray", ".", "var", "(", "self", ",", "axis", ",", "dtype", ",", "out", ")", ".",...
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/contrib/numpy-1.1.0/numpy/core/defmatrix.py#L410-L456
triaquae/py3_training
63b4e1d2e6d1a95b9bcbb1e3818e9a1f09bea5cd
FTP/MadFtpServer/core/ftp_server.py
python
FTPHandler._put
(self,*args,**kwargs)
client send file to server
client send file to server
[ "client", "send", "file", "to", "server" ]
def _put(self,*args,**kwargs): "client send file to server" pass
[ "def", "_put", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pass" ]
https://github.com/triaquae/py3_training/blob/63b4e1d2e6d1a95b9bcbb1e3818e9a1f09bea5cd/FTP/MadFtpServer/core/ftp_server.py#L89-L91
uber/clay
bab57672f11730705b5670df97047abe575a3054
clay/logger.py
python
TCPHandler.connect
(self)
Create a connection with the server, sleeping for some period of time if connection errors have occurred recently.
Create a connection with the server, sleeping for some period of time if connection errors have occurred recently.
[ "Create", "a", "connection", "with", "the", "server", "sleeping", "for", "some", "period", "of", "time", "if", "connection", "errors", "have", "occurred", "recently", "." ]
def connect(self): ''' Create a connection with the server, sleeping for some period of time if connection errors have occurred recently. ''' self.sock = socket.socket() if self.ssl_ca_file: self.sock = ssl.wrap_socket(self.sock, ssl_version=ssl.PROTOCOL_TLSv1, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ssl_ca_file) INTERNAL_LOG.debug('Connecting (backoff: %.03f)' % self.connect_wait) time.sleep(self.connect_wait) self.sock.connect((self.host, self.port))
[ "def", "connect", "(", "self", ")", ":", "self", ".", "sock", "=", "socket", ".", "socket", "(", ")", "if", "self", ".", "ssl_ca_file", ":", "self", ".", "sock", "=", "ssl", ".", "wrap_socket", "(", "self", ".", "sock", ",", "ssl_version", "=", "ss...
https://github.com/uber/clay/blob/bab57672f11730705b5670df97047abe575a3054/clay/logger.py#L48-L63
JoelBender/bacpypes
41104c2b565b2ae9a637c941dfb0fe04195c5e96
py25/bacpypes/local/file.py
python
LocalRecordAccessFileObject.__len__
(self)
Return the number of records.
Return the number of records.
[ "Return", "the", "number", "of", "records", "." ]
def __len__(self): """ Return the number of records. """ raise NotImplementedError("__len__")
[ "def", "__len__", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"__len__\"", ")" ]
https://github.com/JoelBender/bacpypes/blob/41104c2b565b2ae9a637c941dfb0fe04195c5e96/py25/bacpypes/local/file.py#L34-L36
sangwoomo/instagan
f9c1d9c9b7d2c21491317921f24a5200a02a823d
util/get_data.py
python
GetData.__init__
(self, technique='cyclegan', verbose=True)
[]
def __init__(self, technique='cyclegan', verbose=True): url_dict = { 'pix2pix': 'https://people.eecs.berkeley.edu/~tinghuiz/projects/pix2pix/datasets', 'cyclegan': 'https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets' } self.url = url_dict.get(technique.lower()) self._verbose = verbose
[ "def", "__init__", "(", "self", ",", "technique", "=", "'cyclegan'", ",", "verbose", "=", "True", ")", ":", "url_dict", "=", "{", "'pix2pix'", ":", "'https://people.eecs.berkeley.edu/~tinghuiz/projects/pix2pix/datasets'", ",", "'cyclegan'", ":", "'https://people.eecs.be...
https://github.com/sangwoomo/instagan/blob/f9c1d9c9b7d2c21491317921f24a5200a02a823d/util/get_data.py#L29-L35
cea-sec/miasm
09376c524aedc7920a7eda304d6095e12f6958f4
miasm/core/asmblock.py
python
AsmCFG.rebuild_edges
(self)
Consider blocks '.bto' and rebuild edges according to them, ie: - update constraint type - add missing edge - remove no more used edge This method should be called if a block's '.bto' in nodes have been modified without notifying this instance to resynchronize edges.
Consider blocks '.bto' and rebuild edges according to them, ie: - update constraint type - add missing edge - remove no more used edge
[ "Consider", "blocks", ".", "bto", "and", "rebuild", "edges", "according", "to", "them", "ie", ":", "-", "update", "constraint", "type", "-", "add", "missing", "edge", "-", "remove", "no", "more", "used", "edge" ]
def rebuild_edges(self): """Consider blocks '.bto' and rebuild edges according to them, ie: - update constraint type - add missing edge - remove no more used edge This method should be called if a block's '.bto' in nodes have been modified without notifying this instance to resynchronize edges. """ self._pendings = {} for block in self.blocks: edges = [] # Rebuild edges from bto for constraint in block.bto: dst = self._loc_key_to_block.get(constraint.loc_key, None) if dst is None: # Missing destination, add to pendings self._pendings.setdefault( constraint.loc_key, set() ).add( self.AsmCFGPending( block, constraint.c_t ) ) continue edge = (block.loc_key, dst.loc_key) edges.append(edge) if edge in self._edges: # Already known edge, constraint may have changed self.edges2constraint[edge] = constraint.c_t else: # An edge is missing self.add_edge(edge[0], edge[1], constraint.c_t) # Remove useless edges for succ in self.successors(block.loc_key): edge = (block.loc_key, succ) if edge not in edges: self.del_edge(*edge)
[ "def", "rebuild_edges", "(", "self", ")", ":", "self", ".", "_pendings", "=", "{", "}", "for", "block", "in", "self", ".", "blocks", ":", "edges", "=", "[", "]", "# Rebuild edges from bto", "for", "constraint", "in", "block", ".", "bto", ":", "dst", "=...
https://github.com/cea-sec/miasm/blob/09376c524aedc7920a7eda304d6095e12f6958f4/miasm/core/asmblock.py#L511-L552
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/environment_canada/weather.py
python
icon_code_to_condition
(icon_code)
return None
Return the condition corresponding to an icon code.
Return the condition corresponding to an icon code.
[ "Return", "the", "condition", "corresponding", "to", "an", "icon", "code", "." ]
def icon_code_to_condition(icon_code): """Return the condition corresponding to an icon code.""" for condition, codes in ICON_CONDITION_MAP.items(): if icon_code in codes: return condition return None
[ "def", "icon_code_to_condition", "(", "icon_code", ")", ":", "for", "condition", ",", "codes", "in", "ICON_CONDITION_MAP", ".", "items", "(", ")", ":", "if", "icon_code", "in", "codes", ":", "return", "condition", "return", "None" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/environment_canada/weather.py#L225-L230
encode/typesystem
e887641670ce63f646a6e92e77c94413308f8dc4
typesystem/json_schema.py
python
get_valid_types
(data: dict)
return (type_strings, allow_null)
Returns a two-tuple of `(type_strings, allow_null)`.
Returns a two-tuple of `(type_strings, allow_null)`.
[ "Returns", "a", "two", "-", "tuple", "of", "(", "type_strings", "allow_null", ")", "." ]
def get_valid_types(data: dict) -> typing.Tuple[typing.Set[str], bool]: """ Returns a two-tuple of `(type_strings, allow_null)`. """ type_strings = data.get("type", []) if isinstance(type_strings, str): type_strings = {type_strings} else: type_strings = set(type_strings) if not type_strings: type_strings = {"null", "boolean", "object", "array", "number", "string"} if "number" in type_strings: type_strings.discard("integer") allow_null = False if "null" in type_strings: allow_null = True type_strings.remove("null") return (type_strings, allow_null)
[ "def", "get_valid_types", "(", "data", ":", "dict", ")", "->", "typing", ".", "Tuple", "[", "typing", ".", "Set", "[", "str", "]", ",", "bool", "]", ":", "type_strings", "=", "data", ".", "get", "(", "\"type\"", ",", "[", "]", ")", "if", "isinstanc...
https://github.com/encode/typesystem/blob/e887641670ce63f646a6e92e77c94413308f8dc4/typesystem/json_schema.py#L174-L196
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
deep-learning/GANs and Variational Autoencoders/BigGAN-PyTorch/sync_batchnorm/replicate.py
python
patch_replication_callback
(data_parallel)
Monkey-patch an existing `DataParallel` object. Add the replication callback. Useful when you have customized `DataParallel` implementation. Examples: > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) > sync_bn = DataParallel(sync_bn, device_ids=[0, 1]) > patch_replication_callback(sync_bn) # this is equivalent to > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) > sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1])
Monkey-patch an existing `DataParallel` object. Add the replication callback. Useful when you have customized `DataParallel` implementation.
[ "Monkey", "-", "patch", "an", "existing", "DataParallel", "object", ".", "Add", "the", "replication", "callback", ".", "Useful", "when", "you", "have", "customized", "DataParallel", "implementation", "." ]
def patch_replication_callback(data_parallel): """ Monkey-patch an existing `DataParallel` object. Add the replication callback. Useful when you have customized `DataParallel` implementation. Examples: > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) > sync_bn = DataParallel(sync_bn, device_ids=[0, 1]) > patch_replication_callback(sync_bn) # this is equivalent to > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) > sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1]) """ assert isinstance(data_parallel, DataParallel) old_replicate = data_parallel.replicate @functools.wraps(old_replicate) def new_replicate(module, device_ids): modules = old_replicate(module, device_ids) execute_replication_callbacks(modules) return modules data_parallel.replicate = new_replicate
[ "def", "patch_replication_callback", "(", "data_parallel", ")", ":", "assert", "isinstance", "(", "data_parallel", ",", "DataParallel", ")", "old_replicate", "=", "data_parallel", ".", "replicate", "@", "functools", ".", "wraps", "(", "old_replicate", ")", "def", ...
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/deep-learning/GANs and Variational Autoencoders/BigGAN-PyTorch/sync_batchnorm/replicate.py#L70-L94
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_sankey.py
python
Sankey.idssrc
(self)
return self["idssrc"]
Sets the source reference on Chart Studio Cloud for `ids`. The 'idssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str
Sets the source reference on Chart Studio Cloud for `ids`. The 'idssrc' property must be specified as a string or as a plotly.grid_objs.Column object
[ "Sets", "the", "source", "reference", "on", "Chart", "Studio", "Cloud", "for", "ids", ".", "The", "idssrc", "property", "must", "be", "specified", "as", "a", "string", "or", "as", "a", "plotly", ".", "grid_objs", ".", "Column", "object" ]
def idssrc(self): """ Sets the source reference on Chart Studio Cloud for `ids`. The 'idssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["idssrc"]
[ "def", "idssrc", "(", "self", ")", ":", "return", "self", "[", "\"idssrc\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_sankey.py#L257-L268
python-effect/effect
0e882633a944683c7abcd7d61eb202f355ce8494
effect/_base.py
python
catch
(exc_type, callable)
return catcher
A helper for handling errors of a specific type:: eff.on(error=catch(SpecificException, lambda exc: "got an error!")) If any exception other than a ``SpecificException`` is thrown, it will be ignored by this handler and propagate further down the chain of callbacks.
A helper for handling errors of a specific type::
[ "A", "helper", "for", "handling", "errors", "of", "a", "specific", "type", "::" ]
def catch(exc_type, callable): """ A helper for handling errors of a specific type:: eff.on(error=catch(SpecificException, lambda exc: "got an error!")) If any exception other than a ``SpecificException`` is thrown, it will be ignored by this handler and propagate further down the chain of callbacks. """ def catcher(error): if isinstance(error, exc_type): return callable(error) raise error return catcher
[ "def", "catch", "(", "exc_type", ",", "callable", ")", ":", "def", "catcher", "(", "error", ")", ":", "if", "isinstance", "(", "error", ",", "exc_type", ")", ":", "return", "callable", "(", "error", ")", "raise", "error", "return", "catcher" ]
https://github.com/python-effect/effect/blob/0e882633a944683c7abcd7d61eb202f355ce8494/effect/_base.py#L158-L174
tachang/EyeFiServer
4c473e76bcf97472393773ffe352c9078ec1bf39
Release 2.0/configobj.py
python
Section.pop
(self, key, *args)
return val
'D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised'
'D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised'
[ "D", ".", "pop", "(", "k", "[", "d", "]", ")", "-", ">", "v", "remove", "specified", "key", "and", "return", "the", "corresponding", "value", ".", "If", "key", "is", "not", "found", "d", "is", "returned", "if", "given", "otherwise", "KeyError", "is",...
def pop(self, key, *args): """ 'D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised' """ val = dict.pop(self, key, *args) if key in self.scalars: del self.comments[key] del self.inline_comments[key] self.scalars.remove(key) elif key in self.sections: del self.comments[key] del self.inline_comments[key] self.sections.remove(key) if self.main.interpolation and isinstance(val, StringTypes): return self._interpolate(key, val) return val
[ "def", "pop", "(", "self", ",", "key", ",", "*", "args", ")", ":", "val", "=", "dict", ".", "pop", "(", "self", ",", "key", ",", "*", "args", ")", "if", "key", "in", "self", ".", "scalars", ":", "del", "self", ".", "comments", "[", "key", "]"...
https://github.com/tachang/EyeFiServer/blob/4c473e76bcf97472393773ffe352c9078ec1bf39/Release 2.0/configobj.py#L672-L688
mysql/mysql-utilities
08276b2258bf9739f53406b354b21195ff69a261
mysql/utilities/common/charsets.py
python
CharsetInfo.get_maxlen
(self, col_id)
return int(1)
Get the maximum length for the character set col_id[in] id for collation (as read from .frm file) Returns int - max length or 1 if not found.
Get the maximum length for the character set
[ "Get", "the", "maximum", "length", "for", "the", "character", "set" ]
def get_maxlen(self, col_id): """Get the maximum length for the character set col_id[in] id for collation (as read from .frm file) Returns int - max length or 1 if not found. """ for cs in self.charset_map: if int(cs[ID]) == int(col_id): return int(cs[MAXLEN]) return int(1)
[ "def", "get_maxlen", "(", "self", ",", "col_id", ")", ":", "for", "cs", "in", "self", ".", "charset_map", ":", "if", "int", "(", "cs", "[", "ID", "]", ")", "==", "int", "(", "col_id", ")", ":", "return", "int", "(", "cs", "[", "MAXLEN", "]", ")...
https://github.com/mysql/mysql-utilities/blob/08276b2258bf9739f53406b354b21195ff69a261/mysql/utilities/common/charsets.py#L124-L134
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/fractions.py
python
Fraction.from_decimal
(cls, dec)
return cls(*dec.as_integer_ratio())
Converts a finite Decimal instance to a rational number, exactly.
Converts a finite Decimal instance to a rational number, exactly.
[ "Converts", "a", "finite", "Decimal", "instance", "to", "a", "rational", "number", "exactly", "." ]
def from_decimal(cls, dec): """Converts a finite Decimal instance to a rational number, exactly.""" from decimal import Decimal if isinstance(dec, numbers.Integral): dec = Decimal(int(dec)) elif not isinstance(dec, Decimal): raise TypeError( "%s.from_decimal() only takes Decimals, not %r (%s)" % (cls.__name__, dec, type(dec).__name__)) return cls(*dec.as_integer_ratio())
[ "def", "from_decimal", "(", "cls", ",", "dec", ")", ":", "from", "decimal", "import", "Decimal", "if", "isinstance", "(", "dec", ",", "numbers", ".", "Integral", ")", ":", "dec", "=", "Decimal", "(", "int", "(", "dec", ")", ")", "elif", "not", "isins...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/fractions.py#L208-L217
arizvisa/ida-minsc
8627a60f047b5e55d3efeecde332039cd1a16eea
base/database.py
python
type.is_initialized
()
return type.is_initialized(ui.current.address())
Return if the current address is initialized.
Return if the current address is initialized.
[ "Return", "if", "the", "current", "address", "is", "initialized", "." ]
def is_initialized(): '''Return if the current address is initialized.''' return type.is_initialized(ui.current.address())
[ "def", "is_initialized", "(", ")", ":", "return", "type", ".", "is_initialized", "(", "ui", ".", "current", ".", "address", "(", ")", ")" ]
https://github.com/arizvisa/ida-minsc/blob/8627a60f047b5e55d3efeecde332039cd1a16eea/base/database.py#L3667-L3669
achael/eht-imaging
bbd3aeb06bef52bf89fa1c06de71e5509a5b0015
ehtim/parloop.py
python
Parloop.run_loop
(self, arglist, processes=-1)
return out
Run the loop on the list of arguments with multiple processes
Run the loop on the list of arguments with multiple processes
[ "Run", "the", "loop", "on", "the", "list", "of", "arguments", "with", "multiple", "processes" ]
def run_loop(self, arglist, processes=-1): """Run the loop on the list of arguments with multiple processes """ n = len(arglist) if not type(arglist[0]) is list: arglist = [[arg] for arg in arglist] if processes > 0: print("Set up loop with %d Processes" % processes) elif processes == 0: # maximum number of processes -- different argument? processes = int(cpu_count()) print("Set up loop with all available (%d) Processes" % processes) else: print("Set up loop with no multiprocessing") out = -1 if processes > 0: # run on multiple cores with multiprocessing counter = Counter(initval=0, maxval=n) pool = Pool(processes=processes, initializer=self._initcount, initargs=(counter,)) try: print('Running the loop') self.prog_msg(0, n, 0) out = pool.map_async(self, arglist).get(TIMEOUT) pool.close() except KeyboardInterrupt: print('\ngot ^C while pool mapping, terminating') pool.terminate() print('pool terminated') except Exception as e: print('\ngot exception: %r, terminating' % (e,)) pool.terminate() print('pool terminated') finally: pool.join() else: # run on a single core out = [] for i in range(n): self.prog_msg(i, n, i-1) args = arglist[i] out.append(self.func(*args)) return out
[ "def", "run_loop", "(", "self", ",", "arglist", ",", "processes", "=", "-", "1", ")", ":", "n", "=", "len", "(", "arglist", ")", "if", "not", "type", "(", "arglist", "[", "0", "]", ")", "is", "list", ":", "arglist", "=", "[", "[", "arg", "]", ...
https://github.com/achael/eht-imaging/blob/bbd3aeb06bef52bf89fa1c06de71e5509a5b0015/ehtim/parloop.py#L47-L91
thunder-project/thunder
967ff8f3e7c2fabe1705743d95eb2746d4329786
thunder/series/series.py
python
Series.sample
(self, n=100, seed=None)
return self._constructor(result, index=self.index)
Extract random sample of records. Parameters ---------- n : int, optional, default = 100 The number of data points to sample. seed : int, optional, default = None Random seed.
Extract random sample of records.
[ "Extract", "random", "sample", "of", "records", "." ]
def sample(self, n=100, seed=None): """ Extract random sample of records. Parameters ---------- n : int, optional, default = 100 The number of data points to sample. seed : int, optional, default = None Random seed. """ if n < 1: raise ValueError("Number of samples must be larger than 0, got '%g'" % n) if seed is None: seed = random.randint(0, 2 ** 32) if self.mode == 'spark': result = asarray(self.values.tordd().values().takeSample(False, n, seed)) else: basedims = [self.shape[d] for d in self.baseaxes] inds = [unravel_index(int(k), basedims) for k in random.rand(n) * prod(basedims)] result = asarray([self.values[tupleize(i) + (slice(None, None),)] for i in inds]) return self._constructor(result, index=self.index)
[ "def", "sample", "(", "self", ",", "n", "=", "100", ",", "seed", "=", "None", ")", ":", "if", "n", "<", "1", ":", "raise", "ValueError", "(", "\"Number of samples must be larger than 0, got '%g'\"", "%", "n", ")", "if", "seed", "is", "None", ":", "seed",...
https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/series/series.py#L137-L163
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_policy_group.py
python
RoleBinding.group_names
(self, data)
group_names property setter
group_names property setter
[ "group_names", "property", "setter" ]
def group_names(self, data): ''' group_names property setter''' self._group_names = data
[ "def", "group_names", "(", "self", ",", "data", ")", ":", "self", ".", "_group_names", "=", "data" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_policy_group.py#L1550-L1552
tensorflow/tensor2tensor
2a33b152d7835af66a6d20afe7961751047e28dd
tensor2tensor/rl/trainer_model_based_params.py
python
rlmb_base_sv2p
()
return hparams
Base setting with sv2p as world model.
Base setting with sv2p as world model.
[ "Base", "setting", "with", "sv2p", "as", "world", "model", "." ]
def rlmb_base_sv2p(): """Base setting with sv2p as world model.""" hparams = rlmb_base() hparams.learning_rate_bump = 1.0 hparams.generative_model = "next_frame_sv2p" hparams.generative_model_params = "next_frame_sv2p_atari" return hparams
[ "def", "rlmb_base_sv2p", "(", ")", ":", "hparams", "=", "rlmb_base", "(", ")", "hparams", ".", "learning_rate_bump", "=", "1.0", "hparams", ".", "generative_model", "=", "\"next_frame_sv2p\"", "hparams", ".", "generative_model_params", "=", "\"next_frame_sv2p_atari\""...
https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/rl/trainer_model_based_params.py#L571-L577
Ultimaker/Uranium
66da853cd9a04edd3a8a03526fac81e83c03f5aa
plugins/Tools/CameraTool/CameraTool.py
python
CameraTool._rotateCamera
(self, x: float, y: float)
Rotate the camera in response to a mouse event. :param x: Amount by which the camera should be rotated horizontally, expressed in pixelunits :param y: Amount by which the camera should be rotated vertically, expressed in pixelunits
Rotate the camera in response to a mouse event.
[ "Rotate", "the", "camera", "in", "response", "to", "a", "mouse", "event", "." ]
def _rotateCamera(self, x: float, y: float) -> None: """Rotate the camera in response to a mouse event. :param x: Amount by which the camera should be rotated horizontally, expressed in pixelunits :param y: Amount by which the camera should be rotated vertically, expressed in pixelunits """ camera = self._scene.getActiveCamera() if not camera or not camera.isEnabled(): return dx = math.radians(x * 180.0) dy = math.radians(y * 180.0) diff = camera.getPosition() - self._origin my = Matrix() my.setByRotationAxis(dx, Vector.Unit_Y) mx = Matrix(my.getData()) mx.rotateByAxis(dy, Vector.Unit_Y.cross(diff).normalized()) n = diff.multiply(mx) try: angle = math.acos(Vector.Unit_Y.dot(n.normalized())) except ValueError: return if angle < 0.1 or angle > math.pi - 0.1: n = diff.multiply(my) n += self._origin camera.setPosition(n) camera.lookAt(self._origin)
[ "def", "_rotateCamera", "(", "self", ",", "x", ":", "float", ",", "y", ":", "float", ")", "->", "None", ":", "camera", "=", "self", ".", "_scene", ".", "getActiveCamera", "(", ")", "if", "not", "camera", "or", "not", "camera", ".", "isEnabled", "(", ...
https://github.com/Ultimaker/Uranium/blob/66da853cd9a04edd3a8a03526fac81e83c03f5aa/plugins/Tools/CameraTool/CameraTool.py#L323-L357
bayespy/bayespy
0e6e6130c888a4295cc9421d61d4ad27b2960ebb
bayespy/inference/vmp/nodes/gaussian.py
python
WrapToGaussianWishart._compute_message_to_parent
(self, index, m_child, u_X_alpha, u_Lambda)
r""" ... Message from the child is :math:`[m_0, m_1, m_2, m_3]`: .. math:: \alpha m_0^T \Lambda x + m_1 \alpha x^T \Lambda x + \mathrm{tr}(\alpha m_2 \Lambda) + m_3 (\log | \alpha \Lambda |) In case of Gaussian-gamma and Wishart parents: Message to the first parent (x, alpha): .. math:: \tilde{m_0} &= \Lambda m_0 \\ \tilde{m_1} &= m_1 \Lambda \\ \tilde{m_2} &= \mathrm{tr}(m_2 \Lambda) \\ \tilde{m_3} &= m_3 \cdot D Message to the second parent (Lambda): .. math:: \tilde{m_0} &= \alpha (\frac{1}{2} m_0 x^T + \frac{1}{2} x m_0^T + m_1 xx^T + m_2) \\ \tilde{m_1} &= m_3
r""" ...
[ "r", "..." ]
def _compute_message_to_parent(self, index, m_child, u_X_alpha, u_Lambda): r""" ... Message from the child is :math:`[m_0, m_1, m_2, m_3]`: .. math:: \alpha m_0^T \Lambda x + m_1 \alpha x^T \Lambda x + \mathrm{tr}(\alpha m_2 \Lambda) + m_3 (\log | \alpha \Lambda |) In case of Gaussian-gamma and Wishart parents: Message to the first parent (x, alpha): .. math:: \tilde{m_0} &= \Lambda m_0 \\ \tilde{m_1} &= m_1 \Lambda \\ \tilde{m_2} &= \mathrm{tr}(m_2 \Lambda) \\ \tilde{m_3} &= m_3 \cdot D Message to the second parent (Lambda): .. math:: \tilde{m_0} &= \alpha (\frac{1}{2} m_0 x^T + \frac{1}{2} x m_0^T + m_1 xx^T + m_2) \\ \tilde{m_1} &= m_3 """ if index == 0: if self.wishart: # Message to Gaussian-gamma (isotropic) Lambda = u_Lambda[0] D = np.prod(self.dims[0]) m0 = linalg.mvdot(Lambda, m_child[0], ndim=self.ndim) m1 = Lambda * misc.add_trailing_axes(m_child[1], 2*self.ndim) m2 = linalg.inner(Lambda, m_child[2], ndim=2*self.ndim) m3 = D * m_child[3] m = [m0, m1, m2, m3] return m else: # Message to Gaussian-Wishart raise NotImplementedError() elif index == 1: if self.wishart: # Message to Wishart alpha_x = u_X_alpha[0] alpha_xx = u_X_alpha[1] alpha = u_X_alpha[2] m0 = (0.5*linalg.outer(alpha_x, m_child[0], ndim=self.ndim) + 0.5*linalg.outer(m_child[0], alpha_x, ndim=self.ndim) + alpha_xx * misc.add_trailing_axes(m_child[1], 2*self.ndim) + misc.add_trailing_axes(alpha, 2*self.ndim) * m_child[2]) m1 = m_child[3] m = [m0, m1] return m else: # Message to gamma (isotropic) raise NotImplementedError() else: raise ValueError("Invalid parent index")
[ "def", "_compute_message_to_parent", "(", "self", ",", "index", ",", "m_child", ",", "u_X_alpha", ",", "u_Lambda", ")", ":", "if", "index", "==", "0", ":", "if", "self", ".", "wishart", ":", "# Message to Gaussian-gamma (isotropic)", "Lambda", "=", "u_Lambda", ...
https://github.com/bayespy/bayespy/blob/0e6e6130c888a4295cc9421d61d4ad27b2960ebb/bayespy/inference/vmp/nodes/gaussian.py#L2423-L2488
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/asyncio/base_events.py
python
BaseEventLoop.shutdown_asyncgens
(self)
Shutdown all active asynchronous generators.
Shutdown all active asynchronous generators.
[ "Shutdown", "all", "active", "asynchronous", "generators", "." ]
async def shutdown_asyncgens(self): """Shutdown all active asynchronous generators.""" self._asyncgens_shutdown_called = True if not len(self._asyncgens): # If Python version is <3.6 or we don't have any asynchronous # generators alive. return closing_agens = list(self._asyncgens) self._asyncgens.clear() results = await tasks.gather( *[ag.aclose() for ag in closing_agens], return_exceptions=True, loop=self) for result, agen in zip(results, closing_agens): if isinstance(result, Exception): self.call_exception_handler({ 'message': f'an error occurred during closing of ' f'asynchronous generator {agen!r}', 'exception': result, 'asyncgen': agen })
[ "async", "def", "shutdown_asyncgens", "(", "self", ")", ":", "self", ".", "_asyncgens_shutdown_called", "=", "True", "if", "not", "len", "(", "self", ".", "_asyncgens", ")", ":", "# If Python version is <3.6 or we don't have any asynchronous", "# generators alive.", "re...
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/asyncio/base_events.py#L524-L548
CGATOxford/cgat
326aad4694bdfae8ddc194171bb5d73911243947
CGAT/Counts.py
python
Counts.transform
(self, method="vst", design=None, inplace=True, blind=True)
perform transformation on counts table current methods are: - deseq2 variance stabalising transformation - deseq rlog transformation Need to supply a design table if not using "blind"
perform transformation on counts table current methods are: - deseq2 variance stabalising transformation - deseq rlog transformation
[ "perform", "transformation", "on", "counts", "table", "current", "methods", "are", ":", "-", "deseq2", "variance", "stabalising", "transformation", "-", "deseq", "rlog", "transformation" ]
def transform(self, method="vst", design=None, inplace=True, blind=True): ''' perform transformation on counts table current methods are: - deseq2 variance stabalising transformation - deseq rlog transformation Need to supply a design table if not using "blind" ''' assert method in ["vst", "rlog"], ("method must be one of" "[vst, rlog]") method2function = {"vst": "varianceStabilizingTransformation", "rlog": "rlog"} t_function = method2function[method] r_counts = pandas2ri.py2ri(self.table) if not blind: assert design, ("if not using blind must supply a design table " "(a CGAT.Expression.ExperimentalDesign object") # currently this only accepts "~group" design transform = R(''' function(df, design){ suppressMessages(library('DESeq2')) dds <- suppressMessages(DESeqDataSetFromMatrix( countData= df, colData = design, design = ~group)) transformed <- suppressMessages(%(t_function)s(dds, blind=FALSE)) transformed_df <- as.data.frame(assay(transformed)) return(transformed_df) }''' % locals()) r_design = pandas2ri.py2ri(design.table) df = pandas2ri.ri2py(transform(r_counts, r_design)) else: transform = R(''' function(df){ suppressMessages(library('DESeq2')) design = data.frame(row.names = colnames(df), group = seq(1, length(colnames(df)))) dds <- suppressMessages(DESeqDataSetFromMatrix( countData= df, colData = design, design = ~group)) transformed <- suppressMessages(%(t_function)s(dds, blind=TRUE)) transformed_df <- as.data.frame(assay(transformed)) return(transformed_df) }''' % locals()) df = pandas2ri.ri2py(transform(r_counts)) # losing rownames for some reason during the conversion?! df.index = self.table.index if inplace: self.table = df # R replaces "-" in column names with ".". Revert back! self.table.columns = [x.replace(".", "-") for x in self.table.columns] else: tmp_counts = self.clone() tmp_counts.table = df tmp_counts.table.columns = [x.replace(".", "-") for x in tmp_counts.table.columns] return tmp_counts
[ "def", "transform", "(", "self", ",", "method", "=", "\"vst\"", ",", "design", "=", "None", ",", "inplace", "=", "True", ",", "blind", "=", "True", ")", ":", "assert", "method", "in", "[", "\"vst\"", ",", "\"rlog\"", "]", ",", "(", "\"method must be on...
https://github.com/CGATOxford/cgat/blob/326aad4694bdfae8ddc194171bb5d73911243947/CGAT/Counts.py#L252-L328
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1beta1_endpoint_conditions.py
python
V1beta1EndpointConditions.terminating
(self, terminating)
Sets the terminating of this V1beta1EndpointConditions. terminating indicates that this endpoint is terminating. A nil value indicates an unknown state. Consumers should interpret this unknown state to mean that the endpoint is not terminating. This field can be enabled with the EndpointSliceTerminatingCondition feature gate. # noqa: E501 :param terminating: The terminating of this V1beta1EndpointConditions. # noqa: E501 :type: bool
Sets the terminating of this V1beta1EndpointConditions.
[ "Sets", "the", "terminating", "of", "this", "V1beta1EndpointConditions", "." ]
def terminating(self, terminating): """Sets the terminating of this V1beta1EndpointConditions. terminating indicates that this endpoint is terminating. A nil value indicates an unknown state. Consumers should interpret this unknown state to mean that the endpoint is not terminating. This field can be enabled with the EndpointSliceTerminatingCondition feature gate. # noqa: E501 :param terminating: The terminating of this V1beta1EndpointConditions. # noqa: E501 :type: bool """ self._terminating = terminating
[ "def", "terminating", "(", "self", ",", "terminating", ")", ":", "self", ".", "_terminating", "=", "terminating" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1beta1_endpoint_conditions.py#L123-L132
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
lib/hypervisor/hv_kvm/__init__.py
python
KVMHypervisor.HotplugSupported
(self, instance)
Checks if hotplug is generally supported. Hotplug is *not* supported in case of: - qemu versions < 1.7 (where all qmp related commands are supported) - for stopped instances @raise errors.HypervisorError: in one of the previous cases
Checks if hotplug is generally supported.
[ "Checks", "if", "hotplug", "is", "generally", "supported", "." ]
def HotplugSupported(self, instance): """Checks if hotplug is generally supported. Hotplug is *not* supported in case of: - qemu versions < 1.7 (where all qmp related commands are supported) - for stopped instances @raise errors.HypervisorError: in one of the previous cases """ try: version = self.qmp.GetVersion() except errors.HypervisorError: raise errors.HotplugError("Instance is probably down") #TODO: delegate more fine-grained checks to VerifyHotplugSupport if version < (1, 7, 0): raise errors.HotplugError("Hotplug not supported for qemu versions < 1.7")
[ "def", "HotplugSupported", "(", "self", ",", "instance", ")", ":", "try", ":", "version", "=", "self", ".", "qmp", ".", "GetVersion", "(", ")", "except", "errors", ".", "HypervisorError", ":", "raise", "errors", ".", "HotplugError", "(", "\"Instance is proba...
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/hypervisor/hv_kvm/__init__.py#L2144-L2162
mozman/ezdxf
59d0fc2ea63f5cf82293428f5931da7e9f9718e9
src/ezdxf/render/trace.py
python
LinearTrace.is_started
(self)
return bool(self._stations)
`True` if at least one station exist.
`True` if at least one station exist.
[ "True", "if", "at", "least", "one", "station", "exist", "." ]
def is_started(self) -> bool: """`True` if at least one station exist.""" return bool(self._stations)
[ "def", "is_started", "(", "self", ")", "->", "bool", ":", "return", "bool", "(", "self", ".", "_stations", ")" ]
https://github.com/mozman/ezdxf/blob/59d0fc2ea63f5cf82293428f5931da7e9f9718e9/src/ezdxf/render/trace.py#L141-L143
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/distutils/util.py
python
execute
(func, args, msg=None, verbose=0, dry_run=0)
Perform some action that affects the outside world (eg. by writing to the filesystem). Such actions are special because they are disabled by the 'dry_run' flag. This method takes care of all that bureaucracy for you; all you have to do is supply the function to call and an argument tuple for it (to embody the "external action" being performed), and an optional message to print.
Perform some action that affects the outside world (eg. by writing to the filesystem). Such actions are special because they are disabled by the 'dry_run' flag. This method takes care of all that bureaucracy for you; all you have to do is supply the function to call and an argument tuple for it (to embody the "external action" being performed), and an optional message to print.
[ "Perform", "some", "action", "that", "affects", "the", "outside", "world", "(", "eg", ".", "by", "writing", "to", "the", "filesystem", ")", ".", "Such", "actions", "are", "special", "because", "they", "are", "disabled", "by", "the", "dry_run", "flag", ".",...
def execute (func, args, msg=None, verbose=0, dry_run=0): """Perform some action that affects the outside world (eg. by writing to the filesystem). Such actions are special because they are disabled by the 'dry_run' flag. This method takes care of all that bureaucracy for you; all you have to do is supply the function to call and an argument tuple for it (to embody the "external action" being performed), and an optional message to print. """ if msg is None: msg = "%s%r" % (func.__name__, args) if msg[-2:] == ',)': # correct for singleton tuple msg = msg[0:-2] + ')' log.info(msg) if not dry_run: func(*args)
[ "def", "execute", "(", "func", ",", "args", ",", "msg", "=", "None", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ")", ":", "if", "msg", "is", "None", ":", "msg", "=", "\"%s%r\"", "%", "(", "func", ".", "__name__", ",", "args", ")", "if"...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/distutils/util.py#L293-L309
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_box.py
python
Box.quartilemethod
(self)
return self["quartilemethod"]
Sets the method used to compute the sample's Q1 and Q3 quartiles. The "linear" method uses the 25th percentile for Q1 and 75th percentile for Q3 as computed using method #10 (listed on http://www.amstat.org/publications/jse/v14n3/langford.html). The "exclusive" method uses the median to divide the ordered dataset into two halves if the sample is odd, it does not include the median in either half - Q1 is then the median of the lower half and Q3 the median of the upper half. The "inclusive" method also uses the median to divide the ordered dataset into two halves but if the sample is odd, it includes the median in both halves - Q1 is then the median of the lower half and Q3 the median of the upper half. The 'quartilemethod' property is an enumeration that may be specified as: - One of the following enumeration values: ['linear', 'exclusive', 'inclusive'] Returns ------- Any
Sets the method used to compute the sample's Q1 and Q3 quartiles. The "linear" method uses the 25th percentile for Q1 and 75th percentile for Q3 as computed using method #10 (listed on http://www.amstat.org/publications/jse/v14n3/langford.html). The "exclusive" method uses the median to divide the ordered dataset into two halves if the sample is odd, it does not include the median in either half - Q1 is then the median of the lower half and Q3 the median of the upper half. The "inclusive" method also uses the median to divide the ordered dataset into two halves but if the sample is odd, it includes the median in both halves - Q1 is then the median of the lower half and Q3 the median of the upper half. The 'quartilemethod' property is an enumeration that may be specified as: - One of the following enumeration values: ['linear', 'exclusive', 'inclusive']
[ "Sets", "the", "method", "used", "to", "compute", "the", "sample", "s", "Q1", "and", "Q3", "quartiles", ".", "The", "linear", "method", "uses", "the", "25th", "percentile", "for", "Q1", "and", "75th", "percentile", "for", "Q3", "as", "computed", "using", ...
def quartilemethod(self): """ Sets the method used to compute the sample's Q1 and Q3 quartiles. The "linear" method uses the 25th percentile for Q1 and 75th percentile for Q3 as computed using method #10 (listed on http://www.amstat.org/publications/jse/v14n3/langford.html). The "exclusive" method uses the median to divide the ordered dataset into two halves if the sample is odd, it does not include the median in either half - Q1 is then the median of the lower half and Q3 the median of the upper half. The "inclusive" method also uses the median to divide the ordered dataset into two halves but if the sample is odd, it includes the median in both halves - Q1 is then the median of the lower half and Q3 the median of the upper half. The 'quartilemethod' property is an enumeration that may be specified as: - One of the following enumeration values: ['linear', 'exclusive', 'inclusive'] Returns ------- Any """ return self["quartilemethod"]
[ "def", "quartilemethod", "(", "self", ")", ":", "return", "self", "[", "\"quartilemethod\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_box.py#L1242-L1265
mher/flower
47a0eb937a1a132a9cb5b2e137d96b93e4cdc89e
flower/command.py
python
flower
(ctx, tornado_argv)
Web based tool for monitoring and administrating Celery clusters.
Web based tool for monitoring and administrating Celery clusters.
[ "Web", "based", "tool", "for", "monitoring", "and", "administrating", "Celery", "clusters", "." ]
def flower(ctx, tornado_argv): """Web based tool for monitoring and administrating Celery clusters.""" warn_about_celery_args_used_in_flower_command(ctx, tornado_argv) apply_env_options() apply_options(sys.argv[0], tornado_argv) extract_settings() setup_logging() app = ctx.obj.app flower = Flower(capp=app, options=options, **settings) atexit.register(flower.stop) def sigterm_handler(signal, frame): logger.info('SIGTERM detected, shutting down') sys.exit(0) signal.signal(signal.SIGTERM, sigterm_handler) print_banner(app, 'ssl_options' in settings) try: flower.start() except (KeyboardInterrupt, SystemExit): pass
[ "def", "flower", "(", "ctx", ",", "tornado_argv", ")", ":", "warn_about_celery_args_used_in_flower_command", "(", "ctx", ",", "tornado_argv", ")", "apply_env_options", "(", ")", "apply_options", "(", "sys", ".", "argv", "[", "0", "]", ",", "tornado_argv", ")", ...
https://github.com/mher/flower/blob/47a0eb937a1a132a9cb5b2e137d96b93e4cdc89e/flower/command.py#L32-L55
freedombox/FreedomBox
335a7f92cc08f27981f838a7cddfc67740598e54
plinth/setup.py
python
Helper.run_in_thread
(self)
Execute the setup process in a thread.
Execute the setup process in a thread.
[ "Execute", "the", "setup", "process", "in", "a", "thread", "." ]
def run_in_thread(self): """Execute the setup process in a thread.""" thread = threading.Thread(target=self._run) thread.start()
[ "def", "run_in_thread", "(", "self", ")", ":", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_run", ")", "thread", ".", "start", "(", ")" ]
https://github.com/freedombox/FreedomBox/blob/335a7f92cc08f27981f838a7cddfc67740598e54/plinth/setup.py#L43-L46
WebThingsIO/webthing-python
ddb74332eb6742f5d5332de8485060316ad2735e
webthing/property.py
python
Property.as_property_description
(self)
return description
Get the property description. Returns a dictionary describing the property.
Get the property description.
[ "Get", "the", "property", "description", "." ]
def as_property_description(self): """ Get the property description. Returns a dictionary describing the property. """ description = deepcopy(self.metadata) if 'links' not in description: description['links'] = [] description['links'].append( { 'rel': 'property', 'href': self.href_prefix + self.href, } ) return description
[ "def", "as_property_description", "(", "self", ")", ":", "description", "=", "deepcopy", "(", "self", ".", "metadata", ")", "if", "'links'", "not", "in", "description", ":", "description", "[", "'links'", "]", "=", "[", "]", "description", "[", "'links'", ...
https://github.com/WebThingsIO/webthing-python/blob/ddb74332eb6742f5d5332de8485060316ad2735e/webthing/property.py#L48-L65
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/mailbox.py
python
MH.get_string
(self, key)
Return a string representation or raise a KeyError.
Return a string representation or raise a KeyError.
[ "Return", "a", "string", "representation", "or", "raise", "a", "KeyError", "." ]
def get_string(self, key): """Return a string representation or raise a KeyError.""" try: if self._locked: f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') except IOError, e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise try: if self._locked: _lock_file(f) try: return f.read() finally: if self._locked: _unlock_file(f) finally: f.close()
[ "def", "get_string", "(", "self", ",", "key", ")", ":", "try", ":", "if", "self", ".", "_locked", ":", "f", "=", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "str", "(", "key", ")", ")", ",", "'r+'", ")", "else...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/mailbox.py#L971-L992
mozilla/mozillians
bd5da47fef01e4e09d3bb8cb0799735bdfbeb3f9
mozillians/groups/models.py
python
Group.get_functional_areas
(cls)
return cls.objects.visible().filter(functional_area=True)
Return all visible groups that are functional areas.
Return all visible groups that are functional areas.
[ "Return", "all", "visible", "groups", "that", "are", "functional", "areas", "." ]
def get_functional_areas(cls): """Return all visible groups that are functional areas.""" return cls.objects.visible().filter(functional_area=True)
[ "def", "get_functional_areas", "(", "cls", ")", ":", "return", "cls", ".", "objects", ".", "visible", "(", ")", ".", "filter", "(", "functional_area", "=", "True", ")" ]
https://github.com/mozilla/mozillians/blob/bd5da47fef01e4e09d3bb8cb0799735bdfbeb3f9/mozillians/groups/models.py#L274-L276
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
tensorflow_dl_models/research/learned_optimizer/problems/problem_generator.py
python
FullyConnected.accuracy
(self, params, data, labels)
return tf.contrib.metrics.accuracy(predictions, tf.cast(labels, tf.int32))
Computes the accuracy (fraction of correct classifications). Args: params: List of parameter tensors or variables data: Batch of features with samples along the first dimension labels: Vector of labels with the same number of samples as the data Returns: accuracy: Fraction of correct classifications across the batch
Computes the accuracy (fraction of correct classifications).
[ "Computes", "the", "accuracy", "(", "fraction", "of", "correct", "classifications", ")", "." ]
def accuracy(self, params, data, labels): """Computes the accuracy (fraction of correct classifications). Args: params: List of parameter tensors or variables data: Batch of features with samples along the first dimension labels: Vector of labels with the same number of samples as the data Returns: accuracy: Fraction of correct classifications across the batch """ predictions = self.argmax(self.activation(self.inference(params, data))) return tf.contrib.metrics.accuracy(predictions, tf.cast(labels, tf.int32))
[ "def", "accuracy", "(", "self", ",", "params", ",", "data", ",", "labels", ")", ":", "predictions", "=", "self", ".", "argmax", "(", "self", ".", "activation", "(", "self", ".", "inference", "(", "params", ",", "data", ")", ")", ")", "return", "tf", ...
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/tensorflow_dl_models/research/learned_optimizer/problems/problem_generator.py#L349-L361
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/db/transaction.py
python
set_dirty
(using=None)
Sets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether there are open changes waiting for commit.
Sets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether there are open changes waiting for commit.
[ "Sets", "a", "dirty", "flag", "for", "the", "current", "thread", "and", "code", "streak", ".", "This", "can", "be", "used", "to", "decide", "in", "a", "managed", "block", "of", "code", "to", "decide", "whether", "there", "are", "open", "changes", "waitin...
def set_dirty(using=None): """ Sets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether there are open changes waiting for commit. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] connection.set_dirty()
[ "def", "set_dirty", "(", "using", "=", "None", ")", ":", "if", "using", "is", "None", ":", "using", "=", "DEFAULT_DB_ALIAS", "connection", "=", "connections", "[", "using", "]", "connection", ".", "set_dirty", "(", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/db/transaction.py#L78-L87
biocore/qiime
76d633c0389671e93febbe1338b5ded658eba31f
qiime/summarize_taxa.py
python
add_summary_mapping
(otu_table, mapping, level, md_as_string=False, md_identifier='taxonomy')
return summary, taxon_order
Returns sample summary of sample counts by taxon Summary is keyed by sample_id, valued by otu counts for each taxon Taxon order is a list of taxons where idx n corresponds to otu count idx n
Returns sample summary of sample counts by taxon
[ "Returns", "sample", "summary", "of", "sample", "counts", "by", "taxon" ]
def add_summary_mapping(otu_table, mapping, level, md_as_string=False, md_identifier='taxonomy'): """Returns sample summary of sample counts by taxon Summary is keyed by sample_id, valued by otu counts for each taxon Taxon order is a list of taxons where idx n corresponds to otu count idx n """ counts_by_consensus, sample_map = sum_counts_by_consensus(otu_table, level, "Other", md_as_string, md_identifier) summary = defaultdict(list) for row in mapping: # grab otu idx if the sample exists, otherwise ignore it sample_id = row[0] if sample_id not in sample_map: continue otu_idx = sample_map[sample_id] for consensus, counts in sorted(counts_by_consensus.items()): summary[sample_id].append(counts[otu_idx]) taxon_order = sorted(counts_by_consensus.keys()) return summary, taxon_order
[ "def", "add_summary_mapping", "(", "otu_table", ",", "mapping", ",", "level", ",", "md_as_string", "=", "False", ",", "md_identifier", "=", "'taxonomy'", ")", ":", "counts_by_consensus", ",", "sample_map", "=", "sum_counts_by_consensus", "(", "otu_table", ",", "le...
https://github.com/biocore/qiime/blob/76d633c0389671e93febbe1338b5ded658eba31f/qiime/summarize_taxa.py#L122-L151
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/multifile.py
python
MultiFile.next
(self)
return 1
[]
def next(self): while self.readline(): pass if self.level > 1 or self.last: return 0 self.level = 0 self.last = 0 if self.seekable: self.start = self.fp.tell() return 1
[ "def", "next", "(", "self", ")", ":", "while", "self", ".", "readline", "(", ")", ":", "pass", "if", "self", ".", "level", ">", "1", "or", "self", ".", "last", ":", "return", "0", "self", ".", "level", "=", "0", "self", ".", "last", "=", "0", ...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/multifile.py#L123-L131
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/email/_header_value_parser.py
python
get_comment
(value)
return comment, value[1:]
comment = "(" *([FWS] ccontent) [FWS] ")" ccontent = ctext / quoted-pair / comment We handle nested comments here, and quoted-pair in our qp-ctext routine.
comment = "(" *([FWS] ccontent) [FWS] ")" ccontent = ctext / quoted-pair / comment
[ "comment", "=", "(", "*", "(", "[", "FWS", "]", "ccontent", ")", "[", "FWS", "]", ")", "ccontent", "=", "ctext", "/", "quoted", "-", "pair", "/", "comment" ]
def get_comment(value): """comment = "(" *([FWS] ccontent) [FWS] ")" ccontent = ctext / quoted-pair / comment We handle nested comments here, and quoted-pair in our qp-ctext routine. """ if value and value[0] != '(': raise errors.HeaderParseError( "expected '(' but found '{}'".format(value)) comment = Comment() value = value[1:] while value and value[0] != ")": if value[0] in WSP: token, value = get_fws(value) elif value[0] == '(': token, value = get_comment(value) else: token, value = get_qp_ctext(value) comment.append(token) if not value: comment.defects.append(errors.InvalidHeaderDefect( "end of header inside comment")) return comment, value return comment, value[1:]
[ "def", "get_comment", "(", "value", ")", ":", "if", "value", "and", "value", "[", "0", "]", "!=", "'('", ":", "raise", "errors", ".", "HeaderParseError", "(", "\"expected '(' but found '{}'\"", ".", "format", "(", "value", ")", ")", "comment", "=", "Commen...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/email/_header_value_parser.py#L1598-L1621
pybliometrics-dev/pybliometrics
26ad9656e5a1d4c80774937706a0df85776f07d0
pybliometrics/scopus/abstract_retrieval.py
python
_parse_pages
(self, unicode=False)
return pages
Auxiliary function to parse and format page range of a document.
Auxiliary function to parse and format page range of a document.
[ "Auxiliary", "function", "to", "parse", "and", "format", "page", "range", "of", "a", "document", "." ]
def _parse_pages(self, unicode=False): """Auxiliary function to parse and format page range of a document.""" if self.pageRange: pages = f'pp. {self.pageRange}' elif self.startingPage: pages = f'pp. {self.startingPage}-{self.endingPage}' else: pages = '(no pages found)' if unicode: pages = f'{pages}' return pages
[ "def", "_parse_pages", "(", "self", ",", "unicode", "=", "False", ")", ":", "if", "self", ".", "pageRange", ":", "pages", "=", "f'pp. {self.pageRange}'", "elif", "self", ".", "startingPage", ":", "pages", "=", "f'pp. {self.startingPage}-{self.endingPage}'", "else"...
https://github.com/pybliometrics-dev/pybliometrics/blob/26ad9656e5a1d4c80774937706a0df85776f07d0/pybliometrics/scopus/abstract_retrieval.py#L840-L850
makehumancommunity/makehuman
8006cf2cc851624619485658bb933a4244bbfd7c
makehuman/core/transformations.py
python
arcball_map_to_sphere
(point, center, radius)
Return unit sphere coordinates from window coordinates.
Return unit sphere coordinates from window coordinates.
[ "Return", "unit", "sphere", "coordinates", "from", "window", "coordinates", "." ]
def arcball_map_to_sphere(point, center, radius): """Return unit sphere coordinates from window coordinates.""" v0 = (point[0] - center[0]) / radius v1 = (center[1] - point[1]) / radius n = v0*v0 + v1*v1 if n > 1.0: # position outside of sphere n = math.sqrt(n) return numpy.array([v0/n, v1/n, 0.0]) else: return numpy.array([v0, v1, math.sqrt(1.0 - n)])
[ "def", "arcball_map_to_sphere", "(", "point", ",", "center", ",", "radius", ")", ":", "v0", "=", "(", "point", "[", "0", "]", "-", "center", "[", "0", "]", ")", "/", "radius", "v1", "=", "(", "center", "[", "1", "]", "-", "point", "[", "1", "]"...
https://github.com/makehumancommunity/makehuman/blob/8006cf2cc851624619485658bb933a4244bbfd7c/makehuman/core/transformations.py#L1649-L1659
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/mako/exceptions.py
python
RichTraceback._init
(self, trcback)
return new_trcback
format a traceback from sys.exc_info() into 7-item tuples, containing the regular four traceback tuple items, plus the original template filename, the line number adjusted relative to the template source, and code line from that line number of the template.
format a traceback from sys.exc_info() into 7-item tuples, containing the regular four traceback tuple items, plus the original template filename, the line number adjusted relative to the template source, and code line from that line number of the template.
[ "format", "a", "traceback", "from", "sys", ".", "exc_info", "()", "into", "7", "-", "item", "tuples", "containing", "the", "regular", "four", "traceback", "tuple", "items", "plus", "the", "original", "template", "filename", "the", "line", "number", "adjusted",...
def _init(self, trcback): """format a traceback from sys.exc_info() into 7-item tuples, containing the regular four traceback tuple items, plus the original template filename, the line number adjusted relative to the template source, and code line from that line number of the template.""" import mako.template mods = {} rawrecords = traceback.extract_tb(trcback) new_trcback = [] for filename, lineno, function, line in rawrecords: if not line: line = "" try: (line_map, template_lines, template_filename) = mods[filename] except KeyError: try: info = mako.template._get_module_info(filename) module_source = info.code template_source = info.source template_filename = ( info.template_filename or info.template_uri or filename ) except KeyError: # A normal .py file (not a Template) if not compat.py3k: try: fp = open(filename, "rb") encoding = util.parse_encoding(fp) fp.close() except IOError: encoding = None if encoding: line = line.decode(encoding) else: line = line.decode("ascii", "replace") new_trcback.append( ( filename, lineno, function, line, None, None, None, None, ) ) continue template_ln = 1 mtm = mako.template.ModuleInfo source_map = mtm.get_module_source_metadata( module_source, full_line_map=True ) line_map = source_map["full_line_map"] template_lines = [ line_ for line_ in template_source.split("\n") ] mods[filename] = (line_map, template_lines, template_filename) template_ln = line_map[lineno - 1] if template_ln <= len(template_lines): template_line = template_lines[template_ln - 1] else: template_line = None new_trcback.append( ( filename, lineno, function, line, template_filename, template_ln, template_line, template_source, ) ) if not self.source: for l in range(len(new_trcback) - 1, 0, -1): if new_trcback[l][5]: self.source = new_trcback[l][7] self.lineno = new_trcback[l][5] break else: if new_trcback: try: # A normal .py file (not a Template) fp = open(new_trcback[-1][0], "rb") encoding = util.parse_encoding(fp) if compat.py3k and not encoding: encoding = "utf-8" fp.seek(0) self.source = fp.read() fp.close() if encoding: self.source = self.source.decode(encoding) except IOError: self.source = "" self.lineno = new_trcback[-1][1] return new_trcback
[ "def", "_init", "(", "self", ",", "trcback", ")", ":", "import", "mako", ".", "template", "mods", "=", "{", "}", "rawrecords", "=", "traceback", ".", "extract_tb", "(", "trcback", ")", "new_trcback", "=", "[", "]", "for", "filename", ",", "lineno", ","...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/mako/exceptions.py#L147-L251
crypto101/book
7de09b9643183d654b7a02d1a6c3a425a07c2c7c
src/admonition_templates.py
python
latex_visit_canned_admonition_node
(self, node)
[]
def latex_visit_canned_admonition_node(self, node): node_title = node["title"] if node_title is None: node_title = "" self.body.append('\n\\begin{%s}{%s}{%s}' % (node.box_class(), node["type"], node_title)) if not node_title: # when there's no title, remove the spacing self.body.append("\n\\vspace{-1.4\\baselineskip}") if has_latex_floats_counter: self.no_latex_floats += 1
[ "def", "latex_visit_canned_admonition_node", "(", "self", ",", "node", ")", ":", "node_title", "=", "node", "[", "\"title\"", "]", "if", "node_title", "is", "None", ":", "node_title", "=", "\"\"", "self", ".", "body", ".", "append", "(", "'\\n\\\\begin{%s}{%s}...
https://github.com/crypto101/book/blob/7de09b9643183d654b7a02d1a6c3a425a07c2c7c/src/admonition_templates.py#L39-L48